text
stringlengths
2
11.8k
A lightweight decoder takes the last feature map (1/32 scale) from the encoder and upsamples it to 1/16 scale. From here, the feature is passed into a Selective Feature Fusion (SFF) module, which selects and combines local and global features from an attention map for each feature and then upsamples it to 1/8th. This process is repeated until the decoded features are the same size as the original image. The output is passed through two convolution layers and then a sigmoid activation is applied to predict the depth of each pixel.
Natural language processing The Transformer was initially designed for machine translation, and since then, it has practically become the default architecture for solving all NLP tasks. Some tasks lend themselves to the Transformer's encoder structure, while others are better suited for the decoder. Still, other tasks make use of both the Transformer's encoder-decoder structure. Text classification BERT is an encoder-only model and is the first model to effectively implement deep bidirectionality to learn richer representations of the text by attending to words on both sides.
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 is used as the input to the classification head for classification tasks. BERT also adds a segment embedding to denote whether a token belongs to the first or second sentence in a pair of sentences.
BERT is pretrained with two objectives: masked language modeling and next-sentence prediction. In masked language modeling, some percentage of the input tokens are randomly masked, and the model needs to predict these. This solves the issue of bidirectionality, where the model could cheat and see all the words and "predict" the next word. The final hidden states of the predicted mask tokens are passed to a feedforward network with a softmax over the vocabulary to predict the masked word. The second pretraining object is next-sentence prediction. The model must predict whether sentence B follows sentence A. Half of the time sentence B is the next sentence, and the other half of the time, sentence B is a random sentence. The prediction, whether it is the next sentence or not, is passed to a feedforward network with a softmax over the two classes (IsNext and NotNext).
The input embeddings are passed through multiple encoder layers to output some final hidden states.
To use the pretrained model for text classification, add a sequence classification head on top of the base BERT model. The sequence classification head is a linear layer that accepts the final hidden states and performs a linear transformation to convert them into logits. The cross-entropy loss is calculated between the logits and target to find the most likely label. Ready to try your hand at text classification? Check out our complete text classification guide to learn how to finetune DistilBERT and use it for inference! Token classification To use BERT for token classification tasks like named entity recognition (NER), add a token classification head on top of the base BERT model. The token classification head is a linear layer that accepts the final hidden states and performs a linear transformation to convert them into logits. The cross-entropy loss is calculated between the logits and each token to find the most likely label. Ready to try your hand at token classification? Check out our complete token classification guide to learn how to finetune DistilBERT and use it for inference! Question answering To use BERT for question answering, add a span classification head on top of the base BERT model. This linear layer accepts the final hidden states and performs a linear transformation to compute the span start and end logits corresponding to the answer. The cross-entropy loss is calculated between the logits and the label position to find the most likely span of text corresponding to the answer. Ready to try your hand at question answering? Check out our complete question answering guide to learn how to finetune DistilBERT and use it for inference!
πŸ’‘ Notice how easy it is to use BERT for different tasks once it's been pretrained. You only need to add a specific head to the pretrained model to manipulate the hidden states into your desired output! Text generation GPT-2 is a decoder-only model pretrained on a large amount of text. It can generate convincing (though not always true!) text given a prompt and complete other NLP tasks like question answering despite not being explicitly trained to.
GPT-2 uses byte pair encoding (BPE) to tokenize words and generate a token embedding. Positional encodings are added to the token embeddings to indicate the position of each token in the sequence. The input embeddings are passed through multiple decoder blocks to output some final hidden state. Within each decoder block, GPT-2 uses a masked self-attention layer which means GPT-2 can't attend to future tokens. It is only allowed to attend to tokens on the left. This is different from BERT's [mask] token because, in masked self-attention, an attention mask is used to set the score to 0 for future tokens.
The output from the decoder is passed to a language modeling head, which performs a linear transformation to convert the hidden states into logits. The label is the next token in the sequence, which are created by shifting the logits to the right by one. The cross-entropy loss is calculated between the shifted logits and the labels to output the next most likely token.
GPT-2's pretraining objective is based entirely on causal language modeling, predicting the next word in a sequence. This makes GPT-2 especially good at tasks that involve generating text. Ready to try your hand at text generation? Check out our complete causal language modeling guide to learn how to finetune DistilGPT-2 and use it for inference! For more information about text generation, check out the text generation strategies guide!
For more information about text generation, check out the text generation strategies guide! Summarization Encoder-decoder models like BART and T5 are designed for the sequence-to-sequence pattern of a summarization task. We'll explain how BART works in this section, and then you can try finetuning T5 at the end.
BART's encoder architecture is very similar to BERT and accepts a token and positional embedding of the text. BART is pretrained by corrupting the input and then reconstructing it with the decoder. Unlike other encoders with specific corruption strategies, BART can apply any type of corruption. The text infilling corruption strategy works the best though. In text infilling, a number of text spans are replaced with a single [mask] token. This is important because the model has to predict the masked tokens, and it teaches the model to predict the number of missing tokens. The input embeddings and masked spans are passed through the encoder to output some final hidden states, but unlike BERT, BART doesn't add a final feedforward network at the end to predict a word.
The encoder's output is passed to the decoder, which must predict the masked tokens and any uncorrupted tokens from the encoder's output. This gives additional context to help the decoder restore the original text. The output from the decoder is passed to a language modeling head, which performs a linear transformation to convert the hidden states into logits. The cross-entropy loss is calculated between the logits and the label, which is just the token shifted to the right.
Ready to try your hand at summarization? Check out our complete summarization guide to learn how to finetune T5 and use it for inference! For more information about text generation, check out the text generation strategies guide!
Translation Translation is another example of a sequence-to-sequence task, which means you can use an encoder-decoder model like BART or T5 to do it. We'll explain how BART works in this section, and then you can try finetuning T5 at the end. BART adapts to translation by adding a separate randomly initialized encoder to map a source language to an input that can be decoded into the target language. This new encoder's embeddings are passed to the pretrained encoder instead of the original word embeddings. The source encoder is trained by updating the source encoder, positional embeddings, and input embeddings with the cross-entropy loss from the model output. The model parameters are frozen in this first step, and all the model parameters are trained together in the second step. BART has since been followed up by a multilingual version, mBART, intended for translation and pretrained on many different languages. Ready to try your hand at translation? Check out our complete translation guide to learn how to finetune T5 and use it for inference!
For more information about text generation, check out the text generation strategies guide!
Benchmarks Hugging Face's Benchmarking tools are deprecated and it is advised to use external Benchmarking libraries to measure the speed and memory complexity of Transformer models.
[[open-in-colab]] Let's take a look at how πŸ€— Transformers models can be benchmarked, best practices, and already available benchmarks. A notebook explaining in more detail how to benchmark πŸ€— Transformers models can be found here. How to benchmark πŸ€— Transformers models The classes [PyTorchBenchmark] and [TensorFlowBenchmark] allow to flexibly benchmark πŸ€— Transformers models. The benchmark classes allow us to measure the peak memory usage and required time for both inference and training.
Hereby, inference is defined by a single forward pass, and training is defined by a single forward pass and backward pass.
The benchmark classes [PyTorchBenchmark] and [TensorFlowBenchmark] expect an object of type [PyTorchBenchmarkArguments] and [TensorFlowBenchmarkArguments], respectively, for instantiation. [PyTorchBenchmarkArguments] and [TensorFlowBenchmarkArguments] are data classes and contain all relevant configurations for their corresponding benchmark class. In the following example, it is shown how a BERT model of type bert-base-cased can be benchmarked.
from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments args = PyTorchBenchmarkArguments(models=["google-bert/bert-base-uncased"], batch_sizes=[8], sequence_lengths=[8, 32, 128, 512]) benchmark = PyTorchBenchmark(args) </pt> <tf>py from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments args = TensorFlowBenchmarkArguments( models=["google-bert/bert-base-uncased"], batch_sizes=[8], sequence_lengths=[8, 32, 128, 512] ) benchmark = TensorFlowBenchmark(args)
Here, three arguments are given to the benchmark argument data classes, namely models, batch_sizes, and sequence_lengths. The argument models is required and expects a list of model identifiers from the model hub The list arguments batch_sizes and sequence_lengths define the size of the input_ids on which the model is benchmarked. There are many more parameters that can be configured via the benchmark argument data classes. For more detail on these one can either directly consult the files src/transformers/benchmark/benchmark_args_utils.py, src/transformers/benchmark/benchmark_args.py (for PyTorch) and src/transformers/benchmark/benchmark_args_tf.py (for Tensorflow). Alternatively, running the following shell commands from root will print out a descriptive list of all configurable parameters for PyTorch and Tensorflow respectively.
python examples/pytorch/benchmarking/run_benchmark.py --help An instantiated benchmark object can then simply be run by calling benchmark.run(). results = benchmark.run() print(results) ==================== INFERENCE - SPEED - RESULT ====================
results = benchmark.run() print(results) ==================== INFERENCE - SPEED - RESULT ==================== Model Name Batch Size Seq Length Time in s google-bert/bert-base-uncased 8 8 0.006 google-bert/bert-base-uncased 8 32 0.006 google-bert/bert-base-uncased 8 128 0.018 google-bert/bert-base-uncased 8 512 0.088
==================== INFERENCE - MEMORY - RESULT ==================== Model Name Batch Size Seq Length Memory in MB google-bert/bert-base-uncased 8 8 1227 google-bert/bert-base-uncased 8 32 1281 google-bert/bert-base-uncased 8 128 1307 google-bert/bert-base-uncased 8 512 1539
==================== ENVIRONMENT INFORMATION ====================
transformers_version: 2.11.0 framework: PyTorch use_torchscript: False framework_version: 1.4.0 python_version: 3.6.10 system: Linux cpu: x86_64 architecture: 64bit date: 2020-06-29 time: 08:58:43.371351 fp16: False use_multiprocessing: True only_pretrain_model: False cpu_ram_mb: 32088 use_gpu: True num_gpus: 1 gpu: TITAN RTX gpu_ram_mb: 24217 gpu_power_watts: 280.0 gpu_performance_state: 2 use_tpu: False </pt> <tf>bash python examples/tensorflow/benchmarking/run_benchmark_tf.py --help
An instantiated benchmark object can then simply be run by calling benchmark.run(). results = benchmark.run() print(results) results = benchmark.run() print(results) ==================== INFERENCE - SPEED - RESULT ====================
Model Name Batch Size Seq Length Time in s google-bert/bert-base-uncased 8 8 0.005 google-bert/bert-base-uncased 8 32 0.008 google-bert/bert-base-uncased 8 128 0.022 google-bert/bert-base-uncased 8 512 0.105
==================== INFERENCE - MEMORY - RESULT ==================== Model Name Batch Size Seq Length Memory in MB google-bert/bert-base-uncased 8 8 1330 google-bert/bert-base-uncased 8 32 1330 google-bert/bert-base-uncased 8 128 1330 google-bert/bert-base-uncased 8 512 1770
==================== ENVIRONMENT INFORMATION ==================== transformers_version: 2.11.0 framework: Tensorflow use_xla: False framework_version: 2.2.0 python_version: 3.6.10 system: Linux cpu: x86_64 architecture: 64bit date: 2020-06-29 time: 09:26:35.617317 fp16: False use_multiprocessing: True only_pretrain_model: False cpu_ram_mb: 32088 use_gpu: True num_gpus: 1 gpu: TITAN RTX gpu_ram_mb: 24217 gpu_power_watts: 280.0 gpu_performance_state: 2 use_tpu: False
By default, the time and the required memory for inference are benchmarked. In the example output above the first two sections show the result corresponding to inference time and inference memory. In addition, all relevant information about the computing environment, e.g. the GPU type, the system, the library versions, etc are printed out in the third section under ENVIRONMENT INFORMATION. This information can optionally be saved in a .csv file when adding the argument save_to_csv=True to [PyTorchBenchmarkArguments] and [TensorFlowBenchmarkArguments] respectively. In this case, every section is saved in a separate .csv file. The path to each .csv file can optionally be defined via the argument data classes. Instead of benchmarking pre-trained models via their model identifier, e.g. google-bert/bert-base-uncased, the user can alternatively benchmark an arbitrary configuration of any available model class. In this case, a list of configurations must be inserted with the benchmark args as follows.
from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments, BertConfig args = PyTorchBenchmarkArguments( models=["bert-base", "bert-384-hid", "bert-6-lay"], batch_sizes=[8], sequence_lengths=[8, 32, 128, 512] ) config_base = BertConfig() config_384_hid = BertConfig(hidden_size=384) config_6_lay = BertConfig(num_hidden_layers=6) benchmark = PyTorchBenchmark(args, configs=[config_base, config_384_hid, config_6_lay]) benchmark.run() ==================== INFERENCE - SPEED - RESULT ====================
Model Name Batch Size Seq Length Time in s bert-base 8 128 0.006 bert-base 8 512 0.006 bert-base 8 128 0.018 bert-base 8 512 0.088 bert-384-hid 8 8 0.006 bert-384-hid 8 32 0.006 bert-384-hid 8 128 0.011 bert-384-hid 8 512 0.054 bert-6-lay 8 8 0.003 bert-6-lay 8 32 0.004 bert-6-lay 8 128 0.009 bert-6-lay 8 512 0.044
==================== INFERENCE - MEMORY - RESULT ==================== Model Name Batch Size Seq Length Memory in MB bert-base 8 8 1277 bert-base 8 32 1281 bert-base 8 128 1307 bert-base 8 512 1539 bert-384-hid 8 8 1005 bert-384-hid 8 32 1027 bert-384-hid 8 128 1035 bert-384-hid 8 512 1255 bert-6-lay 8 8 1097 bert-6-lay 8 32 1101 bert-6-lay 8 128 1127 bert-6-lay 8 512 1359
==================== ENVIRONMENT INFORMATION ==================== transformers_version: 2.11.0 framework: PyTorch use_torchscript: False framework_version: 1.4.0 python_version: 3.6.10 system: Linux cpu: x86_64 architecture: 64bit date: 2020-06-29 time: 09:35:25.143267 fp16: False use_multiprocessing: True only_pretrain_model: False cpu_ram_mb: 32088 use_gpu: True num_gpus: 1 gpu: TITAN RTX gpu_ram_mb: 24217 gpu_power_watts: 280.0 gpu_performance_state: 2 use_tpu: False </pt> <tf>py
from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments, BertConfig
args = TensorFlowBenchmarkArguments( models=["bert-base", "bert-384-hid", "bert-6-lay"], batch_sizes=[8], sequence_lengths=[8, 32, 128, 512] ) config_base = BertConfig() config_384_hid = BertConfig(hidden_size=384) config_6_lay = BertConfig(num_hidden_layers=6) benchmark = TensorFlowBenchmark(args, configs=[config_base, config_384_hid, config_6_lay]) benchmark.run() ==================== INFERENCE - SPEED - RESULT ====================
Model Name Batch Size Seq Length Time in s bert-base 8 8 0.005 bert-base 8 32 0.008 bert-base 8 128 0.022 bert-base 8 512 0.106 bert-384-hid 8 8 0.005 bert-384-hid 8 32 0.007 bert-384-hid 8 128 0.018 bert-384-hid 8 512 0.064 bert-6-lay 8 8 0.002 bert-6-lay 8 32 0.003 bert-6-lay 8 128 0.0011 bert-6-lay 8 512 0.074
==================== INFERENCE - MEMORY - RESULT ==================== Model Name Batch Size Seq Length Memory in MB bert-base 8 8 1330 bert-base 8 32 1330 bert-base 8 128 1330 bert-base 8 512 1770 bert-384-hid 8 8 1330 bert-384-hid 8 32 1330 bert-384-hid 8 128 1330 bert-384-hid 8 512 1540 bert-6-lay 8 8 1330 bert-6-lay 8 32 1330 bert-6-lay 8 128 1330 bert-6-lay 8 512 1540
==================== ENVIRONMENT INFORMATION ==================== transformers_version: 2.11.0 framework: Tensorflow use_xla: False framework_version: 2.2.0 python_version: 3.6.10 system: Linux cpu: x86_64 architecture: 64bit date: 2020-06-29 time: 09:38:15.487125 fp16: False use_multiprocessing: True only_pretrain_model: False cpu_ram_mb: 32088 use_gpu: True num_gpus: 1 gpu: TITAN RTX gpu_ram_mb: 24217 gpu_power_watts: 280.0 gpu_performance_state: 2 use_tpu: False
Again, inference time and required memory for inference are measured, but this time for customized configurations of the BertModel class. This feature can especially be helpful when deciding for which configuration the model should be trained. Benchmark best practices This section lists a couple of best practices one should be aware of when benchmarking a model.
Currently, only single device benchmarking is supported. When benchmarking on GPU, it is recommended that the user specifies on which device the code should be run by setting the CUDA_VISIBLE_DEVICES environment variable in the shell, e.g. export CUDA_VISIBLE_DEVICES=0 before running the code. The option no_multi_processing should only be set to True for testing and debugging. To ensure accurate memory measurement it is recommended to run each memory benchmark in a separate process by making sure no_multi_processing is set to True. One should always state the environment information when sharing the results of a model benchmark. Results can vary heavily between different GPU devices, library versions, etc., so that benchmark results on their own are not very useful for the community.
Sharing your benchmark Previously all available core models (10 at the time) have been benchmarked for inference time, across many different settings: using PyTorch, with and without TorchScript, using TensorFlow, with and without XLA. All of those tests were done across CPUs (except for TensorFlow XLA) and GPUs. The approach is detailed in the following blogpost and the results are available here. With the new benchmark tools, it is easier than ever to share your benchmark results with the community
PyTorch Benchmarking Results. TensorFlow Benchmarking Results.
Text generation strategies Text generation is essential to many NLP tasks, such as open-ended text generation, summarization, translation, and more. It also plays a role in a variety of mixed-modality applications that have text as an output like speech-to-text and vision-to-text. Some of the models that can generate text include GPT2, XLNet, OpenAI GPT, CTRL, TransformerXL, XLM, Bart, T5, GIT, Whisper. Check out a few examples that use [~transformers.generation_utils.GenerationMixin.generate] method to produce text outputs for different tasks: * Text summarization * Image captioning * Audio transcription Note that the inputs to the generate method depend on the model's modality. They are returned by the model's preprocessor class, such as AutoTokenizer or AutoProcessor. If a model's preprocessor creates more than one kind of input, pass all the inputs to generate(). You can learn more about the individual model's preprocessor in the corresponding model's documentation. The process of selecting output tokens to generate text is known as decoding, and you can customize the decoding strategy that the generate() method will use. Modifying a decoding strategy does not change the values of any trainable parameters. However, it can have a noticeable impact on the quality of the generated output. It can help reduce repetition in the text and make it more coherent. This guide describes: * default generation configuration * common decoding strategies and their main parameters * saving and sharing custom generation configurations with your fine-tuned model on πŸ€— Hub Default text generation configuration A decoding strategy for a model is defined in its generation configuration. When using pre-trained models for inference within a [pipeline], the models call the PreTrainedModel.generate() method that applies a default generation configuration under the hood. The default configuration is also used when no custom configuration has been saved with the model. When you load a model explicitly, you can inspect the generation configuration that comes with it through model.generation_config: thon
from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") model.generation_config GenerationConfig { "bos_token_id": 50256, "eos_token_id": 50256, }
Printing out the model.generation_config reveals only the values that are different from the default generation configuration, and does not list any of the default values. The default generation configuration limits the size of the output combined with the input prompt to a maximum of 20 tokens to avoid running into resource limitations. The default decoding strategy is greedy search, which is the simplest decoding strategy that picks a token with the highest probability as the next token. For many tasks and small output sizes this works well. However, when used to generate longer outputs, greedy search can start producing highly repetitive results. Customize text generation You can override any generation_config by passing the parameters and their values directly to the [generate] method: thon
my_model.generate(**inputs, num_beams=4, do_sample=True) # doctest: +SKIP Even if the default decoding strategy mostly works for your task, you can still tweak a few things. Some of the commonly adjusted parameters include:
max_new_tokens: the maximum number of tokens to generate. In other words, the size of the output sequence, not including the tokens in the prompt. As an alternative to using the output's length as a stopping criteria, you can choose to stop generation whenever the full generation exceeds some amount of time. To learn more, check [StoppingCriteria]. num_beams: by specifying a number of beams higher than 1, you are effectively switching from greedy search to beam search. This strategy evaluates several hypotheses at each time step and eventually chooses the hypothesis that has the overall highest probability for the entire sequence. This has the advantage of identifying high-probability sequences that start with a lower probability initial tokens and would've been ignored by the greedy search. do_sample: if set to True, this parameter enables decoding strategies such as multinomial sampling, beam-search multinomial sampling, Top-K sampling and Top-p sampling. All these strategies select the next token from the probability distribution over the entire vocabulary with various strategy-specific adjustments. num_return_sequences: the number of sequence candidates to return for each input. This option is only available for the decoding strategies that support multiple sequence candidates, e.g. variations of beam search and sampling. Decoding strategies like greedy search and contrastive search return a single output sequence.
Save a custom decoding strategy with your model If you would like to share your fine-tuned model with a specific generation configuration, you can: * Create a [GenerationConfig] class instance * Specify the decoding strategy parameters * Save your generation configuration with [GenerationConfig.save_pretrained], making sure to leave its config_file_name argument empty * Set push_to_hub to True to upload your config to the model's repo thon
from transformers import AutoModelForCausalLM, GenerationConfig model = AutoModelForCausalLM.from_pretrained("my_account/my_model") # doctest: +SKIP generation_config = GenerationConfig( max_new_tokens=50, do_sample=True, top_k=50, eos_token_id=model.config.eos_token_id ) generation_config.save_pretrained("my_account/my_model", push_to_hub=True) # doctest: +SKIP
You can also store several generation configurations in a single directory, making use of the config_file_name argument in [GenerationConfig.save_pretrained]. You can later instantiate them with [GenerationConfig.from_pretrained]. This is useful if you want to store several generation configurations for a single model (e.g. one for creative text generation with sampling, and one for summarization with beam search). You must have the right Hub permissions to add configuration files to a model. thon
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, GenerationConfig tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small") model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small") translation_generation_config = GenerationConfig( num_beams=4, early_stopping=True, decoder_start_token_id=0, eos_token_id=model.config.eos_token_id, pad_token=model.config.pad_token_id, ) Tip: add push_to_hub=True to push to the Hub translation_generation_config.save_pretrained("/tmp", "translation_generation_config.json") You could then use the named generation config file to parameterize generation generation_config = GenerationConfig.from_pretrained("/tmp", "translation_generation_config.json") inputs = tokenizer("translate English to French: Configuration files are easy to use!", return_tensors="pt") outputs = model.generate(**inputs, generation_config=generation_config) print(tokenizer.batch_decode(outputs, skip_special_tokens=True)) ['Les fichiers de configuration sont faciles Γ  utiliser!']
Streaming The generate() supports streaming, through its streamer input. The streamer input is compatible with any instance from a class that has the following methods: put() and end(). Internally, put() is used to push new tokens and end() is used to flag the end of text generation. The API for the streamer classes is still under development and may change in the future.
The API for the streamer classes is still under development and may change in the future. In practice, you can craft your own streaming class for all sorts of purposes! We also have basic streaming classes ready for you to use. For example, you can use the [TextStreamer] class to stream the output of generate() into your screen, one word at a time: thon
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer tok = AutoTokenizer.from_pretrained("openai-community/gpt2") model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") inputs = tok(["An increasing sequence: one,"], return_tensors="pt") streamer = TextStreamer(tok) Despite returning the usual output, the streamer will also print the generated text to stdout. _ = model.generate(**inputs, streamer=streamer, max_new_tokens=20) An increasing sequence: one, two, three, four, five, six, seven, eight, nine, ten, eleven,
Decoding strategies Certain combinations of the generate() parameters, and ultimately generation_config, can be used to enable specific decoding strategies. If you are new to this concept, we recommend reading this blog post that illustrates how common decoding strategies work. Here, we'll show some of the parameters that control the decoding strategies and illustrate how you can use them. Greedy Search [generate] uses greedy search decoding by default so you don't have to pass any parameters to enable it. This means the parameters num_beams is set to 1 and do_sample=False. thon
from transformers import AutoModelForCausalLM, AutoTokenizer prompt = "I look forward to" checkpoint = "distilbert/distilgpt2" tokenizer = AutoTokenizer.from_pretrained(checkpoint) inputs = tokenizer(prompt, return_tensors="pt") model = AutoModelForCausalLM.from_pretrained(checkpoint) outputs = model.generate(**inputs) tokenizer.batch_decode(outputs, skip_special_tokens=True) ['I look forward to seeing you all again!\n\n\n\n\n\n\n\n\n\n\n']
Contrastive search The contrastive search decoding strategy was proposed in the 2022 paper A Contrastive Framework for Neural Text Generation. It demonstrates superior results for generating non-repetitive yet coherent long outputs. To learn how contrastive search works, check out this blog post. The two main parameters that enable and control the behavior of contrastive search are penalty_alpha and top_k: thon
from transformers import AutoTokenizer, AutoModelForCausalLM checkpoint = "openai-community/gpt2-large" tokenizer = AutoTokenizer.from_pretrained(checkpoint) model = AutoModelForCausalLM.from_pretrained(checkpoint) prompt = "Hugging Face Company is" inputs = tokenizer(prompt, return_tensors="pt") outputs = model.generate(**inputs, penalty_alpha=0.6, top_k=4, max_new_tokens=100) tokenizer.batch_decode(outputs, skip_special_tokens=True) ['Hugging Face Company is a family owned and operated business. We pride ourselves on being the best in the business and our customer service is second to none.\n\nIf you have any questions about our products or services, feel free to contact us at any time. We look forward to hearing from you!']
Multinomial sampling As opposed to greedy search that always chooses a token with the highest probability as the next token, multinomial sampling (also called ancestral sampling) randomly selects the next token based on the probability distribution over the entire vocabulary given by the model. Every token with a non-zero probability has a chance of being selected, thus reducing the risk of repetition. To enable multinomial sampling set do_sample=True and num_beams=1. thon
from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed set_seed(0) # For reproducibility checkpoint = "openai-community/gpt2-large" tokenizer = AutoTokenizer.from_pretrained(checkpoint) model = AutoModelForCausalLM.from_pretrained(checkpoint) prompt = "Today was an amazing day because" inputs = tokenizer(prompt, return_tensors="pt") outputs = model.generate(**inputs, do_sample=True, num_beams=1, max_new_tokens=100) tokenizer.batch_decode(outputs, skip_special_tokens=True) ['Today was an amazing day because when you go to the World Cup and you don\'t, or when you don\'t get invited, that\'s a terrible feeling."']
Beam-search decoding Unlike greedy search, beam-search decoding keeps several hypotheses at each time step and eventually chooses the hypothesis that has the overall highest probability for the entire sequence. This has the advantage of identifying high-probability sequences that start with lower probability initial tokens and would've been ignored by the greedy search. To enable this decoding strategy, specify the num_beams (aka number of hypotheses to keep track of) that is greater than 1. thon
from transformers import AutoModelForCausalLM, AutoTokenizer prompt = "It is astonishing how one can" checkpoint = "openai-community/gpt2-medium" tokenizer = AutoTokenizer.from_pretrained(checkpoint) inputs = tokenizer(prompt, return_tensors="pt") model = AutoModelForCausalLM.from_pretrained(checkpoint) outputs = model.generate(**inputs, num_beams=5, max_new_tokens=50) tokenizer.batch_decode(outputs, skip_special_tokens=True) ['It is astonishing how one can have such a profound impact on the lives of so many people in such a short period of time."\n\nHe added: "I am very proud of the work I have been able to do in the last few years.\n\n"I have']
Beam-search multinomial sampling As the name implies, this decoding strategy combines beam search with multinomial sampling. You need to specify the num_beams greater than 1, and set do_sample=True to use this decoding strategy. thon
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, set_seed set_seed(0) # For reproducibility prompt = "translate English to German: The house is wonderful." checkpoint = "google-t5/t5-small" tokenizer = AutoTokenizer.from_pretrained(checkpoint) inputs = tokenizer(prompt, return_tensors="pt") model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint) outputs = model.generate(**inputs, num_beams=5, do_sample=True) tokenizer.decode(outputs[0], skip_special_tokens=True) 'Das Haus ist wunderbar.'
Diverse beam search decoding The diverse beam search decoding strategy is an extension of the beam search strategy that allows for generating a more diverse set of beam sequences to choose from. To learn how it works, refer to Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models. This approach has three main parameters: num_beams, num_beam_groups, and diversity_penalty. The diversity penalty ensures the outputs are distinct across groups, and beam search is used within each group. thon
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM checkpoint = "google/pegasus-xsum" prompt = ( "The Permaculture Design Principles are a set of universal design principles " "that can be applied to any location, climate and culture, and they allow us to design " "the most efficient and sustainable human habitation and food production systems. " "Permaculture is a design system that encompasses a wide variety of disciplines, such " "as ecology, landscape design, environmental science and energy conservation, and the " "Permaculture design principles are drawn from these various disciplines. Each individual " "design principle itself embodies a complete conceptual framework based on sound " "scientific principles. When we bring all these separate principles together, we can " "create a design system that both looks at whole systems, the parts that these systems " "consist of, and how those parts interact with each other to create a complex, dynamic, " "living system. Each design principle serves as a tool that allows us to integrate all " "the separate parts of a design, referred to as elements, into a functional, synergistic, " "whole system, where the elements harmoniously interact and work together in the most " "efficient way possible." ) tokenizer = AutoTokenizer.from_pretrained(checkpoint) inputs = tokenizer(prompt, return_tensors="pt") model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint) outputs = model.generate(**inputs, num_beams=5, num_beam_groups=5, max_new_tokens=30, diversity_penalty=1.0) tokenizer.decode(outputs[0], skip_special_tokens=True) 'The Design Principles are a set of universal design principles that can be applied to any location, climate and culture, and they allow us to design the'
This guide illustrates the main parameters that enable various decoding strategies. More advanced parameters exist for the [generate] method, which gives you even further control over the [generate] method's behavior. For the complete list of the available parameters, refer to the API documentation. Speculative Decoding Speculative decoding (also known as assisted decoding) is a modification of the decoding strategies above, that uses an assistant model (ideally a much smaller one) with the same tokenizer, to generate a few candidate tokens. The main model then validates the candidate tokens in a single forward pass, which speeds up the decoding process. If do_sample=True, then the token validation with resampling introduced in the speculative decoding paper is used. Currently, only greedy search and sampling are supported with assisted decoding, and assisted decoding doesn't support batched inputs. To learn more about assisted decoding, check this blog post. To enable assisted decoding, set the assistant_model argument with a model. thon
from transformers import AutoModelForCausalLM, AutoTokenizer prompt = "Alice and Bob" checkpoint = "EleutherAI/pythia-1.4b-deduped" assistant_checkpoint = "EleutherAI/pythia-160m-deduped" tokenizer = AutoTokenizer.from_pretrained(checkpoint) inputs = tokenizer(prompt, return_tensors="pt") model = AutoModelForCausalLM.from_pretrained(checkpoint) assistant_model = AutoModelForCausalLM.from_pretrained(assistant_checkpoint) outputs = model.generate(**inputs, assistant_model=assistant_model) tokenizer.batch_decode(outputs, skip_special_tokens=True) ['Alice and Bob are sitting in a bar. Alice is drinking a beer and Bob is drinking a']
When using assisted decoding with sampling methods, you can use the temperature argument to control the randomness, just like in multinomial sampling. However, in assisted decoding, reducing the temperature may help improve the latency. thon
from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed set_seed(42) # For reproducibility prompt = "Alice and Bob" checkpoint = "EleutherAI/pythia-1.4b-deduped" assistant_checkpoint = "EleutherAI/pythia-160m-deduped" tokenizer = AutoTokenizer.from_pretrained(checkpoint) inputs = tokenizer(prompt, return_tensors="pt") model = AutoModelForCausalLM.from_pretrained(checkpoint) assistant_model = AutoModelForCausalLM.from_pretrained(assistant_checkpoint) outputs = model.generate(**inputs, assistant_model=assistant_model, do_sample=True, temperature=0.5) tokenizer.batch_decode(outputs, skip_special_tokens=True) ['Alice and Bob are going to the same party. It is a small party, in a small']
Alternativelly, you can also set the prompt_lookup_num_tokens to trigger n-gram based assisted decoding, as opposed to model based assisted decoding. You can read more about it here.
Glossary This glossary defines general machine learning and πŸ€— Transformers terms to help you better understand the documentation. A attention mask The attention mask is an optional argument used when batching sequences together. This argument indicates to the model which tokens should be attended to, and which should not. For example, consider these two sequences: thon
This argument indicates to the model which tokens should be attended to, and which should not. For example, consider these two sequences: thon from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") sequence_a = "This is a short sequence." sequence_b = "This is a rather long sequence. It is at least longer than the sequence A." encoded_sequence_a = tokenizer(sequence_a)["input_ids"] encoded_sequence_b = tokenizer(sequence_b)["input_ids"]
The encoded versions have different lengths: thon len(encoded_sequence_a), len(encoded_sequence_b) (8, 19) Therefore, we can't put them together in the same tensor as-is. The first sequence needs to be padded up to the length of the second one, or the second one needs to be truncated down to the length of the first one. In the first case, the list of IDs will be extended by the padding indices. We can pass a list to the tokenizer and ask it to pad like this: thon
padded_sequences = tokenizer([sequence_a, sequence_b], padding=True) We can see that 0s have been added on the right of the first sentence to make it the same length as the second one: thon padded_sequences["input_ids"] [[101, 1188, 1110, 170, 1603, 4954, 119, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [101, 1188, 1110, 170, 1897, 1263, 4954, 119, 1135, 1110, 1120, 1655, 2039, 1190, 1103, 4954, 138, 119, 102]]
This can then be converted into a tensor in PyTorch or TensorFlow. The attention mask is a binary tensor indicating the position of the padded indices so that the model does not attend to them. For the [BertTokenizer], 1 indicates a value that should be attended to, while 0 indicates a padded value. This attention mask is in the dictionary returned by the tokenizer under the key "attention_mask": thon
padded_sequences["attention_mask"] [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
autoencoding models See encoder models and masked language modeling autoregressive models See causal language modeling and decoder models B backbone The backbone is the network (embeddings and layers) that outputs the raw hidden states or features. It is usually connected to a head which accepts the features as its input to make a prediction. For example, [ViTModel] is a backbone without a specific head on top. Other models can also use [VitModel] as a backbone such as DPT. C causal language modeling A pretraining task where the model reads the texts in order and has to predict the next word. It's usually done by reading the whole sentence but using a mask inside the model to hide the future tokens at a certain timestep. channel Color images are made up of some combination of values in three channels: red, green, and blue (RGB) and grayscale images only have one channel. In πŸ€— Transformers, the channel can be the first or last dimension of an image's tensor: [n_channels, height, width] or [height, width, n_channels]. connectionist temporal classification (CTC) An algorithm which allows a model to learn without knowing exactly how the input and output are aligned; CTC calculates the distribution of all possible outputs for a given input and chooses the most likely output from it. CTC is commonly used in speech recognition tasks because speech doesn't always cleanly align with the transcript for a variety of reasons such as a speaker's different speech rates. convolution A type of layer in a neural network where the input matrix is multiplied element-wise by a smaller matrix (kernel or filter) and the values are summed up in a new matrix. This is known as a convolutional operation which is repeated over the entire input matrix. Each operation is applied to a different segment of the input matrix. Convolutional neural networks (CNNs) are commonly used in computer vision. D DataParallel (DP) Parallelism technique for training on multiple GPUs where the same setup is replicated multiple times, with each instance receiving a distinct data slice. The processing is done in parallel and all setups are synchronized at the end of each training step. Learn more about how DataParallel works here. decoder input IDs This input is specific to encoder-decoder models, and contains the input IDs that will be fed to the decoder. These inputs should be used for sequence to sequence tasks, such as translation or summarization, and are usually built in a way specific to each model. Most encoder-decoder models (BART, T5) create their decoder_input_ids on their own from the labels. In such models, passing the labels is the preferred way to handle training. Please check each model's docs to see how they handle these input IDs for sequence to sequence training. decoder models Also referred to as autoregressive models, decoder models involve a pretraining task (called causal language modeling) where the model reads the texts in order and has to predict the next word. It's usually done by reading the whole sentence with a mask to hide future tokens at a certain timestep.
deep learning (DL) Machine learning algorithms which uses neural networks with several layers. E encoder models Also known as autoencoding models, encoder models take an input (such as text or images) and transform them into a condensed numerical representation called an embedding. Oftentimes, encoder models are pretrained using techniques like masked language modeling, which masks parts of the input sequence and forces the model to create more meaningful representations.
F feature extraction The process of selecting and transforming raw data into a set of features that are more informative and useful for machine learning algorithms. Some examples of feature extraction include transforming raw text into word embeddings and extracting important features such as edges or shapes from image/video data. feed forward chunking In each residual attention block in transformers the self-attention layer is usually followed by 2 feed forward layers. The intermediate embedding size of the feed forward layers is often bigger than the hidden size of the model (e.g., for google-bert/bert-base-uncased). For an input of size [batch_size, sequence_length], the memory required to store the intermediate feed forward embeddings [batch_size, sequence_length, config.intermediate_size] can account for a large fraction of the memory use. The authors of Reformer: The Efficient Transformer noticed that since the computation is independent of the sequence_length dimension, it is mathematically equivalent to compute the output embeddings of both feed forward layers [batch_size, config.hidden_size]_0, , [batch_size, config.hidden_size]_n individually and concat them afterward to [batch_size, sequence_length, config.hidden_size] with n = sequence_length, which trades increased computation time against reduced memory use, but yields a mathematically equivalent result. For models employing the function [apply_chunking_to_forward], the chunk_size defines the number of output embeddings that are computed in parallel and thus defines the trade-off between memory and time complexity. If chunk_size is set to 0, no feed forward chunking is done. finetuned models Finetuning is a form of transfer learning which involves taking a pretrained model, freezing its weights, and replacing the output layer with a newly added model head. The model head is trained on your target dataset. See the Fine-tune a pretrained model tutorial for more details, and learn how to fine-tune models with πŸ€— Transformers. H head The model head refers to the last layer of a neural network that accepts the raw hidden states and projects them onto a different dimension. There is a different model head for each task. For example:
[GPT2ForSequenceClassification] is a sequence classification head - a linear layer - on top of the base [GPT2Model]. [ViTForImageClassification] is an image classification head - a linear layer on top of the final hidden state of the CLS token - on top of the base [ViTModel]. [Wav2Vec2ForCTC] is a language modeling head with CTC on top of the base [Wav2Vec2Model].
I image patch Vision-based Transformers models split an image into smaller patches which are linearly embedded, and then passed as a sequence to the model. You can find the patch_size - or resolution - of the model in its configuration. inference Inference is the process of evaluating a model on new data after training is complete. See the Pipeline for inference tutorial to learn how to perform inference with πŸ€— Transformers. input IDs The input ids are often the only required parameters to be passed to the model as input. They are token indices, numerical representations of tokens building the sequences that will be used as input by the model.
Each tokenizer works differently but the underlying mechanism remains the same. Here's an example using the BERT tokenizer, which is a WordPiece tokenizer: thon from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") sequence = "A Titan RTX has 24GB of VRAM" The tokenizer takes care of splitting the sequence into tokens available in the tokenizer vocabulary. thon tokenized_sequence = tokenizer.tokenize(sequence)
The tokenizer takes care of splitting the sequence into tokens available in the tokenizer vocabulary. thon tokenized_sequence = tokenizer.tokenize(sequence) The tokens are either words or subwords. Here for instance, "VRAM" wasn't in the model vocabulary, so it's been split in "V", "RA" and "M". To indicate those tokens are not separate words but parts of the same word, a double-hash prefix is added for "RA" and "M": thon
print(tokenized_sequence) ['A', 'Titan', 'R', '##T', '##X', 'has', '24', '##GB', 'of', 'V', '##RA', '##M'] These tokens can then be converted into IDs which are understandable by the model. This can be done by directly feeding the sentence to the tokenizer, which leverages the Rust implementation of πŸ€— Tokenizers for peak performance. thon inputs = tokenizer(sequence)
inputs = tokenizer(sequence) The tokenizer returns a dictionary with all the arguments necessary for its corresponding model to work properly. The token indices are under the key input_ids: thon encoded_sequence = inputs["input_ids"] print(encoded_sequence) [101, 138, 18696, 155, 1942, 3190, 1144, 1572, 13745, 1104, 159, 9664, 2107, 102]
encoded_sequence = inputs["input_ids"] print(encoded_sequence) [101, 138, 18696, 155, 1942, 3190, 1144, 1572, 13745, 1104, 159, 9664, 2107, 102] Note that the tokenizer automatically adds "special tokens" (if the associated model relies on them) which are special IDs the model sometimes uses. If we decode the previous sequence of ids, thon decoded_sequence = tokenizer.decode(encoded_sequence) we will see thon print(decoded_sequence) [CLS] A Titan RTX has 24GB of VRAM [SEP]
print(decoded_sequence) [CLS] A Titan RTX has 24GB of VRAM [SEP] because this is the way a [BertModel] is going to expect its inputs. L labels The labels are an optional argument which can be passed in order for the model to compute the loss itself. These labels should be the expected prediction of the model: it will use the standard loss in order to compute the loss between its predictions and the expected value (the label). These labels are different according to the model head, for example:
For sequence classification models, ([BertForSequenceClassification]), the model expects a tensor of dimension (batch_size) with each value of the batch corresponding to the expected label of the entire sequence. For token classification models, ([BertForTokenClassification]), the model expects a tensor of dimension (batch_size, seq_length) with each value corresponding to the expected label of each individual token. For masked language modeling, ([BertForMaskedLM]), the model expects a tensor of dimension (batch_size, seq_length) with each value corresponding to the expected label of each individual token: the labels being the token ID for the masked token, and values to be ignored for the rest (usually -100). For sequence to sequence tasks, ([BartForConditionalGeneration], [MBartForConditionalGeneration]), the model expects a tensor of dimension (batch_size, tgt_seq_length) with each value corresponding to the target sequences associated with each input sequence. During training, both BART and T5 will make the appropriate decoder_input_ids and decoder attention masks internally. They usually do not need to be supplied. This does not apply to models leveraging the Encoder-Decoder framework. For image classification models, ([ViTForImageClassification]), the model expects a tensor of dimension (batch_size) with each value of the batch corresponding to the expected label of each individual image. For semantic segmentation models, ([SegformerForSemanticSegmentation]), the model expects a tensor of dimension (batch_size, height, width) with each value of the batch corresponding to the expected label of each individual pixel. For object detection models, ([DetrForObjectDetection]), the model expects a list of dictionaries with a class_labels and boxes key where each value of the batch corresponds to the expected label and number of bounding boxes of each individual image. For automatic speech recognition models, ([Wav2Vec2ForCTC]), the model expects a tensor of dimension (batch_size, target_length) with each value corresponding to the expected label of each individual token.
Each model's labels may be different, so be sure to always check the documentation of each model for more information about their specific labels!
The base models ([BertModel]) do not accept labels, as these are the base transformer models, simply outputting features. large language models (LLM) A generic term that refers to transformer language models (GPT-3, BLOOM, OPT) that were trained on a large quantity of data. These models also tend to have a large number of learnable parameters (e.g. 175 billion for GPT-3). M masked language modeling (MLM) A pretraining task where the model sees a corrupted version of the texts, usually done by masking some tokens randomly, and has to predict the original text. multimodal A task that combines texts with another kind of inputs (for instance images). N Natural language generation (NLG) All tasks related to generating text (for instance, Write With Transformers, translation). Natural language processing (NLP) A generic way to say "deal with texts". Natural language understanding (NLU) All tasks related to understanding what is in a text (for instance classifying the whole text, individual words). P pipeline A pipeline in πŸ€— Transformers is an abstraction referring to a series of steps that are executed in a specific order to preprocess and transform data and return a prediction from a model. Some example stages found in a pipeline might be data preprocessing, feature extraction, and normalization. For more details, see Pipelines for inference. PipelineParallel (PP) Parallelism technique in which the model is split up vertically (layer-level) across multiple GPUs, so that only one or several layers of the model are placed on a single GPU. Each GPU processes in parallel different stages of the pipeline and working on a small chunk of the batch. Learn more about how PipelineParallel works here. pixel values A tensor of the numerical representations of an image that is passed to a model. The pixel values have a shape of [batch_size, num_channels, height, width], and are generated from an image processor. pooling An operation that reduces a matrix into a smaller matrix, either by taking the maximum or average of the pooled dimension(s). Pooling layers are commonly found between convolutional layers to downsample the feature representation. position IDs Contrary to RNNs that have the position of each token embedded within them, transformers are unaware of the position of each token. Therefore, the position IDs (position_ids) are used by the model to identify each token's position in the list of tokens. They are an optional parameter. If no position_ids are passed to the model, the IDs are automatically created as absolute positional embeddings. Absolute positional embeddings are selected in the range [0, config.max_position_embeddings - 1]. Some models use other types of positional embeddings, such as sinusoidal position embeddings or relative position embeddings. preprocessing The task of preparing raw data into a format that can be easily consumed by machine learning models. For example, text is typically preprocessed by tokenization. To gain a better idea of what preprocessing looks like for other input types, check out the Preprocess tutorial. pretrained model A model that has been pretrained on some data (for instance all of Wikipedia). Pretraining methods involve a self-supervised objective, which can be reading the text and trying to predict the next word (see causal language modeling) or masking some words and trying to predict them (see masked language modeling). Speech and vision models have their own pretraining objectives. For example, Wav2Vec2 is a speech model pretrained on a contrastive task which requires the model to identify the "true" speech representation from a set of "false" speech representations. On the other hand, BEiT is a vision model pretrained on a masked image modeling task which masks some of the image patches and requires the model to predict the masked patches (similar to the masked language modeling objective). R recurrent neural network (RNN) A type of model that uses a loop over a layer to process texts. representation learning A subfield of machine learning which focuses on learning meaningful representations of raw data. Some examples of representation learning techniques include word embeddings, autoencoders, and Generative Adversarial Networks (GANs). S sampling rate A measurement in hertz of the number of samples (the audio signal) taken per second. The sampling rate is a result of discretizing a continuous signal such as speech. self-attention Each element of the input finds out which other elements of the input they should attend to. self-supervised learning A category of machine learning techniques in which a model creates its own learning objective from unlabeled data. It differs from unsupervised learning and supervised learning in that the learning process is supervised, but not explicitly from the user. One example of self-supervised learning is masked language modeling, where a model is passed sentences with a proportion of its tokens removed and learns to predict the missing tokens. semi-supervised learning A broad category of machine learning training techniques that leverages a small amount of labeled data with a larger quantity of unlabeled data to improve the accuracy of a model, unlike supervised learning and unsupervised learning. An example of a semi-supervised learning approach is "self-training", in which a model is trained on labeled data, and then used to make predictions on the unlabeled data. The portion of the unlabeled data that the model predicts with the most confidence gets added to the labeled dataset and used to retrain the model. sequence-to-sequence (seq2seq) Models that generate a new sequence from an input, like translation models, or summarization models (such as Bart or T5). Sharded DDP Another name for the foundational ZeRO concept as used by various other implementations of ZeRO. stride In convolution or pooling, the stride refers to the distance the kernel is moved over a matrix. A stride of 1 means the kernel is moved one pixel over at a time, and a stride of 2 means the kernel is moved two pixels over at a time. supervised learning A form of model training that directly uses labeled data to correct and instruct model performance. Data is fed into the model being trained, and its predictions are compared to the known labels. The model updates its weights based on how incorrect its predictions were, and the process is repeated to optimize model performance. T Tensor Parallelism (TP) Parallelism technique for training on multiple GPUs in which each tensor is split up into multiple chunks, so instead of having the whole tensor reside on a single GPU, each shard of the tensor resides on its designated GPU. Shards gets processed separately and in parallel on different GPUs and the results are synced at the end of the processing step. This is what is sometimes called horizontal parallelism, as the splitting happens on horizontal level. Learn more about Tensor Parallelism here. token A part of a sentence, usually a word, but can also be a subword (non-common words are often split in subwords) or a punctuation symbol. token Type IDs Some models' purpose is to do classification on pairs of sentences or question answering.
These require two different sequences to be joined in a single "input_ids" entry, which usually is performed with the help of special tokens, such as the classifier ([CLS]) and separator ([SEP]) tokens. For example, the BERT model builds its two sequence input as such: thon [CLS] SEQUENCE_A [SEP] SEQUENCE_B [SEP] We can use our tokenizer to automatically generate such a sentence by passing the two sequences to tokenizer as two arguments (and not a list, like before) like this: thon
We can use our tokenizer to automatically generate such a sentence by passing the two sequences to tokenizer as two arguments (and not a list, like before) like this: thon from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") sequence_a = "HuggingFace is based in NYC" sequence_b = "Where is HuggingFace based?" encoded_dict = tokenizer(sequence_a, sequence_b) decoded = tokenizer.decode(encoded_dict["input_ids"]) which will return: thon
which will return: thon print(decoded) [CLS] HuggingFace is based in NYC [SEP] Where is HuggingFace based? [SEP] This is enough for some models to understand where one sequence ends and where another begins. However, other models, such as BERT, also deploy token type IDs (also called segment IDs). They are represented as a binary mask identifying the two types of sequence in the model. The tokenizer returns this mask as the "token_type_ids" entry: thon
encoded_dict["token_type_ids"] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]
The first sequence, the "context" used for the question, has all its tokens represented by a 0, whereas the second sequence, corresponding to the "question", has all its tokens represented by a 1. Some models, like [XLNetModel] use an additional token represented by a 2. transfer learning A technique that involves taking a pretrained model and adapting it to a dataset specific to your task. Instead of training a model from scratch, you can leverage knowledge obtained from an existing model as a starting point. This speeds up the learning process and reduces the amount of training data needed. transformer Self-attention based deep learning model architecture. U unsupervised learning A form of model training in which data provided to the model is not labeled. Unsupervised learning techniques leverage statistical information of the data distribution to find patterns useful for the task at hand. Z Zero Redundancy Optimizer (ZeRO) Parallelism technique which performs sharding of the tensors somewhat similar to TensorParallel, except the whole tensor gets reconstructed in time for a forward or backward computation, therefore the model doesn't need to be modified. This method also supports various offloading techniques to compensate for limited GPU memory. Learn more about ZeRO here.
XLA Integration for TensorFlow Models [[open-in-colab]] Accelerated Linear Algebra, dubbed XLA, is a compiler for accelerating the runtime of TensorFlow Models. From the official documentation: XLA (Accelerated Linear Algebra) is a domain-specific compiler for linear algebra that can accelerate TensorFlow models with potentially no source code changes. Using XLA in TensorFlow is simple – it comes packaged inside the tensorflow library, and it can be triggered with the jit_compile argument in any graph-creating function such as tf.function. When using Keras methods like fit() and predict(), you can enable XLA simply by passing the jit_compile argument to model.compile(). However, XLA is not limited to these methods - it can also be used to accelerate any arbitrary tf.function. Several TensorFlow methods in πŸ€— Transformers have been rewritten to be XLA-compatible, including text generation for models such as GPT2, T5 and OPT, as well as speech processing for models such as Whisper. While the exact amount of speed-up is very much model-dependent, for TensorFlow text generation models inside πŸ€— Transformers, we noticed a speed-up of ~100x. This document will explain how you can use XLA for these models to get the maximum amount of performance. We’ll also provide links to additional resources if you’re interested to learn more about the benchmarks and our design philosophy behind the XLA integration. Running TF functions with XLA Let us consider the following model in TensorFlow: