vector listlengths 1.02k 1.02k | text stringlengths 2 11.8k |
|---|---|
[
0.05942314,
-0.018312974,
-0.0047445935,
-0.00051080325,
-0.022970775,
0.010096726,
0.022695936,
-0.0036217305,
-0.01384322,
0.03564231,
0.054418173,
-0.035931617,
0.019151956,
-0.048718873,
0.007033715,
0.050541494,
0.008845485,
-0.04194915,
-0.027397133,
0.009843585,
-0.002... | Quantizing a model in 4-bit reduces your memory-usage by 4x, and for large models, set device_map="auto" to efficiently use the GPUs available:
from transformers import AutoModelForCausalLM
model_4bit = AutoModelForCausalLM.from_pretrained("bigscience/bloom-1b7", device_map="auto", load_in_4bit=True)
By default, all ... |
[
0.056728806,
-0.040312976,
-0.012130223,
-0.003187295,
-0.02712649,
0.0072794794,
0.038913593,
-0.0068051694,
-0.05183097,
0.050942898,
0.027906913,
-0.03684143,
0.0037305648,
-0.03541514,
0.0052745948,
0.032939307,
0.0068489,
-0.039344173,
-0.031943593,
0.0019964746,
-0.0056... | Training with 8-bit and 4-bit weights are only supported for training extra parameters.
You can check your memory footprint with the get_memory_footprint method:
py
print(model.get_memory_footprint())
Quantized models can be loaded from the [~PreTrainedModel.from_pretrained] method without needing to specify the load_... |
[
0.05519016,
-0.014642873,
-0.03189338,
0.004846332,
-0.02477253,
-0.0068557872,
0.052124042,
-0.01619026,
-0.0072999448,
0.024156442,
-0.0013136676,
-0.03834083,
-0.0018124494,
-0.059259217,
0.018926844,
0.022050275,
0.03060389,
-0.04275375,
-0.03808293,
0.01551686,
0.0192850... | If you have bitsandbytes>=0.41.3, you can serialize 4-bit models and push them on Hugging Face Hub. Simply call model.push_to_hub() after loading it in 4-bit precision. You can also save the serialized 4-bit models locally with model.save_pretrained() command.
Training with 8-bit and 4-bit weights are only supported... |
[
0.011089473,
-0.005473554,
-0.0021392193,
-0.036115717,
-0.041900225,
-0.003057098,
0.013577111,
-0.0214896,
-0.033508193,
0.046995386,
0.011793804,
-0.037614293,
-0.0026281301,
-0.0248614,
0.0127229225,
0.04471755,
0.004731758,
-0.046156183,
-0.016903954,
0.0010789757,
-0.00... | from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("{your_username}/bloom-560m-8bit", device_map="auto")
8-bit
Learn more about the details of 8-bit quantization in this blog post! |
[
0.03525984,
-0.03473488,
-0.0038642918,
-0.033801615,
-0.021829603,
-0.008625391,
0.03584313,
-0.036951378,
-0.0014436411,
0.059262197,
-0.006802612,
-0.02050262,
0.011024169,
-0.058678906,
0.014793675,
0.037826315,
-0.005060035,
-0.048996303,
-0.0600788,
-0.022092083,
0.0256... | This section explores some of the specific features of 8-bit models, such as offloading, outlier thresholds, skipping module conversion, and finetuning.
Offloading
8-bit models can offload weights between the CPU and GPU to support fitting very large models into memory. The weights dispatched to the CPU are actually st... |
[
0.010751016,
0.00019902401,
0.006878419,
-0.027498795,
-0.04148628,
-0.010326928,
0.0018553875,
-0.026605977,
-0.030415334,
0.05910455,
0.008258566,
-0.04776576,
0.022231169,
-0.0565749,
0.015401111,
0.035980567,
0.0016842639,
-0.031159349,
-0.04615869,
-0.00076122035,
-0.002... | from transformers import AutoModelForCausalLM, BitsAndBytesConfig
model_id = "bigscience/bloom-1b7"
quantization_config = BitsAndBytesConfig(
llm_int8_threshold=10,
)
model_8bit = AutoModelForCausalLM.from_pretrained(
model_id,
device_map=device_map,
quantization_config=quantization_config,
) |
[
0.008199476,
-0.0053391936,
-0.0062962878,
-0.023821017,
-0.040014613,
-0.0016804158,
0.0014649779,
-0.016296275,
-0.029262887,
0.05497609,
0.006820673,
-0.043182928,
0.019977972,
-0.057058964,
0.014308745,
0.045383144,
-0.0037587043,
-0.04021997,
-0.056120206,
-0.004154743,
... | from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
model_id = "bigscience/bloom-1b7"
quantization_config = BitsAndBytesConfig(
llm_int8_skip_modules=["lm_head"],
)
model_8bit = AutoModelForCausalLM.from_pretrained(
model_id,
device_map="auto",
quantization_config=quantizati... |
[
0.043711256,
0.0145825045,
-0.0008144195,
0.020260327,
-0.035502706,
0.01778036,
0.044233356,
0.02197165,
-0.027511697,
0.020564886,
0.06172366,
-0.012958198,
0.040375628,
-0.025742363,
-0.015430915,
0.035647735,
0.007903993,
-0.03799718,
-0.022160186,
0.008230305,
0.02626446... | Finetuning
With the PEFT library, you can finetune large models like flan-t5-large and facebook/opt-6.7b with 8-bit quantization. You don't need to pass the device_map parameter for training because it'll automatically load your model on a GPU. However, you can still customize the device map with the device_map paramet... |
[
0.0014692073,
0.0004402503,
0.00041593413,
0.007351156,
-0.015808057,
-0.0007687316,
0.018770361,
-0.017036662,
-0.04231863,
0.045758728,
0.00827261,
-0.029704949,
0.009624076,
-0.077866286,
0.010620612,
0.04592254,
-0.0027882517,
-0.04354724,
-0.03786835,
0.0015767104,
-0.00... | from transformers import AutoModelForCausalLM, BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True) |
[
0.02848285,
0.007969489,
-0.009975007,
-0.0038570527,
-0.015428211,
-0.02767163,
0.030826377,
-0.0056109414,
-0.038097315,
0.04608934,
-0.008465235,
-0.033981122,
0.021587476,
-0.028182399,
-0.015938979,
0.039509438,
-0.02281933,
-0.028693167,
-0.041432332,
0.004022301,
0.012... |
Design a custom device map to fit everything on your GPU except for the lm_head, which you'll dispatch to the CPU:
py
device_map = {
"transformer.word_embeddings": 0,
"transformer.word_embeddings_layernorm": 0,
"lm_head": "cpu",
"transformer.h": 0,
"transformer.ln_f": 0,
}
Now load your model with... |
[
0.019358087,
0.014398216,
-0.018088944,
0.003641494,
-0.033610426,
-0.025937213,
0.030021813,
-0.0022811764,
-0.0038293127,
0.07428137,
-0.0019365383,
-0.012662261,
0.030867908,
-0.036528,
-0.03133472,
0.037753377,
-0.003811078,
-0.05450024,
-0.0377242,
0.022290248,
0.0144492... | Skip module conversion
For some models, like Jukebox, you don't need to quantize every module to 8-bit which can actually cause instability. With Jukebox, there are several lm_head modules that should be skipped using the llm_int8_skip_modules parameter in [BitsAndBytesConfig]: |
[
0.0489953,
-0.033965893,
-0.012220306,
-0.0039605484,
-0.016597943,
0.024540428,
0.01094409,
0.018722594,
-0.036789253,
0.038500383,
0.039897803,
-0.024326539,
0.027934166,
-0.046000827,
-0.0077000763,
0.043890435,
-0.014801258,
-0.038842607,
-0.016483868,
0.016127381,
-0.013... | import torch
from transformers import BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
Normal Float 4 (NF4)
NF4 is a 4-bit data type from the QLoRA paper, adapted for weights initialized from a normal distribution. You should use NF4 for training 4-b... |
[
0.01709987,
-0.022899326,
-0.012828455,
-0.0009523618,
-0.030162862,
-0.0063253883,
0.010241443,
-0.01238781,
-0.044604648,
0.05222354,
0.026950417,
-0.037582755,
0.036502466,
-0.06521546,
0.013539174,
0.05358812,
-0.0043851286,
-0.02699306,
-0.053104833,
0.003734822,
-0.0085... | from transformers import BitsAndBytesConfig
nf4_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
)
model_nf4 = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=nf4_config) |
[
0.010001596,
-0.00915649,
0.0045223697,
0.0023484894,
-0.04690693,
-0.011663873,
0.019444445,
0.021190533,
-0.043638248,
0.05598659,
0.014876676,
-0.02771392,
0.020059068,
-0.054645594,
0.016301485,
0.05760696,
-0.010050487,
-0.017363107,
-0.047493614,
0.021958811,
-0.0181732... | from transformers import BitsAndBytesConfig
double_quant_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
)
model_double_quant = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-13b", quantization_config=double_quant_config) |
[
0.031071743,
-0.036371026,
0.008940727,
-0.009787744,
-0.025468405,
0.0043834904,
0.031795688,
-0.0025519081,
-0.036602687,
0.05530944,
0.021703888,
-0.011423861,
0.020719321,
-0.04969162,
-0.006978835,
0.035010006,
-0.005943593,
-0.08907426,
-0.042741746,
0.018011766,
-0.003... | Try 4-bit quantization in this notebook and learn more about it's details in this blog post.
This section explores some of the specific features of 4-bit models, such as changing the compute data type, using the Normal Float 4 (NF4) data type, and using nested quantization.
Compute data type
To speedup computation, yo... |
[
0.0380189,
0.006774802,
-0.007934186,
0.03547048,
0.023395106,
-0.015246083,
0.0078082466,
-0.028966077,
-0.016268415,
0.014105219,
-0.0026669533,
-0.008860212,
-0.00047829215,
-0.030788494,
-0.0038004084,
0.030551432,
-0.00494868,
-0.032477565,
-0.043441705,
0.009430643,
0.0... |
Optimum
The Optimum library supports quantization for Intel, Furiosa, ONNX Runtime, GPTQ, and lower-level PyTorch quantization functions. Consider using Optimum for quantization if you're using specific and optimized hardware like Intel CPUs, Furiosa NPUs or a model accelerator like ONNX Runtime.
Benchmarks
To compar... |
[
0.01978488,
0.009629452,
0.0110118305,
0.012448156,
-0.04213222,
-0.013210151,
0.00065072975,
0.016723417,
0.01770794,
0.07903163,
-0.020567106,
-0.0006068982,
-0.001404295,
-0.051707726,
-0.018935224,
0.038976353,
0.0035975578,
-0.07374488,
-0.02698674,
-0.009238339,
0.00541... | forward peak memory/batch size
generate throughput/batch size |
[
0.026660528,
0.002619629,
-0.0015262747,
-0.055119056,
0.017110487,
-0.008879473,
0.029018562,
-0.018407406,
0.005486115,
0.050756693,
0.0038612816,
-0.008341547,
0.058744535,
-0.055443287,
-0.021914983,
0.0022051306,
0.013529223,
0.027338464,
-0.06844195,
0.0025312027,
0.016... | Check copies
Since the Transformers library is very opinionated with respect to model code, and each model should fully be implemented in a single file without relying on other models, we have added a mechanism that checks whether a copy of the code of a layer of a given model stays consistent with the original. This w... |
[
0.04917604,
-0.0047732284,
-0.013818791,
-0.03444385,
0.005697673,
0.0057897493,
-0.0006822844,
0.007100914,
-0.016058084,
0.04628853,
0.0019925283,
0.0011988317,
-0.0076902015,
-0.058722496,
-0.017030409,
0.040572442,
-0.0026186462,
-0.056483205,
-0.0076754694,
0.008220561,
... |
For inference, the bnb_4bit_quant_type does not have a huge impact on performance. However, to remain consistent with the model weights, you should use the bnb_4bit_compute_dtype and torch_dtype values.
Nested quantization
Nested quantization is a technique that can save additional memory at no additional performance... |
[
0.012236456,
-0.0022838935,
0.03221175,
-0.004594519,
-0.0037992492,
-0.021077981,
0.009610062,
-0.012189675,
-0.0045276894,
0.081104115,
0.014956411,
0.02959204,
0.047261726,
-0.017108317,
-0.015357387,
0.0065125213,
0.02703916,
-0.006639497,
-0.029137602,
-0.037825417,
-0.0... | If a file is a full copy of another file, you should register it in the constant FULL_COPIES of utils/check_copies.py.
This mechanism relies on comments of the form # Copied from xxx. The xxx should contain the whole path to the class of function which is being copied below. For instance, RobertaSelfOutput is a direct... |
[
0.022261888,
0.0012896816,
0.0052943085,
0.0096626915,
-0.029338604,
-0.017936494,
0.00580026,
0.018637553,
0.003330024,
0.0860846,
-0.026256595,
0.010205019,
-0.0052579325,
-0.05171954,
-0.01574073,
0.036851823,
-0.0060681175,
-0.0734391,
-0.01949734,
-0.011540997,
-0.003478... | forward peak memory/batch size
generate peak memory/batch size
generate throughput/batch size
forward latency/batch size |
[
0.015367459,
-0.00943188,
0.017495053,
-0.042958416,
-0.0076498506,
0.008191912,
-0.0069316183,
0.012873974,
-0.029027423,
0.03862192,
0.028458258,
-0.0069248425,
0.02341708,
-0.06586054,
0.015299701,
0.0093031395,
-0.005407069,
-0.014689881,
-0.045045357,
-0.029271351,
0.000... | Copied from transformers.models.bert.modeling_bert.BertSelfOutput
Note that instead of applying this to a whole class, you can apply it to the relevant methods that are copied from. For instance here you can see how RobertaPreTrainedModel._init_weights is copied from the same method in BertPreTrainedModel with the com... |
[
0.05580237,
-0.005285791,
-0.02805103,
0.051846456,
-0.0140779605,
-0.0033752641,
0.012474617,
-0.0028882672,
-0.009133068,
0.057630483,
0.006083717,
0.0017531894,
-0.002652261,
-0.03464422,
-0.022941306,
0.03425462,
-0.00021048574,
-0.0394093,
-0.04468385,
-0.010271892,
-0.0... |
The benchmarks indicate AWQ quantization is the fastest for inference, text generation, and has the lowest peak memory for text generation. However, AWQ has the largest forward latency per batch size. For a more detailed discussion about the pros and cons of each quantization method, read the Overview of natively sup... |
[
-0.006115108,
-0.028016353,
0.03100656,
-0.004542555,
-0.0028252066,
-0.040920038,
-0.014789402,
0.023167368,
0.0047951066,
0.055871073,
0.06336006,
0.009213069,
0.021470224,
-0.03281146,
0.0052867397,
-0.023382878,
0.009064906,
-0.0032057173,
-0.04848984,
-0.0062194956,
0.03... | Sometimes the copy is exactly the same except for names: for instance in RobertaAttention, we use RobertaSelfAttention insted of BertSelfAttention but other than that, the code is exactly the same. This is why # Copied from supports simple string replacements with the following syntax: Copied from xxx with foo->bar. Th... |
[
0.0024538334,
-0.015026459,
-0.019477192,
-0.009285152,
0.00793877,
-0.018640064,
-0.011922106,
0.007673679,
-0.008245717,
0.038563725,
0.04244242,
0.0020230608,
-0.0024294169,
-0.035494253,
-0.011252403,
0.0013402777,
0.0059889574,
-0.071714014,
-0.035326827,
0.010568749,
-0... | Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Roberta
Note that there shouldn't be any spaces around the arrow (unless that space is part of the pattern to replace of course).
You can add several patterns separated by a comma. For instance here CamemberForMaskedLM is a direct copy of Robe... |
[
-0.020945514,
-0.056827344,
-0.015586351,
-0.002213724,
-0.02826922,
-0.005059425,
0.001562788,
-0.006247541,
0.01413461,
0.03761525,
0.03738413,
0.022982284,
0.014907427,
-0.04064874,
-0.03258833,
0.0007985477,
0.011671707,
-0.02137887,
-0.023011174,
-0.019833235,
0.03140382... | Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM with Roberta->Camembert, ROBERTA->CAMEMBERT
If the order matters (because one of the replacements might conflict with a previous one), the replacements are executed from left to right.
If the replacements change the formatting (if you replace... |
[
0.0065336702,
-0.0344109,
0.053405035,
0.005273783,
-0.017020904,
0.0010913111,
0.021222895,
-0.021861712,
0.019632952,
0.08653831,
0.07200169,
0.00047600683,
0.01609817,
-0.03688099,
-0.05357539,
0.0053696055,
0.01359259,
-0.014990888,
-0.008765979,
-0.027923368,
-0.00020184... | If the replacements change the formatting (if you replace a short name by a very long name for instance), the copy is checked after applying the auto-formatter.
Another way when the patterns are just different casings of the same replacement (with an uppercased and a lowercased variants) is just to add the option all-... |
[
0.017876886,
-0.04616667,
0.016564691,
-0.026074573,
0.046025574,
0.0065503903,
0.0036649732,
-0.014716332,
-0.00069093035,
0.0641141,
0.02733033,
-0.021996895,
0.03245212,
-0.04543297,
-0.014631674,
-0.014151947,
-0.00248682,
-0.027753618,
-0.03140801,
-0.023915803,
0.024324... | Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification with Bert->MobileBert all-casing
In this case, the code is copied from BertForSequenceClassification by replacing:
- Bert by MobileBert (for instance when using MobileBertModel in the init)
- bert by mobilebert (for instance when defining... |
[
0.025954397,
0.003517019,
-0.03606981,
0.034653086,
0.027144445,
0.010682104,
-0.0026244826,
-0.00772115,
-0.0046185227,
0.044031803,
-0.0038109894,
-0.0029131402,
0.030317908,
-0.063639276,
-0.031734634,
0.020910857,
-0.021548383,
-0.015909819,
-0.027215282,
0.010689188,
-0.... |
Export to TFLite
TensorFlow Lite is a lightweight framework for deploying machine learning models
on resource-constrained devices, such as mobile phones, embedded systems, and Internet of Things (IoT) devices.
TFLite is designed to optimize and run models efficiently on these devices with limited computational power... |
[
0.0583577,
-0.008133862,
-0.03221157,
0.05276337,
0.0018669238,
-0.02702945,
-0.019035446,
0.023555076,
0.007136452,
0.015973287,
0.0048839976,
-0.00080510514,
0.0128596,
-0.06589533,
-0.022215381,
0.03568594,
0.015531628,
-0.023643408,
-0.020154312,
0.0019616962,
-0.00333819... | pip install optimum[exporters-tf]
To check out all available arguments, refer to the 🤗 Optimum docs,
or view help in command line:
optimum-cli export tflite --help
To export a model's checkpoint from the 🤗 Hub, for example, google-bert/bert-base-uncased, run the following command:
optimum-cli export tflite --model... |
[
0.054877903,
-0.012612168,
-0.031283192,
-0.023608642,
-0.018092994,
0.020586178,
-0.017326932,
0.047662992,
0.01294645,
0.025112908,
0.04621444,
-0.02727181,
0.026867887,
-0.054181483,
0.0048470837,
0.05150723,
0.008266507,
-0.044960883,
-0.054376483,
0.039500948,
0.03094890... |
Optimize inference using torch.compile()
This guide aims to provide a benchmark on the inference speed-ups introduced with torch.compile() for computer vision models in 🤗 Transformers.
Benefits of torch.compile
Depending on the model and the GPU, torch.compile() yields up to 30% speed-up during inference. To use torc... |
[
0.016023109,
-0.022567758,
-0.0026816844,
-0.0091611,
-0.011537767,
0.014189479,
0.0049895905,
-0.013173929,
-0.002609397,
0.0337388,
0.015190923,
-0.034302995,
0.04696915,
-0.06702624,
0.0059839822,
0.05080567,
-0.0050706933,
-0.02579777,
-0.053626638,
-0.026460698,
0.017391... | from transformers import AutoModelForImageClassification
model = AutoModelForImageClassification.from_pretrained(MODEL_ID).to("cuda")
+ model = torch.compile(model) |
[
0.008097849,
-0.012942352,
-0.0041732336,
-0.05171258,
-0.029493218,
0.0055122203,
-0.019434838,
-0.002733024,
-0.009127839,
0.05057604,
-0.014114409,
-0.017516926,
0.03625563,
-0.01920753,
0.009760039,
0.0135248285,
0.0016843881,
-0.023299076,
-0.04779152,
-0.029550046,
0.00... | Object Detection with DETR
thon
from transformers import AutoImageProcessor, AutoModelForObjectDetection
processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = AutoModelForObjectDetection.from_pretrained("facebook/detr-resnet-50").to("cuda")
model = torch.compile(model)
texts = ["a photo of ... |
[
0.047356363,
-0.0055592256,
-0.005171452,
-0.0027092644,
0.009670307,
0.0028654032,
-0.020260287,
0.0137058925,
0.0012851419,
0.050815437,
-0.034755453,
-0.012449919,
0.044089463,
-0.079119444,
0.017418906,
0.051886104,
-0.010473306,
-0.039559722,
-0.05627858,
-0.040410765,
0... | Image Segmentation with Segformer
thon
from transformers import SegformerImageProcessor, SegformerForSemanticSegmentation
processor = SegformerImageProcessor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512"... |
[
0.038911074,
-0.011165079,
0.0031042919,
0.054439943,
0.01327659,
-0.017114354,
0.0055084513,
-0.0063900994,
0.013713709,
0.03938524,
-0.02804976,
0.030761383,
0.036629163,
-0.06602733,
-0.028094212,
-0.007171729,
0.005993728,
0.0039007391,
-0.03731077,
-0.0010835386,
0.02261... |
Validating TFLite model
-[✓] TFLite model output names match reference model (logits)
- Validating TFLite Model output "logits":
-[✓] (1, 128, 30522) matches (1, 128, 30522)
-[x] values not close enough, max diff: 5.817413330078125e-05 (atol: 1e-05)
The TensorFlow Lite export succeeded with th... |
[
0.031306095,
-0.028877174,
-0.033095825,
-0.015880315,
0.020937016,
0.022300621,
-0.020468278,
-0.014047971,
0.028720926,
0.050197702,
0.013280943,
-0.0063705915,
0.06806661,
-0.07437328,
0.016576322,
0.035680994,
-0.015681455,
-0.029800449,
-0.043976255,
-0.016278032,
0.0047... |
Below you can find the list of the models we benchmarked.
Image Classification
- google/vit-base-patch16-224
- microsoft/beit-base-patch16-224-pt22k-ft22k
- facebook/convnext-large-224
- microsoft/resnet-50
Image Segmentation
- nvidia/segformer-b0-finetuned-ade-512-512
- facebook/mask2former-swin-tiny-coco-panoptic... |
[
0.012916798,
-0.030752221,
-0.02010722,
-0.020669762,
-0.025761476,
0.024145974,
-0.029684836,
0.007832296,
-0.009721856,
0.030723372,
0.02251605,
-0.024665242,
0.025573961,
-0.07165902,
-0.014106788,
0.036723807,
-0.015578048,
-0.025573961,
-0.05743684,
0.02682886,
0.0198043... |
compile() comes with multiple modes for compiling, which essentially differ in compilation time and inference overhead. max-autotune takes longer than reduce-overhead but results in faster inference. Default mode is fastest for compilation but is not as efficient compared to reduce-overhead for inference time. In thi... |
[
0.057657517,
-0.0019779128,
-0.024334652,
-0.02173356,
-0.010823429,
0.024421355,
-0.0199706,
0.015563195,
-0.003887186,
0.051877316,
0.036126263,
-0.031068588,
0.031270895,
-0.08121184,
-0.027831674,
0.04762887,
0.008352392,
-0.023857785,
-0.045952607,
0.02112664,
0.01534643... |
Below you can find inference durations in milliseconds for each model with and without compile(). Note that OwlViT results in OOM in larger batch sizes.
A100 (batch size: 1)
| Task/Model | torch 2.0 - no compile | torch 2.0 - compile |
|:---:|:---:|:---:|
| Image Classification/ViT | 9.325 | 7.584 |
| Image Segmenta... |
[
0.041513406,
-0.013691357,
-0.035578806,
0.01432515,
-0.0011271423,
0.012214909,
0.002380323,
-0.027569972,
0.016377773,
0.053123333,
-0.019273052,
0.021476923,
0.03771065,
-0.06251498,
0.01692514,
0.034195986,
0.0057257386,
-0.026374409,
-0.021232048,
-0.013086374,
0.0071877... | PyTorch training on Apple silicon
Previously, training models on a Mac was limited to the CPU only. With the release of PyTorch v1.12, you can take advantage of training models with Apple's silicon GPUs for significantly faster performance and training. This is powered in PyTorch by integrating Apple's Metal Performanc... |
[
0.021894548,
-0.00015025628,
-0.03726441,
0.05468177,
-0.011172499,
0.007132108,
-0.022454197,
0.0007144905,
0.028064333,
0.05025918,
0.006210735,
0.011268049,
0.03873861,
-0.011192974,
-0.0110564735,
0.044362396,
0.03303292,
-0.02907443,
-0.053398672,
0.005732986,
0.02709518... | Some PyTorch operations are not implemented in MPS yet and will throw an error. To avoid this, you should set the environment variable PYTORCH_ENABLE_MPS_FALLBACK=1 to use the CPU kernels instead (you'll still see a UserWarning).
If you run into any other errors, please open an issue in the PyTorch repository because ... |
[
0.048406277,
0.01175419,
-0.025479225,
0.044181008,
-0.020615913,
0.002390893,
-0.008067712,
-0.010116543,
0.032667857,
0.059153773,
0.0040551242,
0.011130325,
0.043500427,
-0.037233416,
-0.010215795,
0.03581554,
0.020630091,
-0.022997944,
-0.05268826,
-0.013505266,
0.0156391... | If you run into any other errors, please open an issue in the PyTorch repository because the [Trainer] only integrates the MPS backend.
With the mps device set, you can:
train larger networks or batch sizes locally
reduce data retrieval latency because the GPU's unified memory architecture allows direct access to the... |
[
0.018961987,
0.00093989464,
-0.037719768,
0.02281273,
-0.019137021,
0.051430743,
-0.029828664,
-0.0077379495,
0.022652281,
0.043291677,
-0.015957242,
0.004795195,
0.029989112,
-0.045421254,
0.012121086,
0.05148909,
0.0042883265,
-0.03302303,
-0.022345973,
-0.017605476,
0.0188... | Get started by making sure you have PyTorch installed. MPS acceleration is supported on macOS 12.3+.
pip install torch torchvision torchaudio
[TrainingArguments] uses the mps device by default if it's available which means you don't need to explicitly set the device. For example, you can run the run_glue.py script wit... |
[
0.057262238,
-0.037758198,
-0.023878645,
0.029430466,
0.02969207,
-0.008611136,
-0.021466073,
-0.0032373513,
0.025869742,
0.012666001,
0.033601597,
-0.013552548,
0.020710329,
-0.04554819,
-0.008116995,
0.033746935,
0.011779454,
-0.032002907,
-0.033136524,
-0.012767736,
0.0141... | export TASK_NAME=mrpc
python examples/pytorch/text-classification/run_glue.py \
--model_name_or_path google-bert/bert-base-cased \
--task_name $TASK_NAME \
- --use_mps_device \
--do_train \
--do_eval \
--max_seq_length 128 \
--per_device_train_batch_size 32 \
--learning_rate 2e-5 \
--num_train_epochs 3 ... |
[
0.019262295,
0.0068159457,
0.011745302,
0.004485237,
0.0074362443,
-0.0005496434,
0.04040384,
-0.026852697,
0.0033162127,
-0.012200432,
-0.033063024,
0.0044962484,
0.028555766,
-0.061310478,
-0.032417033,
0.020143192,
-0.016619602,
-0.034501825,
-0.049330268,
-0.006485609,
0.... | Before you begin, make sure you have all the necessary libraries installed:
pip install transformers datasets evaluate sacrebleu
We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login:
from huggingface_hub import noteb... |
[
-0.0091591505,
-0.0036585638,
0.027943417,
0.010724506,
-0.003299988,
0.0052748844,
0.04586856,
-0.036432743,
-0.012326266,
0.020895677,
-0.029938336,
0.028627805,
0.044179432,
-0.04534435,
-0.04589768,
-0.0019293918,
-0.02514762,
-0.014255657,
-0.06407037,
0.0026592843,
-0.0... | from huggingface_hub import notebook_login
notebook_login()
Load OPUS Books dataset
Start by loading the English-French subset of the OPUS Books dataset from the 🤗 Datasets library:
from datasets import load_dataset
books = load_dataset("opus_books", "en-fr")
Split the dataset into a train and test set with the [~d... |
[
0.011337845,
0.0044886307,
0.012521659,
0.011112356,
0.0069443416,
0.0043617934,
0.029764485,
0.0017677947,
-0.002654775,
0.04698617,
0.012831706,
0.021604618,
0.034894347,
-0.024662808,
-0.046957985,
-0.023901783,
-0.0039002467,
-0.013797078,
-0.053158917,
-0.011676078,
-0.0... | Split the dataset into a train and test set with the [~datasets.Dataset.train_test_split] method:
books = books["train"].train_test_split(test_size=0.2)
Then take a look at an example:
books["train"][0]
{'id': '90560',
'translation': {'en': 'But this lofty plateau measured only a few fathoms, and soon we reentered ... |
[
0.0114913285,
-0.025039928,
-0.03323962,
0.042438563,
-0.029595314,
-0.012637522,
0.032122817,
-0.008897698,
-0.013379609,
0.024848895,
-0.018677082,
0.03855914,
-0.0120717725,
-0.022027494,
-0.0397935,
0.026171427,
-0.04828709,
-0.03559079,
-0.031740755,
-0.001181094,
-0.024... | translation: an English and French translation of the text.
Preprocess
The next step is to load a T5 tokenizer to process the English-French language pairs:
from transformers import AutoTokenizer
checkpoint = "google-t5/t5-small"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
The preprocessing function you wa... |
[
0.03017396,
0.009490648,
-0.034656625,
0.030201975,
-0.0050850264,
-0.0036701844,
-0.0072843353,
0.0005778439,
0.039055247,
0.077774286,
0.018519022,
0.023393923,
0.022889623,
-0.037710443,
0.013083788,
0.06516679,
0.012432399,
-0.03353596,
-0.036029443,
-0.0020172007,
0.0372... | Backends for distributed setups like gloo and nccl are not supported by the mps device which means you can only train on a single GPU with the MPS backend.
You can learn more about the MPS backend in the Introducing Accelerated PyTorch Training on Mac blog post. |
[
0.0141049065,
-0.01621884,
-0.00028024934,
0.03336117,
-0.013585442,
-0.0122723505,
0.0106634535,
0.021658788,
-0.04178804,
0.051340416,
-0.010093486,
0.02291416,
-0.018787302,
-0.018109113,
-0.05385116,
0.016565148,
-0.039623603,
-0.05797802,
-0.04617463,
-0.006691714,
0.000... | The preprocessing function you want to create needs to:
Prefix the input with a prompt so T5 knows this is a translation task. Some models capable of multiple NLP tasks require prompting for specific tasks.
Tokenize the input (English) and target (French) separately because you can't tokenize French text with a tokeni... |
[
-0.018482966,
-0.009838387,
-0.011018151,
-0.016109394,
-0.033286195,
-0.029746901,
0.007872115,
-0.0023437273,
-0.034297418,
0.026081208,
0.009360864,
0.04207824,
0.0059198863,
-0.02398853,
-0.043904066,
0.052864656,
-0.05325791,
-0.052162416,
-0.051432084,
-0.013728799,
-0.... | source_lang = "en"
target_lang = "fr"
prefix = "translate English to French: "
def preprocess_function(examples):
inputs = [prefix + example[source_lang] for example in examples["translation"]]
targets = [example[target_lang] for example in examples["translation"]]
model_inputs = tokenizer(inputs, text_t... |
[
0.016229708,
-0.013404,
0.030749498,
0.03379257,
0.02576466,
-0.017417954,
-0.006169462,
-0.013425736,
-0.023359185,
0.046254665,
0.008701731,
-0.0023656248,
0.00666215,
-0.023112841,
-0.04828338,
-0.0029995977,
-0.06578828,
-0.048167452,
-0.05831102,
0.005919496,
-0.00344519... | To apply the preprocessing function over the entire dataset, use 🤗 Datasets [~datasets.Dataset.map] method. You can speed up the map function by setting batched=True to process multiple elements of the dataset at once:
tokenized_books = books.map(preprocess_function, batched=True)
Now create a batch of examples usin... |
[
0.0006867548,
-0.009045632,
-0.022406217,
0.020771982,
-0.037530053,
-0.024642536,
0.0072393725,
0.02295096,
-0.020944007,
0.049543113,
0.01670073,
0.008257185,
0.0056123054,
-0.025703356,
-0.039049603,
0.0106368605,
-0.03626854,
-0.061126105,
-0.07551884,
-0.034347598,
-0.00... |
labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
result = metric.compute(predictions=decoded_preds, references=decoded_labels)
... |
[
0.012982962,
0.0080515025,
0.020249289,
0.012135798,
0.0018630723,
-0.0037364757,
-0.010827171,
-0.00045758914,
0.00095219864,
0.07873805,
-0.017535608,
-0.010648095,
0.01841721,
-0.06397122,
0.0066981064,
0.0137750255,
-0.03171011,
-0.07515654,
-0.06033461,
-0.025580224,
-0.... | from transformers import DataCollatorForSeq2Seq
data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)
from transformers import DataCollatorForSeq2Seq
data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf") |
[
-0.01351899,
0.011154451,
-0.006150002,
-0.007930749,
-0.03771512,
0.004802509,
-0.009803287,
-0.00467033,
0.013298691,
0.038978163,
0.014583766,
0.0053569274,
0.012777318,
-0.020678693,
-0.0054266886,
0.019959051,
-0.03231046,
-0.063387245,
-0.07924874,
-0.045998346,
0.01341... | import evaluate
metric = evaluate.load("sacrebleu")
Then create a function that passes your predictions and labels to [~evaluate.EvaluationModule.compute] to calculate the SacreBLEU score:
import numpy as np
def postprocess_text(preds, labels):
preds = [pred.strip() for pred in preds]
labels = [[label.strip... |
[
0.009605612,
0.004318329,
-0.014656378,
0.017288575,
-0.03442456,
0.025559014,
-0.01632725,
-0.0042267744,
0.010055755,
0.03805623,
0.009048654,
0.02613886,
0.0109178955,
-0.06359998,
-0.0037690008,
-0.0018396768,
-0.035553735,
-0.07238923,
-0.082948536,
-0.0323188,
0.0014887... | from transformers import DataCollatorForSeq2Seq
data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf")
Evaluate
Including a metric during training is often helpful for evaluating your model's performance. You can quickly load a evaluation method with the 🤗 Evaluate library.... |
[
0.0074626557,
-0.01299692,
0.005631043,
0.005763665,
-0.03911263,
-0.022438148,
-0.0080791665,
0.008960921,
-0.0121725155,
0.045105696,
-0.0030054932,
0.0026147969,
0.0070612063,
-0.01987174,
-0.0077350675,
0.015584835,
-0.023771534,
-0.082526505,
-0.07426812,
-0.028603261,
-... | import numpy as np
def postprocess_text(preds, labels):
preds = [pred.strip() for pred in preds]
labels = [[label.strip()] for label in labels]
return preds, labels
def compute_metrics(eval_preds):
preds, labels = eval_preds
if isinstance(preds, tuple):
preds = preds[0]
decoded_... |
[
0.03398226,
0.0065747974,
-0.012871636,
0.02822352,
-0.03680461,
-0.0010423459,
-0.0036081204,
-0.0070843888,
-0.0032713625,
0.029962545,
0.01831678,
-0.011945106,
0.02299219,
-0.05008962,
0.01431132,
0.043304574,
-0.008324513,
-0.04071029,
-0.07224081,
-0.011396315,
0.031673... | Your compute_metrics function is ready to go now, and you'll return to it when you setup your training.
Train
If you aren't familiar with finetuning a model with the [Trainer], take a look at the basic tutorial here!
You're ready to start training your model now! Load T5 with [AutoModelForSeq2SeqLM]:
from transforme... |
[
0.04132667,
0.021273708,
0.006345639,
0.02110995,
-0.018534476,
-0.0015017391,
-0.025352782,
-0.02380452,
0.020841982,
0.021958517,
-0.0095352065,
0.0059771826,
0.0020600066,
-0.043113127,
-0.008001832,
0.023581212,
0.00022819178,
-0.046150103,
-0.09944603,
-0.036860533,
0.00... |
Define your training hyperparameters in [Seq2SeqTrainingArguments]. The only required parameter is output_dir which specifies where to save your model. You'll push this model to the Hub by setting push_to_hub=True (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [Trainer]... |
[
0.028934993,
0.021230983,
0.02910097,
0.026625173,
-0.033001382,
-0.021286307,
0.0046749655,
0.0039280774,
-0.004426003,
0.02308437,
-0.0111410795,
0.008713693,
0.015518673,
-0.04691563,
-0.0056881052,
0.015767636,
-0.021936378,
-0.019377593,
-0.0695989,
-0.015145228,
-0.0034... |
training_args = Seq2SeqTrainingArguments(
output_dir="my_awesome_opus_books_model",
evaluation_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
weight_decay=0.01,
save_total_limit=3,
num_train_epochs=2,
predict_with_gener... |
[
0.024683893,
0.032738637,
-0.04027372,
-0.0053229155,
-0.032218978,
-0.03484615,
0.0002438166,
0.0012747932,
-0.021421578,
0.02547782,
0.011425323,
0.01987703,
0.017076634,
-0.053034283,
0.0066328943,
0.042121403,
0.0033074252,
-0.036809314,
-0.07350315,
0.009476594,
0.014225... | Once training is completed, share your model to the Hub with the [~transformers.Trainer.push_to_hub] method so everyone can use your model:
trainer.push_to_hub()
If you aren't familiar with finetuning a model with Keras, take a look at the basic tutorial here!
To finetune a model in TensorFlow, start by setting up a... |
[
0.05098063,
0.0222832,
-0.01121796,
0.01394609,
0.00033906387,
-0.018312488,
-0.0013319593,
-0.016701987,
-0.034236994,
0.035319913,
0.034403596,
-0.020089589,
0.02528206,
-0.04850935,
0.014355657,
0.020270076,
-0.029127821,
-0.051952485,
-0.055229016,
-0.009697705,
0.0263372... | To finetune a model in TensorFlow, start by setting up an optimizer function, learning rate schedule, and some training hyperparameters:
from transformers import AdamWeightDecay
optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)
Then you can load T5 with [TFAutoModelForSeq2SeqLM]:
from transform... |
[
0.03181688,
0.0035193865,
0.0025073085,
0.05348925,
-0.005099381,
-0.021523185,
0.0010764983,
-0.018363196,
0.00089425646,
0.028806077,
0.008659454,
-0.021021383,
0.047223523,
-0.0449722,
-0.012205965,
0.03192538,
-0.010246229,
-0.040795047,
-0.021265503,
-0.035560045,
0.0165... | Then you can load T5 with [TFAutoModelForSeq2SeqLM]:
from transformers import TFAutoModelForSeq2SeqLM
model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint)
Convert your datasets to the tf.data.Dataset format with [~transformers.TFPreTrainedModel.prepare_tf_dataset]: |
[
0.03887087,
0.031751763,
-0.03789639,
-0.029965218,
-0.02403714,
-0.023739383,
0.016065363,
0.014075803,
-0.05229702,
0.029180221,
0.017215788,
-0.03107504,
0.033754855,
-0.051999263,
-0.0025749244,
0.03670536,
-0.008195095,
-0.03107504,
-0.09170926,
0.020409914,
0.0037964063... | Configure the model for training with compile. Note that Transformers models all have a default task-relevant loss function, so you don't need to specify one unless you want to:
import tensorflow as tf
model.compile(optimizer=optimizer) # No loss argument! |
[
0.019034319,
0.048056226,
-0.03416045,
-0.005909323,
-0.027183611,
0.004327955,
-0.011500202,
0.006633062,
-0.006405084,
0.01736972,
0.006875514,
0.0042990055,
0.021306856,
-0.060446624,
-0.026228277,
0.037460696,
-0.00359517,
-0.035723723,
-0.10456571,
-0.015632749,
0.024114... | import tensorflow as tf
model.compile(optimizer=optimizer) # No loss argument!
The last two things to setup before you start training is to compute the SacreBLEU metric from the predictions, and provide a way to push your model to the Hub. Both are done by using Keras callbacks.
Pass your compute_metrics function to ... |
[
0.010889921,
0.0008682189,
-0.016003974,
0.02133863,
-0.020055104,
-0.014947738,
0.015148289,
0.011377929,
0.000093694944,
0.026098376,
0.007988617,
0.018183295,
0.048640314,
-0.048774015,
-0.038880162,
0.0087239705,
-0.022234425,
-0.047276568,
-0.04441537,
-0.03628637,
-0.01... | Convert your datasets to the tf.data.Dataset format with [~transformers.TFPreTrainedModel.prepare_tf_dataset]:
tf_train_set = model.prepare_tf_dataset(
tokenized_books["train"],
shuffle=True,
batch_size=16,
collate_fn=data_collator,
)
tf_test_set = model.prepare_tf_dataset(
tokenized_books["t... |
[
0.011927631,
0.05342137,
-0.049373876,
0.017160265,
-0.019128567,
0.012447429,
-0.00026401406,
-0.0043593724,
0.019544404,
0.028013647,
0.004646994,
0.038562078,
0.001362737,
-0.052561972,
-0.016675118,
0.04787686,
0.0131058395,
-0.03140966,
-0.070359856,
0.01213555,
-0.00207... | Then bundle your callbacks together:
callbacks = [metric_callback, push_to_hub_callback]
Finally, you're ready to start training your model! Call fit with your training and validation datasets, the number of epochs, and your callbacks to finetune the model:
model.fit(x=tf_train_set, validation_data=tf_test_set, epoc... |
[
0.01152521,
0.0148819275,
-0.03313498,
0.022214843,
-0.0056617595,
0.0067170365,
0.0011047994,
0.003817726,
0.006450516,
0.02391481,
0.024130909,
0.04350767,
-0.0001935875,
-0.043075472,
-0.027804568,
0.040453486,
0.008823989,
-0.02181146,
-0.060276847,
0.011921389,
0.0078443... | model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks)
Once training is completed, your model is automatically uploaded to the Hub so everyone can use it!
For a more in-depth example of how to finetune a model for translation, take a look at the corresponding
PyTorch notebook
or TensorF... |
[
0.020904545,
-0.028447421,
-0.022987815,
-0.009345983,
-0.022053935,
0.0016441676,
0.014467956,
0.00080457353,
-0.04838935,
0.06229698,
0.007564428,
0.020990748,
-0.0011736357,
-0.026996315,
-0.037613813,
0.029625546,
-0.0074925907,
-0.04586069,
-0.049854822,
0.0037175606,
0.... | For a more in-depth example of how to finetune a model for translation, take a look at the corresponding
PyTorch notebook
or TensorFlow notebook.
Inference
Great, now that you've finetuned a model, you can use it for inference!
Come up with some text you'd like to translate to another language. For T5, you need to pre... |
[
0.01271721,
-0.033204053,
-0.0068792133,
0.016357878,
-0.015366928,
-0.0066386564,
-0.0026640794,
-0.0025384154,
0.022217417,
0.032256186,
0.00075084314,
-0.0115323765,
0.0046208496,
-0.04848481,
-0.03352001,
0.0038022373,
-0.0026802362,
-0.021858377,
-0.043659307,
-0.004082289... | You can also manually replicate the results of the pipeline if you'd like:
Tokenize the text and return the input_ids as PyTorch tensors:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("my_awesome_opus_books_model")
inputs = tokenizer(text, return_tensors="pt").input_ids |
[
-0.0066866255,
-0.005766516,
-0.0005862438,
-0.0060161003,
-0.012143955,
-0.004697401,
0.022768052,
-0.010571946,
-0.0021289173,
0.017523056,
-0.03236401,
0.016643923,
0.0118086925,
-0.042198382,
-0.014356688,
-0.00077622593,
-0.0092755975,
-0.013470105,
-0.05256917,
0.00596767... | from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("my_awesome_opus_books_model")
inputs = tokenizer(text, return_tensors="pt").input_ids
Use the [~transformers.generation_utils.GenerationMixin.generate] method to create the translation. For more details about the different text generatio... |
[
-0.0008608587,
0.025506925,
-0.029746104,
0.009110643,
-0.016496873,
0.01760337,
0.02343763,
-0.011237416,
-0.016453762,
0.028797677,
-0.041472103,
0.022374243,
0.012056513,
-0.062078822,
-0.011273342,
0.03943155,
-0.016381912,
-0.0467603,
-0.07386231,
0.014377283,
0.00750837... | from transformers.keras_callbacks import KerasMetricCallback
metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
Specify where to push your model and tokenizer in the [~transformers.PushToHubCallback]:
from transformers.keras_callbacks import PushToHubCallback
push_to_hub_... |
[
0.027180068,
0.006435302,
0.002494624,
0.033611774,
0.00071763154,
-0.009856192,
-0.000015133324,
-0.022216002,
-0.0027913887,
0.049007576,
-0.01574113,
0.017626038,
0.022072116,
-0.049266573,
-0.03076283,
0.005974867,
0.0108633945,
-0.031827588,
-0.034331203,
-0.0035288045,
... | from transformers import AutoModelForSeq2SeqLM
model = AutoModelForSeq2SeqLM.from_pretrained("my_awesome_opus_books_model")
outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95)
Decode the generated token ids back into text:
tokenizer.decode(outputs[0], skip_special_tokens=True)
'L... |
[
0.019747566,
0.003838155,
-0.0037323644,
0.024201905,
-0.009762425,
-0.02672603,
0.011744605,
-0.0135337645,
-0.004105415,
0.033169974,
-0.0076169185,
0.015931685,
0.032041542,
-0.03043798,
-0.028522614,
0.011640671,
0.011254628,
-0.0363474,
-0.025790619,
-0.0035838864,
-0.01... | from transformers import TFAutoModelForSeq2SeqLM
model = TFAutoModelForSeq2SeqLM.from_pretrained("my_awesome_opus_books_model")
outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95)
Decode the generated token ids back into text:
tokenizer.decode(outputs[0], skip_special_tokens=True... |
[
0.0031173385,
-0.01478855,
-0.012146427,
-0.009174039,
-0.023617646,
0.025804738,
0.03141191,
0.0033705418,
0.0039962116,
0.057715714,
0.026362518,
-0.0021118638,
0.010443726,
-0.017217835,
-0.016116953,
0.01145654,
-0.0057796445,
-0.031177053,
-0.043976672,
-0.016616018,
-0.... | text = "translate English to French: Legumes share resources with nitrogen-fixing bacteria."
The simplest way to try out your finetuned model for inference is to use it in a [pipeline]. Instantiate a pipeline for translation with your model, and pass your text to it:
from transformers import pipeline
translator = pip... |
[
0.031220477,
-0.022517294,
0.027394582,
0.03773326,
-0.02612415,
-0.005406633,
0.027131733,
0.00020660475,
-0.0115287965,
0.039865248,
-0.0018472358,
0.018048882,
0.0109958,
-0.04147154,
-0.041851208,
0.049795054,
0.009272686,
-0.036010146,
-0.056074195,
0.02375852,
-0.018647... | from huggingface_hub import notebook_login
notebook_login()
Let's define some global variables.
model_checkpoint = "microsoft/layoutlmv2-base-uncased"
batch_size = 4
Load the data
In this guide we use a small sample of preprocessed DocVQA that you can find on 🤗 Hub. If you'd like to use the full
DocVQA dataset, you... |
[
-0.00049225416,
0.0016016628,
-0.011549606,
0.00847118,
-0.014811708,
-0.010454891,
0.026273148,
-0.0109471455,
-0.016927667,
0.026860915,
-0.03059323,
0.022746552,
0.019998744,
-0.047197625,
-0.020895088,
-0.0054184697,
-0.006656452,
-0.017809315,
-0.047403343,
-0.009712837,
... | from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("my_awesome_opus_books_model")
inputs = tokenizer(text, return_tensors="tf").input_ids
Use the [~transformers.generation_tf_utils.TFGenerationMixin.generate] method to create the translation. For more details about the different text gene... |
[
0.024539337,
0.007074043,
0.0073005194,
0.0012905799,
-0.032585897,
-0.010204741,
-0.004646088,
0.009045716,
-0.0075936057,
0.07742813,
0.004169822,
-0.0087393075,
0.022487732,
-0.016772544,
0.008459544,
0.01826462,
-0.021208808,
-0.03242603,
-0.04036601,
-0.0046993764,
-0.00... | from datasets import load_dataset
dataset = load_dataset("nielsr/docvqa_1200_examples")
dataset
DatasetDict({
train: Dataset({
features: ['id', 'image', 'query', 'answers', 'words', 'bounding_boxes', 'answer'],
num_rows: 1000
})
test: Dataset({
features: ['id', 'image', 'query', 'ans... |
[
0.03177408,
-0.028840644,
-0.02991527,
0.00632069,
-0.0024832578,
0.007732952,
-0.025863638,
0.01213311,
0.011530449,
0.073481195,
0.0023489296,
0.023133507,
-0.0111674,
-0.003844693,
-0.04350784,
0.027432011,
-0.0010038315,
-0.034300905,
-0.008713186,
-0.010586521,
-0.016860... |
LayoutLMv2 solves the document question-answering task by adding a question-answering head on top of the final hidden
states of the tokens, to predict the positions of the start and end tokens of the
answer. In other words, the problem is treated as extractive question answering: given the context, extract which piec... |
[
0.012794991,
0.015373138,
0.0107776085,
-0.0077276,
-0.0070027104,
-0.0045750127,
0.0075292815,
0.010100589,
0.034329694,
0.04729565,
0.022498943,
0.0034517755,
0.02806555,
-0.055529304,
-0.008664486,
0.008274687,
-0.004328824,
-0.0309104,
-0.034384403,
-0.02535747,
-0.007830... | As you can see, the dataset is split into train and test sets already. Take a look at a random example to familiarize
yourself with the features.
dataset["train"].features |
[
0.025175609,
-0.027995275,
-0.000586232,
-0.046179257,
-0.020111714,
-0.038324468,
0.008753918,
-0.007318909,
0.0069304854,
0.06358639,
0.037346214,
0.012479909,
0.024369989,
0.00991919,
-0.04646698,
0.009876031,
-0.02052891,
-0.023420509,
-0.039791845,
-0.01466659,
-0.003357... |
Here's what the individual fields represent:
* id: the example's id
* image: a PIL.Image.Image object containing the document image
* query: the question string - natural language asked question, in several languages
* answers: a list of correct answers provided by human annotators
* words and bounding_boxes: the res... |
[
0.038238313,
-0.0083727725,
-0.019480988,
-0.019828346,
-0.014256146,
-0.020841472,
0.021188831,
0.007830026,
0.008872099,
0.0292649,
-0.047530137,
-0.016340293,
0.0206099,
-0.03181219,
-0.020624373,
0.050887927,
-0.005988305,
-0.04483811,
-0.021492768,
-0.01677449,
0.0062560... | pip install -q transformers datasets
pip install 'git+https://github.com/facebookresearch/detectron2.git'
pip install torchvision
sudo apt install tesseract-ocr
pip install -q pytesseract
Once you have installed all of the dependencies, restart your runtime.
We encourage you to share your model with the community. Lo... |
[
0.03781407,
-0.025583407,
0.0159195,
0.03265251,
-0.01650859,
-0.04715538,
0.002796432,
-0.010673779,
0.011613521,
0.06019955,
0.02420886,
0.005841825,
0.012602353,
0.006031176,
-0.03478446,
0.0042498754,
0.0053859805,
-0.024994316,
-0.011452221,
-0.017251968,
-0.014278458,
... |
Note that the LayoutLMv2 checkpoint that we use in this guide has been trained with max_position_embeddings = 512 (you can
find this information in the checkpoint's config.json file).
We can truncate the examples but to avoid the situation where the answer might be at the end of a large document and end up truncated,... |
[
0.039621778,
0.014547982,
-0.008242039,
0.06277311,
-0.0021525424,
-0.045021027,
-0.00512997,
-0.004533462,
-0.012707328,
0.047202542,
0.016320463,
-0.017533932,
-0.002663835,
-0.0026502006,
-0.05344713,
-0.050856583,
-0.029859494,
-0.036976688,
-0.014138948,
0.0073489808,
0.... | updated_dataset = updated_dataset.filter(lambda x: len(x["words"]) + len(x["question"].split()) < 512) |
[
0.017869283,
-0.021792848,
0.016234463,
0.0067311893,
-0.008742727,
-0.057346605,
-0.011308682,
0.0063509163,
-0.0049364422,
0.04694063,
0.025403665,
-0.006770283,
0.014898176,
-0.0101074455,
-0.03221304,
-0.026043376,
-0.03204245,
-0.010811129,
-0.054446578,
0.024010515,
-0.... | updated_dataset = updated_dataset.remove_columns("words")
updated_dataset = updated_dataset.remove_columns("bounding_boxes")
Finally, the data exploration won't be complete if we don't peek at an image example.
updated_dataset["train"][11]["image"] |
[
0.040115606,
-0.028814433,
0.012481042,
-0.0105690835,
-0.007647837,
0.002125189,
0.023512123,
0.00097374874,
0.002391726,
0.04941242,
-0.0019332822,
0.0037137498,
-0.012751133,
-0.051231977,
-0.019304391,
0.01924753,
-0.00031828968,
-0.06015919,
-0.063286565,
-0.026511554,
-... |
At this point let's also remove the OCR features from this dataset. These are a result of OCR for fine-tuning a different
model. They would still require some processing if we wanted to use them, as they do not match the input requirements
of the model we use in this guide. Instead, we can use the [LayoutLMv2Processo... |
[
0.03480609,
-0.019825118,
-0.00031607496,
-0.005935575,
0.01327655,
0.003132249,
-0.0076923254,
0.005146906,
0.0014502538,
0.053345416,
0.007598881,
-0.0049749683,
0.033909027,
-0.014218467,
-0.024564607,
0.01928688,
-0.023667544,
-0.031187931,
-0.046796847,
-0.013792362,
-0.... | Finally, the data exploration won't be complete if we don't peek at an image example.
updated_dataset["train"][11]["image"]
Preprocess the data
The Document Question Answering task is a multimodal task, and you need to make sure that the inputs from each modality
are preprocessed according to the model's expectations... |
[
0.003424599,
0.02155026,
-0.0046814624,
0.008621517,
-0.029825786,
-0.036350176,
-0.021352552,
-0.0052745887,
-0.012194397,
0.051545512,
0.019248364,
-0.018584628,
0.00898869,
-0.001934722,
-0.06377521,
-0.032960884,
-0.035361633,
-0.008762737,
-0.03403416,
0.01673464,
0.0042... | updated_dataset = dataset.map(lambda example: {"question": example["query"]["en"]}, remove_columns=["query"])
updated_dataset = updated_dataset.map(
lambda example: {"answer": example["answers"][0]}, remove_columns=["answer", "answers"]
) |
[
0.03696102,
-0.030240836,
0.042115062,
-0.03670474,
-0.005887281,
-0.010421983,
-0.031778503,
-0.00011601485,
-0.050315965,
0.0750041,
0.015889252,
-0.013589866,
-0.0020181914,
0.017113693,
-0.04077672,
0.039694656,
-0.028959444,
-0.047980987,
-0.04575991,
-0.009838237,
-0.03... | Preprocessing document images
First, let's prepare the document images for the model with the help of the image_processor from the processor.
By default, image processor resizes the images to 224x224, makes sure they have the correct order of color channels,
applies OCR with tesseract to get words and normalized boundi... |
[
0.03506152,
-0.0024348276,
0.04005382,
-0.033964943,
-0.0052952995,
-0.06562131,
-0.019031335,
-0.0030841152,
-0.037168097,
0.065101884,
0.0115356725,
0.0002225162,
0.035205804,
-0.022119056,
-0.015958041,
0.02012791,
-0.028467644,
-0.03367637,
-0.06233159,
-0.015640613,
-0.0... | image_processor = processor.image_processor
def get_ocr_words_and_boxes(examples):
images = [image.convert("RGB") for image in examples["image"]]
encoded_inputs = image_processor(images)
examples["image"] = encoded_inputs.pixel_values
examples["words"] = encoded_inputs.words
examples["boxes"] ... |
[
0.01464273,
0.00799249,
-0.02723819,
0.006473985,
-0.03424772,
-0.014046175,
0.0012126011,
-0.020269336,
-0.0026709426,
0.039616723,
-0.010053319,
-0.023197882,
0.03028876,
-0.055262752,
-0.0048368466,
0.030939547,
-0.020323567,
-0.04493149,
-0.062096026,
-0.028932951,
0.0149... | from transformers import AutoProcessor
processor = AutoProcessor.from_pretrained(model_checkpoint) |
[
0.0453993,
0.004029115,
-0.015549696,
0.002090853,
-0.015157321,
-0.02521376,
-0.040109497,
0.027422689,
-0.00048274905,
0.0571415,
0.0020018418,
-0.0021017522,
-0.0054678256,
-0.035953224,
-0.029820539,
-0.025315488,
-0.041853387,
0.006158116,
-0.015738618,
-0.03287235,
0.01... |
def subfinder(words_list, answer_list):
matches = []
start_indices = []
end_indices = []
for idx, i in enumerate(range(len(words_list))):
if words_list[i] == answer_list[0] and words_list[i : i + len(answer_list)] == answer_list:
matches.append(answer_list)
start... |
[
0.023307906,
0.0076256003,
0.008600886,
-0.010841215,
-0.02644578,
-0.02678501,
-0.027548276,
0.042092748,
-0.0006581409,
0.08062359,
0.04802927,
0.011830635,
-0.013159284,
0.017399656,
-0.03378162,
-0.014141637,
0.011865972,
-0.01020516,
-0.010374774,
-0.016961483,
0.0053464... | To illustrate how this function finds the position of the answer, let's use it on an example: |
[
0.019553429,
-0.017371317,
0.029494159,
0.002652763,
0.014975274,
-0.05887422,
-0.00083923934,
-0.00622187,
-0.00087266625,
0.050031677,
0.03194725,
-0.022363076,
0.017000502,
-0.031433813,
-0.023033397,
0.010240235,
-0.025785996,
-0.018626388,
-0.03325937,
-0.015602809,
-0.0... | To apply this preprocessing to the entire dataset in a fast way, use [~datasets.Dataset.map].
dataset_with_ocr = updated_dataset.map(get_ocr_words_and_boxes, batched=True, batch_size=2) |
[
0.031623866,
-0.024311395,
0.0075103017,
-0.014668901,
0.024619134,
-0.03153594,
0.013078916,
-0.018889325,
-0.009107615,
0.033587534,
-0.012221642,
0.0068838326,
0.012243624,
-0.0145516675,
-0.031741098,
0.01938757,
-0.046864282,
-0.037456255,
-0.05392763,
-0.0063086534,
-0.... | dataset_with_ocr = updated_dataset.map(get_ocr_words_and_boxes, batched=True, batch_size=2)
Preprocessing text data
Once we have applied OCR to the images, we need to encode the text part of the dataset to prepare it for the model.
This involves converting the words and boxes that we got in the previous step to token-... |
[
0.028249588,
-0.019356199,
-0.017386729,
-0.0032600118,
-0.0028734263,
-0.018048348,
0.0014809492,
0.018509943,
-0.00013391051,
0.05136009,
0.029880555,
0.0059391833,
0.006289226,
-0.024587605,
-0.02329514,
0.028003404,
-0.018156053,
-0.01245536,
-0.027526423,
-0.032557804,
0... |
On top of the preprocessing mentioned above, we also need to add the labels for the model. For xxxForQuestionAnswering models
in 🤗 Transformers, the labels consist of the start_positions and end_positions, indicating which token is at the
start and which token is at the end of the answer.
Let's start with that. Defi... |
[
0.0095675355,
-0.018363496,
0.031048197,
0.008950275,
-0.024474373,
-0.05151038,
0.00976043,
0.020693654,
-0.015146026,
0.049967226,
0.029643929,
0.03027662,
0.01119556,
-0.0043439697,
-0.02433549,
-0.001054165,
0.015608972,
0.0022722897,
-0.026449608,
0.02188188,
0.036449224... | Once examples are encoded, however, they will look like this:
encoding = tokenizer(example["question"], example["words"], example["boxes"])
tokenizer.decode(encoding["input_ids"])
[CLS] who is in cc in this letter? [SEP] wie baw brown & williamson tobacco corporation research & development |
[
0.046055976,
-0.005292723,
0.014255067,
0.0034430556,
-0.006748686,
-0.033932853,
0.0050550145,
0.028614132,
-0.032863166,
0.049086753,
0.0022378003,
0.036191083,
0.0010826868,
-0.0079409415,
-0.058476232,
-0.016268158,
-0.011781416,
-0.02039834,
-0.053900346,
-0.0015246756,
... |
We'll need to find the position of the answer in the encoded input.
* token_type_ids tells us which tokens are part of the question, and which ones are part of the document's words.
* tokenizer.cls_token_id will help find the special token at the beginning of the input.
* word_ids will help match the answer found in ... |
[
0.03350968,
0.008432717,
0.029279498,
0.013810301,
-0.023984859,
-0.04459663,
0.012794228,
0.013298809,
-0.015690383,
0.04694673,
0.027897086,
0.02040441,
0.025035491,
-0.00074347877,
-0.05109397,
-0.0090824505,
-0.019975862,
-0.042080637,
-0.044568982,
0.017722528,
-0.002731... | def encode_dataset(examples, max_length=512):
questions = examples["question"]
words = examples["words"]
boxes = examples["boxes"]
answers = examples["answer"] |
[
0.041566834,
-0.008852474,
0.049645938,
-0.0014819823,
-0.020438028,
-0.03697166,
-0.00030714294,
-0.018065354,
-0.004246034,
0.062049914,
0.036641285,
0.0074333753,
-0.007981493,
-0.037422165,
-0.029313028,
-0.0073207486,
-0.030739635,
-0.0065060807,
-0.029358078,
-0.005935437... |
example = dataset_with_ocr["train"][1]
words = [word.lower() for word in example["words"]]
match, word_idx_start, word_idx_end = subfinder(words, example["answer"].lower().split())
print("Question: ", example["question"])
print("Words:", words)
print("Answer: ", example["answer"])
print("start_index", word_idx_start)... |
[
0.031506132,
0.01618831,
0.03057948,
0.020372279,
0.007904613,
-0.0077922917,
0.024317566,
-0.014938736,
-0.017676568,
0.025693502,
-0.030017873,
0.016160231,
0.025005534,
-0.019108664,
-0.020484602,
0.0023271574,
-0.008431119,
-0.041446567,
-0.079130374,
-0.01440521,
0.02694... |
encoded_train_dataset.features
{'image': Sequence(feature=Sequence(feature=Sequence(feature=Value(dtype='uint8', id=None), length=-1, id=None), length=-1, id=None), length=-1, id=None),
'input_ids': Sequence(feature=Value(dtype='int32', id=None), length=-1, id=None),
'token_type_ids': Sequence(feature=Value(dtype='... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.