vector listlengths 1.02k 1.02k | text stringlengths 2 11.8k |
|---|---|
[
0.034078557,
-0.0013753439,
-0.0401579,
-0.026829015,
-0.034363974,
-0.023004454,
-0.0052373665,
0.011202541,
0.0034321162,
0.044039544,
-0.0042598196,
-0.012215764,
0.03253732,
-0.018566249,
-0.0026989563,
0.05819613,
0.029569,
-0.027385576,
-0.044410583,
-0.020806758,
0.006... | from transformers import TFPreTrainedModel
model.save_pretrained("path_to/model")
model = TFPreTrainedModel.from_pretrained("path_to/model")
ImportError
Another common error you may encounter, especially if it is a newly released model, is ImportError:
ImportError: cannot import name 'ImageGPTImageProcessor' from 'tra... |
[
-0.04053327,
0.01685704,
-0.010822056,
0.015288626,
-0.021030385,
-0.04255175,
0.025981117,
0.01389751,
0.014483961,
0.054144375,
-0.007262438,
0.0052780537,
0.0726653,
-0.0032288868,
-0.0118722115,
-0.0052951016,
-0.012983739,
-0.027276764,
-0.06453682,
0.025040068,
0.017402... | import os
os.environ["CUDA_VISIBLE_DEVICES"] = ""
Another option is to get a better traceback from the GPU. Add the following environment variable to the beginning of your code to get the traceback to point to the source of the error:
import os
os.environ["CUDA_LAUNCH_BLOCKING"] = "1" |
[
-0.029300952,
-0.013519166,
-0.038690835,
0.019218145,
-0.027759543,
-0.0076434193,
0.018482793,
-0.029866608,
0.025454495,
0.053426158,
-0.044630215,
-0.01274139,
0.03241206,
-0.005843928,
0.0059888773,
0.006080796,
-0.01754946,
-0.023884801,
-0.050541315,
-0.006823219,
0.02... | pip install transformers --upgrade
CUDA error: device-side assert triggered
Sometimes you may run into a generic CUDA error about an error in the device code.
RuntimeError: CUDA error: device-side assert triggered
You should try to run the code on a CPU first to get a more descriptive error message. Add the following e... |
[
-0.008670333,
-0.00047601463,
0.012812494,
0.019389477,
-0.041837323,
-0.051517215,
0.007905739,
-0.007928009,
-0.032484055,
0.0696002,
0.00022919221,
0.031771425,
0.0145049915,
-0.027748033,
-0.042549953,
0.016880425,
-0.0044390913,
-0.019404322,
-0.046617884,
0.021274976,
0... | import os
os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
Incorrect output when padding tokens aren't masked
In some cases, the output hidden_state may be incorrect if the input_ids include padding tokens. To demonstrate, load a model and tokenizer. You can access a model's pad_token_id to see its value. The pad_token_id may... |
[
0.022290213,
-0.0064846277,
0.013673703,
0.0040857974,
-0.0055206465,
0.0055132313,
-0.030135537,
-0.023550803,
-0.026902491,
0.05677108,
0.0145190405,
0.007448609,
0.0070852623,
-0.043927886,
-0.0206292,
0.02558258,
-0.0049570883,
-0.030639773,
-0.029394012,
-0.006618102,
0.... | from transformers import AutoModelForSequenceClassification
import torch
model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-uncased")
model.config.pad_token_id
0
The following example shows the output without masking the padding tokens:
input_ids = torch.tensor([[7592, 2057, 2097, 2393,... |
[
0.023974653,
0.009187934,
-0.03548249,
-0.0046398006,
-0.042054363,
-0.004950061,
-0.008764852,
-0.008362924,
0.016852772,
0.04146205,
0.033197843,
-0.008186639,
0.032943994,
-0.024806716,
0.023904141,
0.05361861,
0.022324633,
-0.010259742,
-0.05485965,
-0.005034677,
-0.01706... | Save the model with [~TFPretrainedModel.save_pretrained] and load it again with [~TFPreTrainedModel.from_pretrained]:
from transformers import TFPreTrainedModel
model.save_pretrained("path_to/model")
model = TFPreTrainedModel.from_pretrained("path_to/model") |
[
0.021320246,
0.023081167,
-0.02471111,
0.016066588,
-0.0464825,
0.010761994,
0.008906478,
-0.004864363,
-0.0026231906,
0.021989686,
0.017128961,
-0.011198586,
0.026966836,
-0.06298568,
0.018205889,
0.053642612,
0.0027614448,
-0.038536526,
-0.029251667,
-0.03306457,
-0.0049662... | Save the model weights as a h5 file extension with model.save_weights and then reload the model with [~TFPreTrainedModel.from_pretrained]:
from transformers import TFPreTrainedModel
from tensorflow import keras
model.save_weights("some_folder/tf_model.h5")
model = TFPreTrainedModel.from_pretrained("some_folder")
Save... |
[
0.0015160502,
-0.0058489037,
-0.0074492786,
0.009279303,
-0.0086980015,
-0.019448502,
-0.0034088702,
-0.004514062,
-0.029768407,
0.06401499,
0.0078009306,
0.0407055,
0.012157108,
-0.035940256,
-0.03769134,
-0.000580405,
-0.006950507,
-0.034504943,
-0.046532873,
-0.006013965,
... | Here is the actual output of the second sequence:
input_ids = torch.tensor([[7592]])
output = model(input_ids)
print(output.logits)
tensor([[-0.1008, -0.4061]], grad_fn=)
Most of the time, you should provide an attention_mask to your model to ignore the padding tokens to avoid this silent error. Now the output of the... |
[
0.014582103,
0.00968908,
-0.017065909,
-0.0044939728,
-0.01300828,
-0.0101888245,
0.03111843,
-0.002940662,
-0.04314214,
0.038517635,
0.026135901,
0.020004706,
0.018378671,
-0.03589211,
-0.01943783,
0.029208958,
0.003404977,
-0.040844806,
-0.04048678,
-0.00019800985,
0.014716... | By default, the tokenizer creates an attention_mask for you based on your specific tokenizer's defaults.
attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0]])
output = model(input_ids, attention_mask=attention_mask)
print(output.logits)
tensor([[ 0.0082, -0.2307],
[-0.1008, -0.4061]], grad_fn... |
[
0.027921986,
0.017596014,
-0.019019324,
-0.029135985,
-0.022884587,
-0.007709594,
0.042364392,
0.0069525884,
-0.027545229,
0.04769483,
0.038736347,
-0.0005987145,
0.020484496,
-0.016968084,
-0.013821453,
0.03775957,
0.0067153703,
-0.03516412,
-0.029861594,
0.004911814,
0.0079... | 🤗 Transformers doesn't automatically create an attention_mask to mask a padding token if it is provided because:
Some models don't have a padding token.
For some use-cases, users want a model to attend to a padding token. |
[
0.019577662,
-0.013197698,
-0.006749557,
0.02379748,
-0.04305937,
-0.010377309,
0.008697993,
-0.01962072,
-0.010434722,
0.06435941,
0.025505502,
-0.012573337,
0.04305937,
0.0028401245,
-0.017252455,
0.03183523,
0.015745377,
0.0038574021,
-0.03556704,
0.0016039617,
0.014331594... |
ValueError: Unrecognized configuration class XYZ for this kind of AutoModel
Generally, we recommend using the [AutoModel] class to load pretrained instances of models. This class
can automatically infer and load the correct architecture from a given checkpoint based on the configuration. If you see
this ValueError wh... |
[
0.048446912,
0.0067726206,
-0.021371055,
0.0052038007,
-0.0012232406,
-0.05523416,
-0.008257331,
-0.0068128468,
0.023331167,
0.031654324,
0.017172908,
0.003360712,
0.02597878,
-0.042098492,
-0.015183543,
0.04277137,
0.025993407,
-0.0126236975,
-0.06775546,
-0.0026768674,
0.02... | export with 🤗 Optimum via CLI.
export with 🤗 Optimum with optimum.onnxruntime.
Exporting a 🤗 Transformers model to ONNX with CLI
To export a 🤗 Transformers model to ONNX, first install an extra dependency:
pip install optimum[exporters]
To check out all available arguments, refer to the 🤗 Optimum docs,
or view ... |
[
0.038997713,
-0.013032472,
-0.025438245,
-0.007025428,
-0.036690325,
0.018074542,
-0.01702055,
0.021934433,
-0.005472926,
0.045606527,
0.0068509495,
-0.0334144,
0.011131013,
-0.01847335,
-0.021364707,
0.051901996,
-0.014321475,
-0.033158027,
-0.03794372,
-0.033101052,
0.00979... | from transformers import AutoProcessor, AutoModelForQuestionAnswering
processor = AutoProcessor.from_pretrained("openai-community/gpt2-medium")
model = AutoModelForQuestionAnswering.from_pretrained("openai-community/gpt2-medium")
ValueError: Unrecognized configuration class for this kind of AutoModel: AutoModelForQues... |
[
0.042139005,
0.013317934,
-0.040603455,
0.018426588,
0.02142386,
-0.022693641,
-0.0065814513,
-0.020803735,
0.007788481,
0.03038615,
0.018057466,
-0.0056291157,
0.022560757,
-0.035612922,
-0.03201029,
0.036705524,
-0.0035398833,
-0.002486039,
-0.06337092,
-0.0043593347,
0.002... |
Export to ONNX
Deploying 🤗 Transformers models in production environments often requires, or can benefit from exporting the models into
a serialized format that can be loaded and executed on specialized runtimes and hardware.
🤗 Optimum is an extension of Transformers that enables exporting models from PyTorch or Te... |
[
0.028501188,
-0.011382106,
-0.017606584,
0.010103297,
-0.011685912,
-0.01660332,
-0.010152753,
-0.0077505712,
-0.008541878,
0.053752366,
-0.0031828918,
-0.00640111,
0.02153486,
-0.036400132,
0.0074608964,
0.03572187,
-0.030154455,
-0.04193928,
-0.058443688,
-0.00097323715,
-0... | from transformers import AutoTokenizer
from optimum.onnxruntime import ORTModelForQuestionAnswering
tokenizer = AutoTokenizer.from_pretrained("distilbert_base_uncased_squad_onnx")
model = ORTModelForQuestionAnswering.from_pretrained("distilbert_base_uncased_squad_onnx")
inputs = tokenizer("What am I using?", "Using Dis... |
[
0.034920406,
-0.024019009,
-0.010609394,
0.033752397,
-0.009883134,
-0.05387805,
-0.02115889,
-0.015468601,
0.020305347,
0.053967897,
0.021218788,
0.020979198,
0.03345291,
-0.025516454,
-0.023899214,
0.019930987,
0.012413815,
-0.012563559,
-0.06397083,
0.006805885,
0.00381286... | optimum-cli export onnx --help
To export a model's checkpoint from the 🤗 Hub, for example, distilbert/distilbert-base-uncased-distilled-squad, run the following command:
optimum-cli export onnx --model distilbert/distilbert-base-uncased-distilled-squad distilbert_base_uncased_squad_onnx/
You should see the logs indi... |
[
0.034159206,
-0.028228367,
-0.004444337,
0.041015316,
0.0069774576,
-0.037071537,
0.002868721,
-0.03506931,
0.022600895,
0.0626151,
0.0042623165,
0.035676043,
0.035312004,
-0.032763716,
-0.02134192,
0.006840942,
0.014372046,
-0.0043381583,
-0.080756485,
-0.015926806,
0.023025... |
Validating ONNX model distilbert_base_uncased_squad_onnx/model.onnx
-[✓] ONNX model output names match reference model (start_logits, end_logits)
- Validating ONNX Model output "start_logits":
-[✓] (2, 16) matches (2, 16)
-[✓] all values close (atol: 0.0001)
- Validating ONNX Model output ... |
[
0.040458,
-0.005516663,
-0.036219545,
-0.0017922672,
-0.00812865,
-0.013834265,
-0.018287608,
-0.025949435,
0.00507948,
0.060523983,
-0.004920167,
0.033463065,
0.018984139,
-0.026394028,
-0.016405497,
0.047986448,
-0.001682045,
-0.03390766,
-0.068941616,
0.008847409,
-0.00499... | optimum-cli export onnx --model local_path --task question-answering distilbert_base_uncased_squad_onnx/
The resulting model.onnx file can then be run on one of the many
accelerators that support the ONNX
standard. For example, we can load and run the model with ONNX
Runtime as follows:
thon |
[
0.037600055,
-0.011280016,
-0.015593381,
0.015806211,
0.009151711,
-0.026646378,
-0.012322886,
-0.033542085,
0.020658746,
0.043474175,
0.013301905,
-0.022787051,
0.034308277,
-0.038650017,
-0.00079988793,
0.034989335,
-0.018175725,
-0.042878248,
-0.07378124,
-0.026589623,
-0.... | from optimum.onnxruntime import ORTModelForSequenceClassification
from transformers import AutoTokenizer
model_checkpoint = "distilbert_base_uncased_squad"
save_directory = "onnx/"
Load a model from transformers and export it to ONNX
ort_model = ORTModelForSequenceClassification.from_pretrained(model_checkpoint, export... |
[
0.04372679,
0.0021710976,
-0.031901844,
0.011257806,
-0.006142877,
-0.05830239,
0.0043599186,
-0.022203682,
0.0053985007,
0.03496442,
-0.0021640083,
-0.014674848,
0.037062854,
-0.033801775,
-0.017808318,
0.041997004,
0.037459854,
-0.023252899,
-0.05333988,
-0.009917929,
0.013... | tranformers.onnx is no longer maintained, please export models with 🤗 Optimum as described above. This section will be removed in the future versions.
To export a 🤗 Transformers model to ONNX with tranformers.onnx, install extra dependencies:
pip install transformers[onnx]
Use transformers.onnx package as a Python ... |
[
0.036386475,
-0.03293526,
-0.02399484,
-0.013038734,
-0.012227997,
-0.01570896,
0.004273105,
-0.046383083,
0.015151113,
0.08485219,
-0.0079883635,
0.0130908,
0.053047493,
-0.03483938,
-0.015694084,
0.04694837,
-0.017360186,
-0.02912703,
-0.0621813,
-0.011253625,
0.012428822,
... | python -m transformers.onnx --model=distilbert/distilbert-base-uncased onnx/
This exports an ONNX graph of the checkpoint defined by the --model argument. Pass any checkpoint on the 🤗 Hub or one that's stored locally.
The resulting model.onnx file can then be run on one of the many accelerators that support the ONNX s... |
[
0.035532612,
0.008670777,
-0.031372983,
0.03764172,
-0.01950925,
-0.066905595,
-0.014163246,
-0.041596297,
0.0042694793,
0.03690939,
-0.008407139,
0.008326583,
0.040658917,
-0.04399834,
-0.035151802,
0.022907257,
0.013335714,
-0.0038593747,
-0.07610365,
-0.021091081,
0.030347... | The process is identical for TensorFlow checkpoints on the Hub. For instance, here's how you would
export a pure TensorFlow checkpoint from the Keras organization:
optimum-cli export onnx --model keras-io/transformers-qa distilbert_base_cased_squad_onnx/
Exporting a 🤗 Transformers model to ONNX with optimum.onnxrunti... |
[
0.016806686,
-0.0060933176,
-0.019252595,
-0.016205937,
-0.008303218,
-0.025002627,
-0.0009252617,
-0.013988884,
-0.008360432,
0.07580888,
0.009654905,
-0.004569988,
0.02164129,
-0.030094694,
-0.0038440824,
-0.005324501,
-0.032697942,
-0.037933048,
-0.06156253,
0.0029644133,
... | from transformers import AutoTokenizer
from onnxruntime import InferenceSession
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
session = InferenceSession("onnx/model.onnx")
ONNX Runtime expects NumPy arrays as input
inputs = tokenizer("Using DistilBERT with ONNX Runtime!", return_tensor... |
[
0.009952175,
-0.03636626,
-0.020536935,
0.022522956,
-0.02394995,
-0.055785142,
-0.012732605,
-0.02940783,
0.0014067653,
0.047723364,
0.02359688,
0.014277289,
0.03436553,
-0.044339772,
-0.044810534,
0.0087017175,
0.0048105856,
-0.0036814958,
-0.08397194,
-0.0032622244,
0.0444... | The required output names (like ["last_hidden_state"]) can be obtained by taking a look at the ONNX configuration of
each model. For example, for DistilBERT we have:
thon
from transformers.models.distilbert import DistilBertConfig, DistilBertOnnxConfig
config = DistilBertConfig()
onnx_config = DistilBertOnnxConfig(co... |
[
0.03623696,
0.01115467,
-0.06582443,
-0.015603965,
0.023301177,
-0.02202995,
-0.00439691,
-0.014416555,
0.012237309,
0.039673466,
0.0028462918,
-0.00051992846,
0.02944777,
-0.03808094,
-0.0069987345,
0.043892264,
0.033806264,
-0.01306151,
-0.066383205,
-0.008339809,
0.0093386... | Exporting a model for an unsupported architecture
If you wish to contribute by adding support for a model that cannot be currently exported, you should first check if it is
supported in optimum.exporters.onnx,
and if it is not, contribute to 🤗 Optimum
directly.
Exporting a model with transformers.onnx
tranformers.onn... |
[
0.022651881,
0.03052102,
-0.030296188,
-0.032432098,
-0.026572399,
-0.0040786033,
0.0065306835,
-0.0026804258,
-0.02499857,
0.028638048,
0.068461515,
-0.0070822258,
0.022904817,
-0.053060483,
0.028609943,
0.0070330435,
0.008887912,
-0.0024046544,
-0.09268723,
0.01122055,
-0.0... |
Fine-tune a pretrained model
[[open-in-colab]]
There are significant benefits to using a pretrained model. It reduces computation costs, your carbon footprint, and allows you to use state-of-the-art models without having to train one from scratch. 🤗 Transformers provides access to thousands of pretrained models for a... |
[
0.03981337,
0.0048598307,
-0.041741233,
0.024624115,
-0.033270307,
-0.049949273,
0.005779949,
-0.032715313,
0.011589108,
0.04381515,
-0.013874798,
0.018197892,
0.029692069,
-0.051146887,
-0.016270027,
0.038411282,
0.008375997,
-0.022287307,
-0.07296684,
-0.03446792,
0.0304369... | The process is identical for TensorFlow checkpoints on the Hub. For example, export a pure TensorFlow checkpoint like so:
python -m transformers.onnx --model=keras-io/transformers-qa onnx/
To export a model that's stored locally, save the model's weights and tokenizer files in the same directory (e.g. local-pt-checkpo... |
[
0.008784953,
0.016604057,
0.044997137,
0.029202687,
0.008167094,
-0.007329079,
-0.0017994238,
-0.011994976,
-0.0047795256,
0.05289436,
0.0031620858,
-0.0013289282,
-0.013642598,
-0.027526658,
-0.04025312,
0.0017221916,
-0.0045842254,
-0.047298126,
-0.04590617,
0.010645629,
-0... | As you now know, you need a tokenizer to process the text and include a padding and truncation strategy to handle any variable sequence lengths. To process your dataset in one step, use 🤗 Datasets map method to apply a preprocessing function over the entire dataset: |
[
0.026338255,
0.0051213275,
0.012594773,
0.015808424,
-0.017791314,
-0.02345281,
0.007870024,
0.010878547,
-0.018201567,
0.035965532,
0.022153674,
-0.0099691525,
0.0031350183,
-0.021333167,
0.00049144914,
0.018721221,
-0.031780947,
-0.06268669,
-0.029045926,
0.0017461402,
-0.0... | from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length", truncation=True)
tokenized_datasets = dataset.map(tokenize_function, batched=True)
If you like, you can create a... |
[
0.017898757,
0.020392392,
0.008693088,
-0.00809046,
-0.019145574,
-0.028926164,
0.020517074,
0.006015894,
-0.026072338,
0.03978733,
0.05267111,
0.019353377,
0.00097321026,
-0.06721731,
-0.006611596,
0.0008658454,
0.00357421,
-0.058572713,
-0.06455743,
-0.0058808224,
-0.011872... | If you like, you can create a smaller subset of the full dataset to fine-tune on to reduce the time it takes:
small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000)) |
[
0.028790256,
0.010646252,
-0.021920806,
-0.033258192,
-0.024001189,
-0.019114384,
0.011281536,
-0.018681554,
-0.0098154945,
0.022074392,
0.017438909,
-0.0039129336,
0.04741596,
-0.034179702,
0.027729122,
-0.001133564,
-0.025927985,
-0.0113373855,
-0.08444397,
-0.0021362314,
-... | Fine-tune a pretrained model with 🤗 Transformers [Trainer].
Fine-tune a pretrained model in TensorFlow with Keras.
Fine-tune a pretrained model in native PyTorch.
Prepare a dataset
Before you can fine-tune a pretrained model, download a dataset and prepare it for training. The previous tutorial showed you how to pro... |
[
0.010794558,
0.007839503,
0.017371707,
-0.008061849,
-0.038243577,
-0.016511012,
0.0054116235,
0.008040331,
-0.04931786,
0.040710904,
0.038673922,
0.023482645,
0.012931951,
-0.024199892,
-0.025275761,
0.0059531447,
-0.00085352315,
-0.0511827,
-0.08618432,
0.012989331,
-0.0039... | small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
Train
At this point, you should follow the section corresponding to the framework you want to use. You can use the links
in the right sidebar to ju... |
[
0.010660182,
-0.023660244,
-0.0013357907,
0.012536008,
0.007156897,
-0.01061443,
0.05320287,
0.026091628,
-0.015058896,
0.06860164,
0.009104619,
0.0025539338,
0.03017008,
-0.030875966,
-0.03626161,
-0.0137386285,
0.004637277,
-0.009601354,
-0.040340062,
-0.03584331,
0.0151111... |
from datasets import load_dataset
dataset = load_dataset("yelp_review_full")
dataset["train"][100]
{'label': 0,
'text': 'My expectations for McDonalds are t rarely high. But for one to still fail so spectacularlythat takes something special!\nThe cashier took my friends\'s order, then promptly ignored me. I had to f... |
[
0.036852144,
-0.0066171573,
-0.04598619,
-0.018641498,
0.008114366,
-0.0015726071,
0.024328735,
-0.005385641,
0.033118103,
0.03294576,
0.035358526,
-0.0071234074,
0.058394708,
-0.024931926,
0.021398947,
0.03420959,
-0.011051335,
0.0047537256,
-0.06445535,
-0.0034270629,
-0.01... | Train with PyTorch Trainer
🤗 Transformers provides a [Trainer] class optimized for training 🤗 Transformers models, making it easier to start training without manually writing your own training loop. The [Trainer] API supports a wide range of training options and features such as logging, gradient accumulation, and mi... |
[
0.014454641,
-0.00023235468,
0.014293587,
0.0041840617,
0.007005871,
0.011803953,
-0.010300778,
-0.014186217,
0.00050958653,
0.053228512,
0.028291907,
-0.059053317,
0.0064589567,
-0.04010257,
0.02842612,
0.023634749,
-0.022802634,
-0.052369557,
-0.053819045,
-0.03900203,
-0.0... | from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5) |
[
-0.00038690036,
-0.011734915,
-0.0020872648,
-0.03350502,
0.005486719,
0.0048986133,
-0.015705477,
-0.004970002,
-0.00859382,
0.038155474,
0.04489999,
-0.033205867,
0.021878887,
-0.055016764,
-0.017432401,
0.03772034,
-0.040684666,
-0.044165708,
-0.04462803,
-0.00859382,
0.00... | You will see a warning about some of the pretrained weights not being used and some weights being randomly
initialized. Don't worry, this is completely normal! The pretrained head of the BERT model is discarded, and replaced with a randomly initialized classification head. You will fine-tune this new model head on your... |
[
0.029872624,
0.028351467,
0.000025112104,
-0.00097245385,
-0.060440633,
-0.032972887,
0.013567271,
-0.0030060958,
-0.0059940824,
0.034798276,
0.0034370902,
0.030915702,
0.041549314,
-0.03288596,
-0.008503991,
0.04375137,
-0.016022852,
-0.02065876,
-0.04343265,
0.002709108,
-0... | Training hyperparameters
Next, create a [TrainingArguments] class which contains all the hyperparameters you can tune as well as flags for activating different training options. For this tutorial you can start with the default training hyperparameters, but feel free to experiment with these to find your optimal setting... |
[
0.010045628,
0.028937727,
-0.010340031,
-0.009061889,
-0.04788009,
0.013707723,
0.00795608,
0.007381634,
0.011668438,
0.048368372,
0.02648197,
0.033030655,
0.0017341095,
-0.033863604,
0.034524217,
0.04900026,
0.004132422,
-0.009966642,
-0.052389495,
0.0033928228,
-0.001745777... | from transformers import TrainingArguments
training_args = TrainingArguments(output_dir="test_trainer")
Evaluate
[Trainer] does not automatically evaluate model performance during training. You'll need to pass [Trainer] a function to compute and report metrics. The 🤗 Evaluate library provides a simple accuracy functi... |
[
0.013882919,
0.042525277,
-0.04130946,
-0.010277884,
-0.018717907,
-0.00036470054,
0.003898386,
0.009740663,
0.013402248,
0.043854192,
0.032713924,
0.021135401,
0.009959793,
-0.028359609,
0.013677927,
0.034551788,
-0.0010832776,
-0.020018548,
-0.052930396,
-0.011133196,
0.029... | import numpy as np
import evaluate
metric = evaluate.load("accuracy")
Call [~evaluate.compute] on metric to calculate the accuracy of your predictions. Before passing your predictions to compute, you need to convert the logits to predictions (remember all 🤗 Transformers models return logits):
def compute_metrics(eva... |
[
-0.010347682,
0.010682417,
-0.027943106,
0.023882624,
-0.03868374,
-0.0136440955,
-0.017551765,
0.02028786,
-0.020113215,
0.008957803,
0.024712184,
0.029893303,
-0.012348816,
-0.025250671,
0.0007194986,
0.017784623,
0.0026869772,
-0.032134574,
-0.065491654,
-0.010966214,
0.01... | def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return metric.compute(predictions=predictions, references=labels)
If you'd like to monitor your evaluation metrics during fine-tuning, specify the evaluation_strategy parameter in your training arguments ... |
[
0.01884674,
0.025280137,
-0.01472313,
-0.012151187,
-0.05985611,
-0.016437758,
-0.001748283,
0.0150065385,
0.0010734139,
0.008204708,
0.017075429,
0.026399605,
0.0065857307,
-0.017939828,
0.011711902,
0.029729668,
-0.006142903,
-0.028836928,
-0.07017222,
0.009607586,
-0.01144... | If you'd like to monitor your evaluation metrics during fine-tuning, specify the evaluation_strategy parameter in your training arguments to report the evaluation metric at the end of each epoch:
from transformers import TrainingArguments, Trainer
training_args = TrainingArguments(output_dir="test_trainer", evaluation... |
[
0.025814578,
0.034546178,
-0.019391486,
-0.052090857,
-0.038402747,
-0.013586262,
0.012160418,
0.021279033,
0.006776157,
0.01800638,
0.044866577,
0.03905456,
0.02395419,
-0.040847052,
0.03039086,
0.034817766,
-0.010829629,
-0.030771084,
-0.07745731,
0.0031809914,
-0.013178878... | Trainer
Create a [Trainer] object with your model, training arguments, training and test datasets, and evaluation function:
trainer = Trainer(
model=model,
args=training_args,
train_dataset=small_train_dataset,
eval_dataset=small_eval_dataset,
compute_metrics=compute_metrics,
)
Then fine-tun... |
[
-0.0045876247,
-0.0038207069,
0.0017871609,
-0.001757664,
-0.013950265,
-0.040282257,
0.023639105,
0.0010349917,
-0.020266056,
0.023583584,
0.006204745,
-0.00005086034,
0.027609032,
-0.015754778,
-0.030648941,
0.020751888,
0.017920192,
-0.02627647,
-0.0570781,
-0.0059653,
0.0... | from datasets import load_dataset
dataset = load_dataset("glue", "cola")
dataset = dataset["train"] # Just take the training split for now
Next, load a tokenizer and tokenize the data as NumPy arrays. Note that the labels are already a list of 0 and 1s,
so we can just convert that directly to a NumPy array without to... |
[
-0.0034723599,
-0.013954581,
-0.020873968,
0.011095628,
-0.02851714,
-0.03369944,
0.019107932,
-0.0019198405,
-0.016690489,
0.03647878,
-0.012832713,
-0.028922461,
0.010205372,
-0.01968696,
-0.021568801,
0.03193341,
-0.035407577,
-0.058481853,
-0.047538217,
-0.0011508187,
-0.... | from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
tokenized_data = tokenizer(dataset["sentence"], return_tensors="np", padding=True)
Tokenizer returns a BatchEncoding, but we convert that to a dict for Keras
tokenized_data = dict(tokenized_data)
labels = np.... |
[
0.040764276,
0.012973637,
-0.019134538,
-0.037399963,
0.006935394,
-0.017396308,
0.00460841,
-0.010688707,
-0.006746151,
0.016260853,
0.05124972,
-0.04704433,
0.02722291,
-0.050408643,
0.014256282,
0.05741763,
-0.008621056,
-0.026479958,
-0.06358554,
0.0014517367,
0.00768886,... | Finally, load, compile, and fit the model. Note that Transformers models all have a default task-relevant loss function, so you don't need to specify one unless you want to: |
[
0.029833382,
0.0065909307,
-0.0030235094,
-0.0069215437,
0.008176452,
-0.012890353,
-0.015698787,
-0.006708245,
-0.024671553,
0.012982783,
0.007927603,
-0.042887263,
0.049371544,
-0.054120995,
0.018272592,
0.017803334,
-0.0071917223,
-0.039559804,
-0.059894282,
-0.019026246,
... | from transformers import TFAutoModelForSequenceClassification
from tensorflow.keras.optimizers import Adam
Load and compile our model
model = TFAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased")
Lower learning rates are often better for fine-tuning transformers
model.compile(optimizer=Ada... |
[
0.03129202,
-0.00014552243,
-0.0031802827,
-0.018179042,
-0.028199207,
-0.028353147,
0.06314383,
0.030340387,
-0.035014596,
0.016933518,
0.023301082,
-0.026267946,
0.007578099,
-0.0587775,
-0.004579747,
0.017801186,
0.001423955,
-0.039045054,
-0.042711653,
0.027751377,
0.0326... | You don't have to pass a loss argument to your models when you compile() them! Hugging Face models automatically
choose a loss that is appropriate for their task and model architecture if this argument is left blank. You can always
override this by specifying a loss yourself if you want to! |
[
0.017345851,
0.029001383,
-0.022912467,
-0.0024345357,
-0.010988913,
-0.0067177373,
0.03230012,
-0.015971377,
-0.01841794,
0.046787065,
-0.007724539,
-0.017469553,
0.02867151,
-0.058662515,
-0.007648943,
0.043900672,
0.024987921,
-0.020355947,
-0.059212305,
-0.046704598,
0.02... |
Train a TensorFlow model with Keras
You can also train 🤗 Transformers models in TensorFlow with the Keras API!
Loading data for Keras
When you want to train a 🤗 Transformers model with the Keras API, you need to convert your dataset to a format that
Keras understands. If your dataset is small, you can just convert ... |
[
0.011713639,
-0.01401478,
-0.019005205,
0.0059885113,
-0.018118018,
-0.00077152334,
0.013474151,
0.019739907,
0.006802921,
0.05201133,
0.011394806,
-0.0017899688,
0.019906254,
-0.031467408,
-0.02097365,
0.02930489,
0.000065304404,
-0.013384045,
-0.056946307,
-0.030413873,
0.0... | [~TFPreTrainedModel.prepare_tf_dataset]: This is the method we recommend in most cases. Because it is a method
on your model, it can inspect the model to automatically figure out which columns are usable as model inputs, and
discard the others to make a simpler, more performant dataset.
[~datasets.Dataset.to_tf_dataset... |
[
0.002216305,
-0.013552017,
-0.017479734,
0.03846934,
-0.011985108,
-0.0009993394,
0.006964037,
0.003917271,
-0.014875184,
0.024986966,
-0.013726117,
-0.009868041,
0.011483697,
-0.004188868,
-0.04089283,
0.0052091,
-0.019401807,
-0.051116034,
-0.04153352,
-0.0071172463,
-0.002... | Before you can use [~TFPreTrainedModel.prepare_tf_dataset], you will need to add the tokenizer outputs to your dataset as columns, as shown in
the following code sample:
def tokenize_dataset(data):
# Keys of the returned dictionary will be added to the dataset as columns
return tokenizer(data["text"])
dataset ... |
[
0.02843891,
0.0020727534,
0.031814013,
0.03695004,
-0.010895712,
-0.0136985155,
0.042614345,
0.0060348306,
-0.023552349,
0.0017939406,
-0.015466776,
-0.027734542,
-0.023024071,
-0.020074526,
-0.0121503705,
-0.02339093,
-0.012253091,
-0.060634457,
-0.033633634,
0.016083099,
-0... | def tokenize_dataset(data):
# Keys of the returned dictionary will be added to the dataset as columns
return tokenizer(data["text"])
dataset = dataset.map(tokenize_dataset)
Remember that Hugging Face datasets are stored on disk by default, so this will not inflate your memory usage! Once the
columns have been ... |
[
0.01864668,
0.014303949,
-0.027576983,
0.021559015,
-0.01650753,
-0.033865564,
0.011191874,
0.012899327,
-0.016198255,
0.034922253,
0.0054638507,
-0.012641598,
0.022847658,
-0.03685522,
-0.03149446,
0.0021826408,
-0.035308845,
-0.064432204,
-0.062061097,
-0.03731913,
0.005370... | tf_dataset = model.prepare_tf_dataset(dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer) |
[
0.024570983,
0.002608636,
0.0022889588,
0.035379954,
-0.019088786,
-0.028823925,
0.02530571,
-0.013557135,
-0.024782924,
0.060473725,
0.0062840395,
-0.0086754365,
0.031112883,
-0.030095568,
-0.050950527,
0.013578329,
-0.0007484153,
-0.03860145,
-0.06962956,
-0.025122028,
-0.0... |
This approach works great for smaller datasets, but for larger datasets, you might find it starts to become a problem. Why?
Because the tokenized array and labels would have to be fully loaded into memory, and because NumPy doesn’t handle
“jagged” arrays, so every tokenized sample would have to be padded to the lengt... |
[
0.06096801,
0.005438003,
-0.036695153,
0.0011215477,
-0.0087125,
-0.010798043,
0.010596635,
0.0053080632,
-0.0066529457,
0.0134878075,
0.033342693,
-0.021816984,
0.031263646,
-0.0697,
-0.01729506,
0.008660524,
0.00018871804,
-0.021894949,
-0.0651261,
0.03014616,
0.01309149,
... | model.compile(optimizer=Adam(3e-5)) # No loss argument!
model.fit(tf_dataset)
Train in native PyTorch |
[
0.022692079,
-0.022925716,
-0.031803954,
0.0016610192,
-0.011302232,
-0.0222102,
0.0066185226,
-0.020268084,
0.014208103,
0.04818781,
0.03317658,
0.009958814,
0.02320316,
-0.045939047,
-0.0126310475,
0.02073536,
-0.02257526,
-0.03370226,
-0.09211173,
0.0067754984,
-0.01893927... | Train in native PyTorch
[Trainer] takes care of the training loop and allows you to fine-tune a model in a single line of code. For users who prefer to write their own training loop, you can also fine-tune a 🤗 Transformers model in native PyTorch.
At this point, you may need to restart your notebook or execute the fo... |
[
0.004903862,
-0.057421595,
0.0298765,
0.03215034,
-0.00402239,
0.001226865,
-0.0044433377,
-0.0025724587,
-0.0027181713,
0.021802938,
0.014089159,
-0.004616034,
0.0031139343,
-0.02518491,
-0.030855114,
0.0032974244,
-0.014564075,
-0.030106762,
-0.03856889,
-0.0018978629,
-0.0... | Remove the text column because the model does not accept raw text as an input:
tokenized_datasets = tokenized_datasets.remove_columns(["text"])
Rename the label column to labels because the model expects the argument to be named labels:
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
Set th... |
[
0.010380091,
-0.03399293,
0.009371953,
0.009020971,
-0.011134327,
0.0007617045,
0.0090060355,
0.0030804228,
-0.011888565,
0.017832847,
0.025658987,
0.02594276,
0.010454768,
-0.028601257,
-0.033664353,
-0.0014067263,
-0.008094978,
-0.037308585,
-0.042745065,
0.00860278,
-0.008... | tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
Set the format of the dataset to return PyTorch tensors instead of lists:
tokenized_datasets.set_format("torch")
Then create a smaller subset of the dataset as previously shown to speed up the fine-tuning:
small_train_dataset = tokenized_datas... |
[
0.025605563,
-0.00031598264,
0.005871383,
0.025412833,
-0.012892264,
-0.03992265,
0.004178112,
0.0052105943,
-0.019355603,
0.031029537,
0.024366584,
-0.013477337,
0.032323584,
-0.04644794,
-0.05366155,
0.028992105,
-0.02022289,
-0.061453354,
-0.05027501,
-0.011137043,
-0.0025... |
Note that in the code sample above, you need to pass the tokenizer to prepare_tf_dataset so it can correctly pad batches as they're loaded.
If all the samples in your dataset are the same length and no padding is necessary, you can skip this argument.
If you need to do something more complex than just padding samples... |
[
0.012866844,
-0.022470046,
0.0046716323,
-0.00057312334,
-0.0017572774,
0.029632734,
0.0025199377,
-0.017560137,
-0.0023809439,
0.030759124,
0.048405908,
-0.03705536,
0.017112471,
-0.020101737,
0.023914136,
0.047395043,
-0.006202368,
-0.04089664,
-0.055077605,
-0.021314774,
-... | from torch.utils.data import DataLoader
train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)
Load your model with the number of expected labels:
from transformers import AutoModelForSequenceClassification
model = AutoModelForSequ... |
[
0.039255485,
-0.005234299,
-0.01586834,
-0.0130311875,
0.009299945,
0.031201633,
-0.04418354,
-0.01678355,
-0.0019659423,
0.045281794,
0.025991974,
-0.053420126,
0.030976351,
-0.054631017,
0.021936888,
0.016248504,
-0.025921574,
-0.029624656,
-0.05730625,
-0.011897734,
0.0172... | from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5)
Optimizer and learning rate scheduler
Create an optimizer and learning rate scheduler to fine-tune the model. Let's use the AdamW optimizer from PyTorch:
... |
[
0.010275249,
0.0029749768,
-0.0339183,
0.0236288,
-0.019353382,
0.011835776,
0.014693179,
-0.0057539972,
0.005411964,
0.05150451,
0.019068355,
0.0010065042,
0.04976584,
-0.0729671,
0.02139133,
0.01583329,
-0.013260915,
-0.02352904,
-0.061223954,
0.00044669188,
0.0151207205,
... | Lastly, specify device to use a GPU if you have access to one. Otherwise, training on a CPU may take several hours instead of a couple of minutes.
import torch
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
model.to(device)
Get free access to a cloud GPU if you don't have one with... |
[
0.018082678,
-0.02144254,
0.004070045,
-0.0019863548,
-0.03103184,
0.0064060846,
0.012545399,
0.01078616,
-0.015501499,
0.04141424,
0.021716518,
0.021356018,
0.026821198,
-0.025162898,
-0.015342879,
0.0292726,
-0.0021882348,
-0.04986436,
-0.06292888,
0.004538695,
-0.018414339... | small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
DataLoader
Create a DataLoader for your training and test datasets so you can iterate over batches of data:
from torch.utils.data import DataLoade... |
[
0.01690185,
-0.0040504225,
-0.048254993,
0.004673565,
-0.008744992,
-0.00733067,
0.01589362,
-0.0027673803,
0.04601448,
0.053408165,
-0.040077128,
0.037220478,
0.007414689,
-0.03458788,
0.006430965,
0.04441812,
-0.004218461,
-0.05071955,
-0.070352025,
0.021186827,
-0.00083625... | Great, now you are ready to train! 🥳
Training loop
To keep track of your training progress, use the tqdm library to add a progress bar over the number of training steps:
from tqdm.auto import tqdm
progress_bar = tqdm(range(num_training_steps))
model.train()
for epoch in range(num_epochs):
for batch in train_dat... |
[
0.015884861,
0.027639376,
-0.033438835,
-0.011224076,
-0.028516367,
-0.03731457,
-0.014809839,
0.0238768,
-0.012850754,
0.0639355,
0.016323358,
0.049818773,
0.008154606,
-0.03485334,
0.010941176,
0.020962926,
-0.00668706,
-0.05225172,
-0.074119925,
0.034032926,
0.023890944,
... | optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
progress_bar.update(1)
Evaluate
Just like how you added an evaluation function to [Trainer], you need to do the same when you write your own training loop. But instead of calculating and reporting the metric at the end of each epoch,... |
[
0.04644593,
0.01503073,
-0.027661007,
-0.019482728,
-0.036090497,
0.014053802,
-0.02869376,
0.0040402934,
-0.014221275,
0.045692302,
0.023404395,
-0.026014186,
0.026488695,
-0.047618244,
-0.0049125506,
0.0372349,
-0.0089947125,
-0.022022739,
-0.05738752,
0.024046376,
0.025372... | from torch.optim import AdamW
optimizer = AdamW(model.parameters(), lr=5e-5)
Create the default learning rate scheduler from [Trainer]:
from transformers import get_scheduler
num_epochs = 3
num_training_steps = num_epochs * len(train_dataloader)
lr_scheduler = get_scheduler(
name="linear", optimizer=optimizer, n... |
[
0.014113777,
-0.0043339273,
-0.024563674,
0.0067753256,
-0.03544126,
0.0060090474,
-0.016066896,
-0.0062585333,
0.0053354353,
0.045677315,
0.028227555,
0.029368062,
0.012552707,
-0.040716108,
-0.0054958193,
0.038064428,
-0.022254147,
-0.046447158,
-0.056341056,
0.010685127,
0... | import evaluate
metric = evaluate.load("accuracy")
model.eval()
for batch in eval_dataloader:
batch = {k: v.to(device) for k, v in batch.items()}
with torch.no_grad():
outputs = model(**batch)
logits = outputs.logits
predictions = torch.argmax(logits, dim=-1)
metric.add_batch(predicti... |
[
0.04814391,
-0.014508927,
-0.03736585,
-0.010377814,
-0.022399498,
-0.019855075,
-0.014994941,
-0.0036879836,
-0.0050030784,
0.040739354,
0.026001714,
0.024200605,
0.058550313,
-0.048601333,
-0.013829938,
0.027531227,
-0.018625747,
-0.02585877,
-0.061180502,
-0.011442755,
0.0... | metric.compute()
Additional resources
For more fine-tuning examples, refer to:
🤗 Transformers Examples includes scripts
to train common NLP tasks in PyTorch and TensorFlow.
🤗 Transformers Notebooks contains various notebooks on how to fine-tune a model for specific tasks in PyTorch and TensorFlow. |
[
-0.0076755257,
0.0008149244,
-0.056410313,
0.020950714,
-0.014250327,
-0.019650528,
0.005928402,
0.023403335,
0.010541843,
0.02928372,
-0.040098898,
0.028456328,
0.018069621,
-0.059542578,
0.013319512,
0.027835786,
0.004026142,
-0.035105005,
-0.05419409,
0.019591428,
0.011842... | Get free access to a cloud GPU if you don't have one with a hosted notebook like Colaboratory or SageMaker StudioLab.
Great, now you are ready to train! 🥳
Training loop
To keep track of your training progress, use the tqdm library to add a progress bar over the number of training steps: |
[
0.028493116,
-0.001608854,
-0.06376558,
-0.011934772,
0.03514482,
-0.013459416,
-0.02042314,
0.0032301182,
0.017529862,
0.040364068,
0.03239337,
0.002772725,
0.05105785,
-0.048845343,
-0.0075239413,
0.026351523,
0.008126708,
-0.013587061,
-0.049838133,
-0.0062014014,
-0.00438... |
How 🤗 Transformers solve tasks
In What 🤗 Transformers can do, you learned about natural language processing (NLP), speech and audio, computer vision tasks, and some important applications of them. This page will look closely at how models solve these tasks and explain what's happening under the hood. There are many ... |
[
0.030704325,
0.0009354186,
-0.03681861,
-0.0383073,
-0.013119121,
-0.0066758646,
-0.012414649,
-0.018236509,
0.020137252,
0.050695367,
0.002753088,
-0.013624214,
0.052316982,
-0.055400707,
0.025826192,
0.004120494,
-0.044501334,
-0.049897853,
-0.043491147,
-0.022144333,
-0.01... | Wav2Vec2 for audio classification and automatic speech recognition (ASR)
Vision Transformer (ViT) and ConvNeXT for image classification
DETR for object detection
Mask2Former for image segmentation
GLPN for depth estimation
BERT for NLP tasks like text classification, token classification and question answering that use... |
[
0.0027193981,
0.045831297,
-0.014177222,
-0.032101482,
0.008990092,
-0.0014357234,
-0.050920554,
-0.017113334,
-0.017700555,
0.036771294,
0.032045554,
-0.03067537,
0.045635555,
-0.06537741,
-0.011912222,
0.029417036,
-0.053353332,
-0.045579627,
-0.058554444,
-0.033247963,
-0.... | Speech and audio
Wav2Vec2 is a self-supervised model pretrained on unlabeled speech data and finetuned on labeled data for audio classification and automatic speech recognition.
This model has four main components:
A feature encoder takes the raw audio waveform, normalizes it to zero mean and unit variance, and conv... |
[
0.008029392,
0.06293917,
-0.043415066,
-0.04338689,
0.027004113,
-0.01670677,
-0.04789462,
-0.032765556,
-0.007902613,
0.03935811,
0.030370824,
-0.00978318,
0.06677074,
-0.061474156,
0.014319083,
0.027764793,
-0.03842839,
-0.019988962,
-0.06789767,
-0.02896216,
-0.02041156,
... | Before you go further, it is good to have some basic knowledge of the original Transformer architecture. Knowing how encoders, decoders, and attention work will aid you in understanding how different Transformer models work. If you're just getting started or need a refresher, check out our course for more information! ... |
[
-0.0070103803,
0.005972873,
-0.043517675,
-0.010929853,
0.010281411,
-0.014986219,
-0.04109682,
-0.028805241,
-0.034583583,
0.011419787,
0.06294212,
0.002462279,
0.042076692,
-0.043517675,
0.0028855677,
0.0447281,
-0.027983882,
-0.01743589,
-0.04043397,
-0.026802275,
-0.00571... | About half of the feature vectors are randomly masked, and the masked feature vector is fed to a context network, which is a Transformer encoder that also adds relative positional embeddings.
The pretraining objective of the context network is a contrastive task. The model has to predict the true quantized speech repr... |
[
0.027881209,
0.03161939,
-0.021513004,
-0.007631502,
0.0024988921,
-0.00899084,
-0.030067971,
-0.02352246,
-0.014982271,
0.04914303,
0.030703314,
0.019636527,
0.030703314,
-0.041046105,
-0.0013990471,
0.011916373,
-0.012706857,
-0.059338067,
-0.078782514,
-0.007609339,
-0.002... | Waveforms are continuous by nature, so they can't be divided into separate units like a sequence of text can be split into words. That's why the feature vectors are passed to a quantization module, which aims to learn discrete speech units. The speech unit is chosen from a collection of codewords, known as a codebook (... |
[
0.015682677,
-0.0069300295,
-0.026849613,
-0.029433923,
0.025843093,
-0.008888664,
0.007718924,
-0.036724396,
0.03326958,
0.0659951,
-0.001286204,
-0.009582347,
0.05323677,
-0.043715633,
0.007446891,
0.019926384,
0.010228424,
-0.051196527,
-0.022986751,
0.020688076,
-0.025951... | Split an image into a sequence of patches and process them in parallel with a Transformer.
Use a modern CNN, like ConvNeXT, which relies on convolutional layers but adopts modern network designs.
A third approach mixes Transformers with convolutions (for example, Convolutional Vision Transformer or LeViT). We won't di... |
[
0.011238116,
-0.014139392,
-0.0075890175,
-0.05159978,
-0.0036733337,
0.001077592,
-0.011522012,
-0.0027402863,
-0.034289066,
0.07228955,
-0.025522918,
-0.011618952,
0.064257376,
-0.033319663,
0.017130684,
-0.016853712,
-0.021963835,
-0.03531386,
-0.029275881,
0.0028839651,
-... |
ViT and ConvNeXT are commonly used for image classification, but for other vision tasks like object detection, segmentation, and depth estimation, we'll look at DETR, Mask2Former and GLPN, respectively; these models are better suited for those tasks.
Image classification
ViT and ConvNeXT can both be used for image cl... |
[
-0.0052266824,
-0.0013103179,
0.016777905,
-0.02563372,
-0.030637914,
-0.013604693,
-0.033701707,
-0.02846408,
-0.006798699,
0.004457087,
-0.028099343,
0.016544474,
0.062151197,
-0.039946005,
-0.009483164,
-0.013962135,
-0.01452383,
-0.016281864,
-0.060575534,
0.051821843,
-0... | The main change ViT introduced was in how images are fed to a Transformer: |
[
0.014497394,
-0.008453815,
0.012238247,
-0.052320123,
0.020591335,
-0.033441134,
0.011310126,
-0.00086112,
0.008122858,
0.052521575,
0.0292538,
0.0056298813,
0.014468615,
-0.008252363,
0.016432779,
0.01690763,
-0.0013553085,
-0.04285185,
-0.01828902,
0.00913012,
-0.0360888,
... | An image is split into square non-overlapping patches, each of which gets turned into a vector or patch embedding. The patch embeddings are generated from a convolutional 2D layer which creates the proper input dimensions (which for a base Transformer is 768 values for each patch embedding). If you had a 224x224 pixel ... |
[
0.0010116387,
-0.0067347502,
-0.028308056,
-0.037706044,
0.011608442,
-0.02489968,
-0.013234194,
-0.020735472,
-0.023658974,
0.046690464,
0.054077655,
-0.01215749,
0.014410726,
-0.0127350595,
-0.025099333,
0.011337483,
-0.03200165,
-0.07033518,
-0.03950293,
-0.0010998785,
-0.... | A learnable embedding - a special [CLS] token - is added to the beginning of the patch embeddings just like BERT. The final hidden state of the [CLS] token is used as the input to the attached classification head; other outputs are ignored. This token helps the model learn how to encode a representation of the image. |
[
0.0050517195,
0.029519355,
-0.008737908,
-0.0022964058,
0.0010567944,
-0.029011944,
-0.056173332,
-0.006215779,
-0.023684133,
0.03742899,
0.041518122,
-0.010461612,
0.029026868,
-0.05026349,
-0.0048577096,
0.031399757,
-0.038801983,
-0.021699263,
-0.06590368,
-0.034772545,
0.... |
Now that wav2vec2 is pretrained, you can finetune it on your data for audio classification or automatic speech recognition!
Audio classification
To use the pretrained model for audio classification, add a sequence classification head on top of the base Wav2Vec2 model. The classification head is a linear layer that ac... |
[
0.0277919,
-0.003166633,
-0.014626577,
-0.046760086,
0.023141183,
-0.0138608245,
0.021581577,
-0.0044821114,
0.003941167,
0.056230128,
0.05131245,
0.009378713,
0.020907152,
-0.01752098,
0.0017088929,
0.02524876,
0.00027705843,
-0.017942496,
-0.01716972,
-0.011830526,
-0.01277... | The last thing to add to the patch and learnable embeddings are the position embeddings because the model doesn't know how the image patches are ordered. The position embeddings are also learnable and have the same size as the patch embeddings. Finally, all of the embeddings are passed to the Transformer encoder. |
[
0.0090256445,
-0.0077412804,
-0.022135992,
-0.020353321,
0.043991245,
0.028157767,
-0.00604634,
-0.007120153,
-0.024887199,
0.06327777,
0.004200504,
0.023343153,
0.040117096,
-0.04823035,
-0.0318354,
-0.0008830007,
-0.0033688254,
-0.033856697,
-0.046545938,
0.019651482,
-0.00... | ConvNeXT is a CNN architecture that adopts new and modern network designs to improve performance. However, convolutions are still at the core of the model. From a high-level perspective, a convolution is an operation where a smaller matrix (kernel) is multiplied by a small window of the image pixels. It computes some f... |
[
0.01788274,
0.005435534,
-0.014908893,
-0.04454164,
0.0166932,
-0.025588313,
-0.018054564,
0.024425207,
-0.02067155,
0.07121375,
0.03235547,
0.003185322,
0.059054017,
-0.048876848,
0.015411142,
0.010137518,
-0.0012126693,
-0.035210364,
-0.012761113,
-0.013930827,
-0.04660351,... | Ready to try your hand at image classification? Check out our complete image classification guide to learn how to finetune ViT and use it for inference!
CNN
This section briefly explains convolutions, but it'd be helpful to have a prior understanding of how they change an image's shape and size. If you're unfamiliar w... |
[
0.014043291,
-0.004780931,
-0.0016491069,
-0.051499464,
-0.023117077,
-0.041087165,
-0.014435232,
-0.006714749,
-0.047358207,
0.029772665,
0.008489572,
0.0060233073,
0.01888708,
-0.041797094,
-0.011210969,
-0.0011286768,
-0.0033980475,
0.0013394372,
-0.037478358,
-0.0076317415,... | The output, specifically only the output with the [CLS] token, is passed to a multilayer perceptron head (MLP). ViT's pretraining objective is simply classification. Like other classification heads, the MLP head converts the output into logits over the class labels and calculates the cross-entropy loss to find the most... |
[
0.03564545,
0.011094468,
0.0033677078,
-0.019340163,
0.024178782,
0.0003131503,
-0.007673077,
-0.008682315,
-0.014659013,
0.06052569,
0.012282649,
0.014480069,
0.040312286,
-0.05311029,
-0.061327353,
-0.025395595,
0.0024210992,
-0.038737588,
-0.051564224,
0.0077876006,
-0.021... | A basic convolution without padding or stride, taken from A guide to convolution arithmetic for deep learning.
You can feed this output to another convolutional layer, and with each successive layer, the network learns more complex and abstract things like hotdogs or rockets. Between convolutional layers, it is common ... |
[
0.0451612,
-0.01859074,
-0.0024811488,
0.007121684,
0.029316168,
-0.004694162,
-0.015916534,
-0.0027796733,
-0.025497917,
0.038697343,
-0.00045225554,
0.003244442,
0.0577171,
-0.03486479,
-0.030488815,
-0.008115574,
0.00032578487,
-0.06149245,
-0.04865054,
0.036495056,
-0.026... | ConvNeXT modernizes a CNN in five ways:
Change the number of blocks in each stage and "patchify" an image with a larger stride and corresponding kernel size. The non-overlapping sliding window makes this patchifying strategy similar to how ViT splits an image into patches. |
[
-0.0012004689,
0.0009696095,
-0.012753894,
-0.0006507622,
0.0056625893,
-0.04555161,
-0.008377147,
-0.009589813,
-0.052493073,
0.0967902,
0.024629649,
-0.0016918074,
0.01246815,
-0.06696142,
0.015862219,
0.019611724,
-0.00039420332,
-0.04003189,
-0.030274816,
-0.0033470257,
0... | A bottleneck layer shrinks the number of channels and then restores it because it is faster to do a 1x1 convolution, and you can increase the depth. An inverted bottleneck does the opposite by expanding the number of channels and shrinking them, which is more memory efficient. |
[
0.015955579,
-0.013020089,
-0.0135257235,
-0.02007088,
0.001303589,
0.0034586806,
0.0066610323,
0.007886494,
-0.049580272,
0.068766296,
0.0040204967,
-0.022205783,
0.043035116,
-0.047557734,
-0.018188797,
-0.005295117,
0.014143721,
-0.040506944,
-0.034298874,
0.019480973,
-0.... | Replace the typical 3x3 convolutional layer in the bottleneck layer with depthwise convolution, which applies a convolution to each input channel separately and then stacks them back together at the end. This widens the network width for improved performance.
ViT has a global receptive field which means it can see mor... |
[
0.006242552,
-0.02285362,
0.00035579086,
-0.03397608,
0.014179758,
0.007919913,
-0.003230218,
-0.006380891,
-0.055418644,
0.06358065,
0.019685654,
0.0037939497,
0.05137914,
-0.023365473,
-0.017804243,
-0.013557232,
-0.001140433,
-0.01694654,
-0.026063086,
0.03159665,
0.001169... | ViT has a global receptive field which means it can see more of an image at once thanks to its attention mechanism. ConvNeXT attempts to replicate this effect by increasing the kernel size to 7x7.
ConvNeXT also makes several layer design changes that imitate Transformer models. There are fewer activation and normaliza... |
[
-0.01838038,
-0.003524547,
-0.031304304,
-0.05338326,
0.006349458,
-0.03754829,
-0.012234836,
-0.0021076966,
-0.015567774,
0.055211455,
-0.0056603695,
0.00032960228,
0.043707896,
-0.023499323,
0.009605049,
-0.0066342345,
0.010990258,
0.015567774,
-0.04320163,
-0.013402067,
0.... | The output from the convolution blocks is passed to a classification head which converts the outputs into logits and calculates the cross-entropy loss to find the most likely label.
Object detection
DETR, DEtection TRansformer, is an end-to-end object detection model that combines a CNN with a Transformer encoder-decod... |
[
0.024606492,
0.0075284317,
0.009028484,
-0.051156715,
0.015620263,
-0.0047924207,
-0.01932462,
-0.021352857,
-0.004979047,
0.040395778,
0.022085277,
-0.012535649,
0.041466236,
-0.036339298,
0.012458181,
0.031268697,
-0.010070774,
-0.036649168,
-0.043015588,
0.004021267,
0.004... | A pretrained CNN backbone takes an image, represented by its pixel values, and creates a low-resolution feature map of it. A 1x1 convolution is applied to the feature map to reduce dimensionality and it creates a new feature map with a high-level image representation. Since the Transformer is a sequential model, the fe... |
[
-0.011804736,
0.018805875,
-0.033329364,
-0.066264294,
-0.009853715,
-0.0143967075,
-0.041950483,
0.018017014,
-0.023651734,
0.06429215,
0.010649619,
-0.0019862384,
0.026581787,
-0.007275831,
0.0036872192,
-0.0020918895,
0.011276482,
-0.028046815,
-0.065362744,
-0.00012843197,
... |
The feature vectors are passed to the encoder, which learns the image representations using its attention layers. Next, the encoder hidden states are combined with object queries in the decoder. Object queries are learned embeddings that focus on the different regions of an image, and they're updated as they progress... |
[
0.004408033,
0.009429978,
-0.026783708,
-0.041603267,
0.015547686,
-0.030638507,
-0.017232375,
-0.0014062875,
-0.014748173,
0.07138515,
0.009501364,
-0.010507895,
0.03552125,
-0.012620895,
0.0070421454,
0.02966767,
0.005311055,
-0.006774451,
-0.020173443,
-0.01866008,
0.01111... |
An object detection head is added on top of DETR to find the class label and the coordinates of the bounding box. There are two components to the object detection head: a linear layer to transform the decoder hidden states into logits over the class labels, and a MLP to predict the bounding box.
Ready to try your han... |
[
0.018606756,
0.042303506,
-0.029719908,
-0.05726243,
0.00840556,
0.0033791903,
-0.009699266,
-0.018564338,
-0.0268073,
0.053953934,
0.02730216,
0.006489742,
0.027994966,
-0.026467968,
0.013043109,
0.024728887,
-0.0052879383,
-0.029974408,
-0.034102958,
-0.015934508,
-0.004079... | Each of these feature maps of differing scales is fed successively to one Transformer decoder layer at a time in order to capture small objects from the high-resolution features. The key to Mask2Former is the masked attention mechanism in the decoder. Unlike cross-attention which can attend to the entire image, masked ... |
[
-0.004516678,
0.009539629,
-0.023722505,
-0.0368856,
0.0012177674,
-0.0547932,
-0.016041622,
-0.0004985885,
-0.034310844,
0.05493785,
0.03980752,
0.012953356,
0.043394826,
-0.025111139,
0.0131341675,
0.036625233,
0.0013488559,
-0.00942391,
-0.016374314,
-0.025357043,
0.021075... |
Like DETR, Mask2Former also uses learned object queries and combines them with the image features from the pixel decoder to make a set prediction (class label, mask prediction). The decoder hidden states are passed into a linear layer and transformed into logits over the class labels. The cross-entropy loss is calcul... |
[
0.008292143,
0.021031223,
-0.019548912,
-0.056415927,
-0.038364004,
-0.0523359,
-0.039009765,
0.015527588,
-0.034401387,
0.05852932,
0.045995712,
-0.013524265,
0.0062154382,
0.014316789,
0.0152340615,
-0.005019315,
0.017993217,
0.02503787,
-0.048255872,
-0.027870407,
0.007140... |
DETR uses a bipartite matching loss during training to compare a fixed number of predictions with a fixed set of ground truth labels. If there are fewer ground truth labels in the set of N labels, then they're padded with a no object class. This loss function encourages DETR to find a one-to-one assignment between th... |
[
0.061568044,
0.026423875,
-0.03180831,
0.007931315,
-0.007841344,
0.009267042,
-0.021094806,
0.011986944,
0.017952733,
0.06799061,
0.021427007,
-0.012007706,
0.01593184,
-0.039642733,
0.003578089,
0.053318366,
-0.005149126,
-0.029842783,
0.004017564,
-0.030867072,
0.027489688... | Ready to try your hand at object detection? Check out our complete image segmentation guide to learn how to finetune SegFormer and use it for inference!
Depth estimation
GLPN, Global-Local Path Network, is a Transformer for depth estimation that combines a SegFormer encoder with a lightweight decoder. |
[
0.016153391,
0.0204367,
-0.028219445,
-0.0656774,
-0.0020069259,
-0.012807932,
-0.02211643,
-0.014711625,
-0.005011191,
0.053555354,
0.040789414,
-0.0047662305,
0.01585944,
-0.04465279,
0.023894142,
0.06338177,
-0.029955164,
-0.05302344,
-0.017427186,
-0.026525717,
0.00030248... | There are three main components to Mask2Former:
A Swin backbone accepts an image and creates a low-resolution image feature map from 3 consecutive 3x3 convolutions.
The feature map is passed to a pixel decoder which gradually upsamples the low-resolution features into high-resolution per-pixel embeddings. The pixel d... |
[
0.028229047,
0.010690248,
-0.013343354,
-0.036506735,
0.02766305,
-0.013456552,
-0.0028989604,
0.0039796587,
0.010683172,
0.016442182,
0.033733357,
0.010025202,
0.021720093,
-0.024705721,
-0.010803447,
0.02479062,
-0.014072074,
-0.06225955,
-0.025002869,
0.0020888785,
-0.0017... |
The encoder accepts the patch embeddings, and passes them through several encoder blocks. Each block consists of attention and Mix-FFN layers. The purpose of the latter is to provide positional information. At the end of each encoder block is a patch merging layer for creating hierarchical representations. The featur... |
[
0.019514455,
0.009170159,
-0.017062142,
-0.0067438567,
0.015003688,
-0.018206555,
-0.012328438,
-0.017240493,
-0.029724987,
0.035491634,
0.008256115,
-0.000011001729,
0.010203103,
-0.027421301,
-0.0068367473,
-0.029635813,
-0.03795881,
-0.045300882,
-0.022873377,
0.00697051,
... |
BERT uses WordPiece tokenization to generate a token embedding of the text. To tell the difference between a single sentence and a pair of sentences, a special [SEP] token is added to differentiate them. A special [CLS] token is added to the beginning of every sequence of text. The final output with the [CLS] token i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.