source
stringclasses
470 values
url
stringlengths
49
167
file_type
stringclasses
1 value
chunk
stringlengths
1
512
chunk_id
stringlengths
5
9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#diverse-beam-search-decoding
.md
... "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, "
15_13_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#diverse-beam-search-decoding
.md
... "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." ... )
15_13_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#diverse-beam-search-decoding
.md
>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint) >>> inputs = tokenizer(prompt, return_tensors="pt") >>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
15_13_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#diverse-beam-search-decoding
.md
>>> 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
15_13_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#diverse-beam-search-decoding
.md
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](./main_classes/text_generation).
15_13_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#speculative-decoding
.md
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), 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](https://arxiv.org/pdf/2211.17192.pdf) is used.
15_14_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#speculative-decoding
.md
resampling introduced in the [speculative decoding paper](https://arxiv.org/pdf/2211.17192.pdf) is used. Assisted decoding assumes the main and assistant models have the same tokenizer, otherwise, see Universal Assisted Decoding below. 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](https://huggingface.co/blog/assisted-generation).
15_14_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#speculative-decoding
.md
To learn more about assisted decoding, check [this blog post](https://huggingface.co/blog/assisted-generation). To enable assisted decoding, set the `assistant_model` argument with a model. ```python >>> from transformers import AutoModelForCausalLM, AutoTokenizer
15_14_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#speculative-decoding
.md
>>> 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")
15_14_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#speculative-decoding
.md
>>> 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'] ``` <Tip> If you're using a `pipeline` object, all you need to do is to pass the assistant checkpoint under `assistant_model` ```python
15_14_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#speculative-decoding
.md
If you're using a `pipeline` object, all you need to do is to pass the assistant checkpoint under `assistant_model` ```python >>> from transformers import pipeline >>> import torch
15_14_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#speculative-decoding
.md
>>> pipe = pipeline( ... "text-generation", ... model="meta-llama/Llama-3.1-8B", ... assistant_model="meta-llama/Llama-3.2-1B", # This extra line is all that's needed, also works with UAD ... torch_dtype=torch.bfloat16 >>> ) >>> pipe_output = pipe("Once upon a time, ", max_new_tokens=50, do_sample=False) >>> pipe_output[0]["generated_text"] 'Once upon a time, 3D printing was a niche technology that was only' ``` </Tip>
15_14_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#speculative-decoding
.md
>>> pipe_output[0]["generated_text"] 'Once upon a time, 3D printing was a niche technology that was only' ``` </Tip> 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. ```python >>> from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed >>> set_seed(42) # For reproducibility
15_14_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#speculative-decoding
.md
>>> 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")
15_14_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#speculative-decoding
.md
>>> 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, a couple of friends of mine, who are both in the same office as'] ```
15_14_9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#speculative-decoding
.md
['Alice and Bob, a couple of friends of mine, who are both in the same office as'] ``` We recommend to install `scikit-learn` library to enhance the candidate generation strategy and achieve additional speedup.
15_14_10
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#universal-assisted-decoding
.md
Universal Assisted Decoding (UAD) adds support for main and assistant models with different tokenizers. To use it, simply pass the tokenizers using the `tokenizer` and `assistant_tokenizer` arguments (see below). Internally, the main model input tokens are re-encoded into assistant model tokens, then candidate tokens are generated in the assistant encoding, which are in turn re-encoded into main model candidate tokens. Validation then proceeds as explained above.
15_15_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#universal-assisted-decoding
.md
in turn re-encoded into main model candidate tokens. Validation then proceeds as explained above. The re-encoding steps involve decoding token ids into text and then encoding the text using a different tokenizer. Since re-encoding the tokens may result in tokenization discrepancies, UAD finds the longest common subsequence between the source and target encodings, to ensure the new tokens include the correct prompt suffix. ```python >>> from transformers import AutoModelForCausalLM, AutoTokenizer
15_15_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#universal-assisted-decoding
.md
>>> prompt = "Alice and Bob" >>> checkpoint = "google/gemma-2-9b" >>> assistant_checkpoint = "double7/vicuna-68m" >>> assistant_tokenizer = AutoTokenizer.from_pretrained(assistant_checkpoint) >>> tokenizer = AutoTokenizer.from_pretrained(checkpoint) >>> inputs = tokenizer(prompt, return_tensors="pt")
15_15_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#universal-assisted-decoding
.md
>>> model = AutoModelForCausalLM.from_pretrained(checkpoint) >>> assistant_model = AutoModelForCausalLM.from_pretrained(assistant_checkpoint) >>> outputs = model.generate(**inputs, assistant_model=assistant_model, tokenizer=tokenizer, assistant_tokenizer=assistant_tokenizer) >>> 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'] ```
15_15_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#prompt-lookup
.md
Alternatively, 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](https://twitter.com/joao_gante/status/1747322413006643259).
15_16_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#self-speculative-decoding
.md
An LLM can be trained to also use its language modeling head with earlier hidden states as input, effectively skipping layers to yield a lower-quality output -- a technique called early exiting. We use the lower-quality early exit output as an assistant output, and apply self-speculation to fix the output using the remaining layers. The final generation of that self-speculative solution is the same (or has the same distribution) as the original model's generation.
15_17_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#self-speculative-decoding
.md
If the model you're using was trained to do early exit, you can pass `assistant_early_exit` (integer). In this case, the assistant model will be the same model but exiting early, hence the "self-speculative" name. Because the assistant model is a portion of the target model, caches and weights can be shared, which results in lower memory requirements. As in other assisted generation methods, the final generated result has the same quality as if no assistant had been used. ```python
15_17_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#self-speculative-decoding
.md
```python >>> from transformers import AutoModelForCausalLM, AutoTokenizer
15_17_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#self-speculative-decoding
.md
>>> prompt = "Alice and Bob" >>> checkpoint = "facebook/layerskip-llama3.2-1B" >>> tokenizer = AutoTokenizer.from_pretrained(checkpoint) >>> inputs = tokenizer(prompt, return_tensors="pt") >>> model = AutoModelForCausalLM.from_pretrained(checkpoint) >>> outputs = model.generate(**inputs, assistant_early_exit=4, do_sample=False, max_new_tokens=20) >>> 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'] ```
15_17_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#dola-decoding
.md
**D**ecoding by C**o**ntrasting **La**yers (DoLa) is a contrastive decoding strategy to improve the factuality and reduce the hallucinations of LLMs, as described in this paper of ICLR 2024 [DoLa: Decoding by Contrasting Layers Improves Factuality in Large Language Models](https://arxiv.org/abs/2309.03883). DoLa is achieved by contrasting the differences in logits obtained from final layers versus earlier layers, thus amplify the factual knowledge localized to particular part of transformer layers.
15_18_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#dola-decoding
.md
layers versus earlier layers, thus amplify the factual knowledge localized to particular part of transformer layers. Do the following two steps to activate DoLa decoding when calling the `model.generate` function: 1. Set the `dola_layers` argument, which can be either a string or a list of integers. - If set to a string, it can be one of `low`, `high`.
15_18_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#dola-decoding
.md
- If set to a string, it can be one of `low`, `high`. - If set to a list of integers, it should be a list of layer indices between 0 and the total number of layers in the model. The 0-th layer is word embedding, and the 1st layer is the first transformer layer, and so on. 2. Set `repetition_penalty = 1.2` is suggested to reduce repetition in DoLa decoding. See the following examples for DoLa decoding with the 32-layer LLaMA-7B model. ```python
15_18_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#dola-decoding
.md
See the following examples for DoLa decoding with the 32-layer LLaMA-7B model. ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed >>> import torch >>> from accelerate.test_utils.testing import get_backend
15_18_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#dola-decoding
.md
>>> tokenizer = AutoTokenizer.from_pretrained("huggyllama/llama-7b") >>> model = AutoModelForCausalLM.from_pretrained("huggyllama/llama-7b", torch_dtype=torch.float16) >>> device, _, _ = get_backend() # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.) >>> model.to(device) >>> set_seed(42) >>> text = "On what date was the Declaration of Independence officially signed?" >>> inputs = tokenizer(text, return_tensors="pt").to(device)
15_18_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#dola-decoding
.md
# Vanilla greddy decoding >>> vanilla_output = model.generate(**inputs, do_sample=False, max_new_tokens=50) >>> tokenizer.batch_decode(vanilla_output[:, inputs.input_ids.shape[-1]:], skip_special_tokens=True) ['\nThe Declaration of Independence was signed on July 4, 1776.\nWhat was the date of the signing of the Declaration of Independence?\nThe Declaration of Independence was signed on July 4,']
15_18_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#dola-decoding
.md
# DoLa decoding with contrasting higher part of layers (layers 16,18,...,30) >>> dola_high_output = model.generate(**inputs, do_sample=False, max_new_tokens=50, dola_layers='high') >>> tokenizer.batch_decode(dola_high_output[:, inputs.input_ids.shape[-1]:], skip_special_tokens=True) ['\nJuly 4, 1776, when the Continental Congress voted to separate from Great Britain. The 56 delegates to the Continental Congress signed the Declaration on August 2, 1776.']
15_18_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#dola-decoding
.md
# DoLa decoding with contrasting specific layers (layers 28 and 30) >>> dola_custom_output = model.generate(**inputs, do_sample=False, max_new_tokens=50, dola_layers=[28,30], repetition_penalty=1.2) >>> tokenizer.batch_decode(dola_custom_output[:, inputs.input_ids.shape[-1]:], skip_special_tokens=True)
15_18_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#dola-decoding
.md
>>> tokenizer.batch_decode(dola_custom_output[:, inputs.input_ids.shape[-1]:], skip_special_tokens=True) ['\nIt was officially signed on 2 August 1776, when 56 members of the Second Continental Congress, representing the original 13 American colonies, voted unanimously for the resolution for independence. The 2'] ```
15_18_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#understanding-the-dolalayers-argument
.md
`dola_layers` stands for the candidate layers in premature layer selection, as described in the DoLa paper. The selected premature layer will be contrasted with the final layer. Setting `dola_layers` to `'low'` or `'high'` will select the lower or higher part of the layers to contrast, respectively. - For `N`-layer models with `N <= 40` layers, the layers of `range(0, N // 2, 2)` and `range(N // 2, N, 2)` are used for `'low'` and `'high'` layers, respectively.
15_19_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#understanding-the-dolalayers-argument
.md
- For models with `N > 40` layers, the layers of `range(0, 20, 2)` and `range(N - 20, N, 2)` are used for `'low'` and `'high'` layers, respectively. - If the model has tied word embeddings, we skip the word embeddings (0-th) layer and start from the 2nd layer, as the early exit from word embeddings will become identity function.
15_19_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#understanding-the-dolalayers-argument
.md
- Set the `dola_layers` to a list of integers for layer indices to contrast manually specified layers. For example, setting `dola_layers=[28,30]` will contrast the final layer (32-th layer) with the 28-th and 30-th layers.
15_19_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/generation_strategies.md
https://huggingface.co/docs/transformers/en/generation_strategies/#understanding-the-dolalayers-argument
.md
The paper suggested that contrasting `'high'` layers to improve short-answer tasks like TruthfulQA, and contrasting `'low'` layers to improve all the other long-answer reasoning tasks, such as GSM8K, StrategyQA, FACTOR, and VicunaQA. Applying DoLa to smaller models like GPT-2 is not recommended, as the results shown in the Appendix N of the paper.
15_19_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/
.md
<!--Copyright 2020 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
16_0_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/
.md
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. -->
16_0_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#glossary
.md
This glossary defines general machine learning and 🤗 Transformers terms to help you better understand the documentation.
16_1_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#attention-mask
.md
The attention mask is an optional argument used when batching sequences together. <Youtube id="M6adb1j2jPI"/> This argument indicates to the model which tokens should be attended to, and which should not. For example, consider these two sequences: ```python >>> from transformers import BertTokenizer >>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased")
16_2_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#attention-mask
.md
>>> 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."
16_2_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#attention-mask
.md
>>> encoded_sequence_a = tokenizer(sequence_a)["input_ids"] >>> encoded_sequence_b = tokenizer(sequence_b)["input_ids"] ``` The encoded versions have different lengths: ```python >>> 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.
16_2_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#attention-mask
.md
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: ```python >>> 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: ```python >>> padded_sequences["input_ids"]
16_2_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#attention-mask
.md
```python >>> 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
16_2_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#attention-mask
.md
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": ```python >>> 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]] ```
16_2_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#autoencoding-models
.md
See [encoder models](#encoder-models) and [masked language modeling](#masked-language-modeling-mlm)
16_3_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#autoregressive-models
.md
See [causal language modeling](#causal-language-modeling) and [decoder models](#decoder-models)
16_4_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#backbone
.md
The backbone is the network (embeddings and layers) that outputs the raw hidden states or features. It is usually connected to a [head](#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](model_doc/dpt).
16_5_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#causal-language-modeling
.md
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.
16_6_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#channel
.md
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`].
16_7_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#connectionist-temporal-classification-ctc
.md
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.
16_8_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#convolution
.md
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.
16_9_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#dataparallel-dp
.md
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](perf_train_gpu_many#dataparallel-vs-distributeddataparallel).
16_10_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#decoder-input-ids
.md
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.
16_11_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#decoder-input-ids
.md
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.
16_11_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#decoder-models
.md
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. <Youtube id="d_ixlCubqQw"/>
16_12_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#deep-learning-dl
.md
Machine learning algorithms which use neural networks with several layers.
16_13_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#encoder-models
.md
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](#masked-language-modeling-mlm), which masks parts of the input sequence and forces the model to create more meaningful representations. <Youtube id="H39Z_720T5s"/>
16_14_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#feature-extraction
.md
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.
16_15_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#feed-forward-chunking
.md
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
16_16_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#feed-forward-chunking
.md
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](https://arxiv.org/abs/2001.04451) 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`
16_16_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#feed-forward-chunking
.md
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
16_16_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#feed-forward-chunking
.md
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.
16_16_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#finetuned-models
.md
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](#head). The model head is trained on your target dataset. See the [Fine-tune a pretrained model](https://huggingface.co/docs/transformers/training) tutorial for more details, and learn how to fine-tune models with 🤗 Transformers.
16_17_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#head
.md
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`].
16_18_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#head
.md
* [`Wav2Vec2ForCTC`] is a language modeling head with [CTC](#connectionist-temporal-classification-ctc) on top of the base [`Wav2Vec2Model`].
16_18_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#image-patch
.md
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.
16_19_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#inference
.md
Inference is the process of evaluating a model on new data after training is complete. See the [Pipeline for inference](https://huggingface.co/docs/transformers/pipeline_tutorial) tutorial to learn how to perform inference with 🤗 Transformers.
16_20_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#input-ids
.md
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. <Youtube id="VFp38yj8h3A"/> Each tokenizer works differently but the underlying mechanism remains the same. Here's an example using the BERT tokenizer, which is a [WordPiece](https://arxiv.org/pdf/1609.08144.pdf) tokenizer: ```python >>> from transformers import BertTokenizer
16_21_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#input-ids
.md
>>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased")
16_21_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#input-ids
.md
>>> sequence = "A Titan RTX has 24GB of VRAM" ``` The tokenizer takes care of splitting the sequence into tokens available in the tokenizer vocabulary. ```python >>> 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": ```python
16_21_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#input-ids
.md
is added for "RA" and "M": ```python >>> 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](https://github.com/huggingface/tokenizers) for peak performance. ```python >>> inputs = tokenizer(sequence) ```
16_21_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#input-ids
.md
```python >>> 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`: ```python >>> 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
16_21_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#input-ids
.md
``` 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, ```python >>> decoded_sequence = tokenizer.decode(encoded_sequence) ``` we will see ```python >>> 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.
16_21_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#labels
.md
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
16_22_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#labels
.md
- 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.
16_22_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#labels
.md
`(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).
16_22_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#labels
.md
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
16_22_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#labels
.md
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.
16_22_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#labels
.md
`(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
16_22_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#labels
.md
- 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. <Tip>
16_22_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#labels
.md
target_length)` with each value corresponding to the expected label of each individual token. <Tip> 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! </Tip> The base models ([`BertModel`]) do not accept labels, as these are the base transformer models, simply outputting features.
16_22_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#large-language-models-llm
.md
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).
16_23_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#masked-language-modeling-mlm
.md
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.
16_24_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#multimodal
.md
A task that combines texts with another kind of inputs (for instance images).
16_25_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#natural-language-generation-nlg
.md
All tasks related to generating text (for instance, [Write With Transformers](https://transformer.huggingface.co/), translation).
16_26_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#natural-language-processing-nlp
.md
A generic way to say "deal with texts".
16_27_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#natural-language-understanding-nlu
.md
All tasks related to understanding what is in a text (for instance classifying the whole text, individual words).
16_28_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#pipeline
.md
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](https://huggingface.co/docs/transformers/pipeline_tutorial).
16_29_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#pipelineparallel-pp
.md
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](perf_train_gpu_many#from-naive-model-parallelism-to-pipeline-parallelism).
16_30_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#pixel-values
.md
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.
16_31_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#pooling
.md
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.
16_32_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#position-ids
.md
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.
16_33_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#position-ids
.md
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.
16_33_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#preprocessing
.md
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](https://huggingface.co/docs/transformers/preprocessing) tutorial.
16_34_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#pretrained-model
.md
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](#causal-language-modeling)) or masking some words and trying to predict them (see [masked language modeling](#masked-language-modeling-mlm)).
16_35_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#pretrained-model
.md
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).
16_35_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/glossary.md
https://huggingface.co/docs/transformers/en/glossary/#recurrent-neural-network-rnn
.md
A type of model that uses a loop over a layer to process texts.
16_36_0