Skip to content

Commit 81799d8

Browse files
yanamisydshieh
andauthored
Standardize ByT5 model card format (#38699)
* Standardize ByT5 model card format * Apply review feedback from @stevhliu * Fix Notes formatting and wording * Fix `aya_vision` test (#38674) * fix 1: load_in_4bit=True, * fix 2: decorateor * fixfix 2: breakpoint * fixfix 3: update * fixfix 4: fast * fixfix 5: cond * fixfix 5: cond * fixfix 6: cuda 8 * ruff * breakpoint * dtype * a10 * a10 --------- Co-authored-by: ydshieh <[email protected]> * Fix autodoc formatting for ByT5Tokenizer --------- Co-authored-by: Yih-Dar <[email protected]> Co-authored-by: ydshieh <[email protected]>
1 parent e55983e commit 81799d8

File tree

1 file changed

+98
-120
lines changed

1 file changed

+98
-120
lines changed

docs/source/en/model_doc/byt5.md

Lines changed: 98 additions & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -13,150 +13,128 @@ specific language governing permissions and limitations under the License.
1313
rendered properly in your Markdown viewer.
1414
1515
-->
16-
17-
# ByT5
18-
19-
<div class="flex flex-wrap space-x-1">
20-
<img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white">
21-
<img alt="TensorFlow" src="https://img.shields.io/badge/TensorFlow-FF6F00?style=flat&logo=tensorflow&logoColor=white">
22-
<img alt="Flax" src="https://img.shields.io/badge/Flax-29a79b.svg?style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAtCAMAAAANxBKoAAAC7lBMVEUAAADg5vYHPVgAoJH+/v76+v39/f9JbLP///9+AIgAnY3///+mcqzt8fXy9fgkXa3Ax9709fr+///9/f8qXq49qp5AaLGMwrv8/P0eW60VWawxYq8yqJzG2dytt9Wyu9elzci519Lf3O3S2efY3OrY0+Xp7PT///////+dqNCexMc6Z7AGpJeGvbenstPZ5ejQ1OfJzOLa7ejh4+/r8fT29vpccbklWK8PVa0AS6ghW63O498vYa+lsdKz1NDRt9Kw1c672tbD3tnAxt7R6OHp5vDe7OrDyuDn6vLl6/EAQK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klIpFNfHpdEafIF2aRmOcrUmjohbT2WUllbmRvgfbythbQO3222fpDJoufaQPncYYuqoGtUEsCJZL6/3PR5b4syeSjZMQG/T2maGANlXT2v8S4AULWaUkCxfLyW8iW4kdka+nEMjxpL2NCwsYNBp+Q61PF43zyDg9Bm9+3NNySn78jMZUUkumqE4Gp7JmFOdP1vc8PpRrzj9+wPinCy8K1PiJ4aYbnTYpCCbDkBSbzhu2QJ1Gd82t8jI8TH51+OzvXoWbnXUOBkNW+0mWFwGcGOUVpU81/n3TOHb5oMt2FgYGjzau0Nif0Ss7Q3XB33hjjQHjHA5E5aOyIQc8CBrLdQSs3j92VG+3nNEjbkbdbBr9zm04ruvw37vh0QKOdeGIkckc80fX3KH/h7PT4BOjgCty8VZ5ux1MoO5Cf5naca2LAsEgehI+drX8o/0Nu+W0m6K/I9gGPd/dfx/EN/wN62AhsBWuAAAAAElFTkSuQmCC
23-
">
16+
<div style="float: right;">
17+
<div class="flex flex-wrap space-x-1">
18+
<img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white">
19+
<img alt="TensorFlow" src="https://img.shields.io/badge/TensorFlow-FF6F00?style=flat&logo=tensorflow&logoColor=white">
20+
<img alt="Flax" src="https://img.shields.io/badge/Flax-29a79b.svg?style=flat&logo=flax&logoColor=white">
21+
</div>
2422
</div>
2523

26-
## Overview
27-
28-
The ByT5 model was presented in [ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://arxiv.org/abs/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir
29-
Kale, Adam Roberts, Colin Raffel.
30-
31-
The abstract from the paper is the following:
32-
33-
*Most widely-used pre-trained language models operate on sequences of tokens corresponding to word or subword units.
34-
Encoding text as a sequence of tokens requires a tokenizer, which is typically created as an independent artifact from
35-
the model. Token-free models that instead operate directly on raw text (bytes or characters) have many benefits: they
36-
can process text in any language out of the box, they are more robust to noise, and they minimize technical debt by
37-
removing complex and error-prone text preprocessing pipelines. Since byte or character sequences are longer than token
38-
sequences, past work on token-free models has often introduced new model architectures designed to amortize the cost of
39-
operating directly on raw text. In this paper, we show that a standard Transformer architecture can be used with
40-
minimal modifications to process byte sequences. We carefully characterize the trade-offs in terms of parameter count,
41-
training FLOPs, and inference speed, and show that byte-level models are competitive with their token-level
42-
counterparts. We also demonstrate that byte-level models are significantly more robust to noise and perform better on
43-
tasks that are sensitive to spelling and pronunciation. As part of our contribution, we release a new set of
44-
pre-trained byte-level Transformer models based on the T5 architecture, as well as all code and data used in our
45-
experiments.*
46-
47-
This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The original code can be
48-
found [here](https://github.com/google-research/byt5).
24+
# ByT5
4925

50-
<Tip>
26+
[ByT5](https://huggingface.co/papers/2105.13626) is tokenizer-free version of the [T5](./t5) model designed to works directly on raw UTF-8 bytes. This means it can process any language, more robust to noise like typos, and simpler to use because it doesn't require a preprocessing pipeline.
5127

52-
ByT5's architecture is based on the T5v1.1 model, refer to [T5v1.1's documentation page](t5v1.1) for the API reference. They
53-
only differ in how inputs should be prepared for the model, see the code examples below.
28+
You can find all the original ByT5 checkpoints under the [Google](https://huggingface.co/google?search_models=byt5) organization.
5429

55-
</Tip>
30+
> [!TIP]
31+
> Refer to the [T5](./t5) docs for more examples of how to apply ByT5 to different language tasks.
5632
57-
Since ByT5 was pre-trained unsupervisedly, there's no real advantage to using a task prefix during single-task
58-
fine-tuning. If you are doing multi-task fine-tuning, you should use a prefix.
33+
The example below demonstrates how to generate text with [`Pipeline`], [`AutoModel`] and from the command line.
5934

35+
<hfoptions id="usage">
36+
<hfoption id="Pipeline">
6037

61-
## Usage example
38+
```python
39+
import torch
40+
from transformers import pipeline
41+
42+
pipeline = pipeline(
43+
task="text2text-generation",
44+
model="google/byt5-small",
45+
torch_dtype=torch.float16,
46+
device=0
47+
)
48+
pipeline("translate English to French: The weather is nice today")
49+
```
6250

63-
ByT5 works on raw UTF-8 bytes, so it can be used without a tokenizer:
51+
</hfoption>
52+
<hfoption id="AutoModel">
6453

6554
```python
66-
>>> from transformers import T5ForConditionalGeneration
67-
>>> import torch
55+
import torch
56+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
57+
58+
tokenizer = AutoTokenizer.from_pretrained(
59+
"google/byt5-small"
60+
)
61+
model = AutoModelForSeq2SeqLM.from_pretrained(
62+
"google/byt5-small",
63+
torch_dtype=torch.float16,
64+
device_map="auto"
65+
)
66+
67+
input_ids = tokenizer("summarize: Photosynthesis is the process by which plants, algae, and some bacteria convert light energy into chemical energy.", return_tensors="pt").to("cuda")
68+
69+
output = model.generate(**input_ids)
70+
print(tokenizer.decode(output[0], skip_special_tokens=True))
71+
```
6872

69-
>>> model = T5ForConditionalGeneration.from_pretrained("google/byt5-small")
73+
</hfoption>
74+
<hfoption id="transformers-cli">
7075

71-
>>> num_special_tokens = 3
72-
>>> # Model has 3 special tokens which take up the input ids 0,1,2 of ByT5.
73-
>>> # => Need to shift utf-8 character encodings by 3 before passing ids to model.
76+
```bash
77+
echo -e "translate English to French: Life is beautiful." | transformers-cli run --task text2text-generation --model google/byt5-small --device 0
78+
```
7479

75-
>>> input_ids = torch.tensor([list("Life is like a box of chocolates.".encode("utf-8"))]) + num_special_tokens
80+
</hfoption>
81+
</hfoptions>
7682

77-
>>> labels = torch.tensor([list("La vie est comme une boîte de chocolat.".encode("utf-8"))]) + num_special_tokens
83+
## Quantization
7884

79-
>>> loss = model(input_ids, labels=labels).loss
80-
>>> loss.item()
81-
2.66
82-
```
85+
Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends.
8386

84-
For batched inference and training it is however recommended to make use of the tokenizer:
87+
The example below uses [torchao](../quantization/torchao) to only quantize the weights to int4.
8588

8689
```python
87-
>>> from transformers import T5ForConditionalGeneration, AutoTokenizer
88-
89-
>>> model = T5ForConditionalGeneration.from_pretrained("google/byt5-small")
90-
>>> tokenizer = AutoTokenizer.from_pretrained("google/byt5-small")
91-
92-
>>> model_inputs = tokenizer(
93-
... ["Life is like a box of chocolates.", "Today is Monday."], padding="longest", return_tensors="pt"
94-
... )
95-
>>> labels_dict = tokenizer(
96-
... ["La vie est comme une boîte de chocolat.", "Aujourd'hui c'est lundi."], padding="longest", return_tensors="pt"
97-
... )
98-
>>> labels = labels_dict.input_ids
99-
100-
>>> loss = model(**model_inputs, labels=labels).loss
101-
>>> loss.item()
102-
17.9
103-
```
90+
# pip install torchao
91+
import torch
92+
from transformers import TorchAoConfig, AutoModelForSeq2SeqLM, AutoTokenizer
10493

105-
Similar to [T5](t5), ByT5 was trained on the span-mask denoising task. However,
106-
since the model works directly on characters, the pretraining task is a bit
107-
different. Let's corrupt some characters of the
108-
input sentence `"The dog chases a ball in the park."` and ask ByT5 to predict them
109-
for us.
94+
quantization_config = TorchAoConfig("int4_weight_only", group_size=128)
11095

111-
```python
112-
>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
113-
>>> import torch
114-
115-
>>> tokenizer = AutoTokenizer.from_pretrained("google/byt5-base")
116-
>>> model = AutoModelForSeq2SeqLM.from_pretrained("google/byt5-base")
117-
118-
>>> input_ids_prompt = "The dog chases a ball in the park."
119-
>>> input_ids = tokenizer(input_ids_prompt).input_ids
120-
121-
>>> # Note that we cannot add "{extra_id_...}" to the string directly
122-
>>> # as the Byte tokenizer would incorrectly merge the tokens
123-
>>> # For ByT5, we need to work directly on the character level
124-
>>> # Contrary to T5, ByT5 does not use sentinel tokens for masking, but instead
125-
>>> # uses final utf character ids.
126-
>>> # UTF-8 is represented by 8 bits and ByT5 has 3 special tokens.
127-
>>> # => There are 2**8+2 = 259 input ids and mask tokens count down from index 258.
128-
>>> # => mask to "The dog [258]a ball [257]park."
129-
130-
>>> input_ids = torch.tensor([input_ids[:8] + [258] + input_ids[14:21] + [257] + input_ids[28:]])
131-
>>> input_ids
132-
tensor([[ 87, 107, 104, 35, 103, 114, 106, 35, 258, 35, 100, 35, 101, 100, 111, 111, 257, 35, 115, 100, 117, 110, 49, 1]])
133-
134-
>>> # ByT5 produces only one char at a time so we need to produce many more output characters here -> set `max_length=100`.
135-
>>> output_ids = model.generate(input_ids, max_length=100)[0].tolist()
136-
>>> output_ids
137-
[0, 258, 108, 118, 35, 119, 107, 104, 35, 114, 113, 104, 35, 122, 107, 114, 35, 103, 114, 104, 118, 257, 35, 108, 113, 35, 119, 107, 104, 35, 103, 108, 118, 102, 114, 256, 108, 113, 35, 119, 107, 104, 35, 115, 100, 117, 110, 49, 35, 87, 107, 104, 35, 103, 114, 106, 35, 108, 118, 35, 119, 107, 104, 35, 114, 113, 104, 35, 122, 107, 114, 35, 103, 114, 104, 118, 35, 100, 35, 101, 100, 111, 111, 35, 108, 113, 255, 35, 108, 113, 35, 119, 107, 104, 35, 115, 100, 117, 110, 49]
138-
139-
>>> # ^- Note how 258 descends to 257, 256, 255
140-
141-
>>> # Now we need to split on the sentinel tokens, let's write a short loop for this
142-
>>> output_ids_list = []
143-
>>> start_token = 0
144-
>>> sentinel_token = 258
145-
>>> while sentinel_token in output_ids:
146-
... split_idx = output_ids.index(sentinel_token)
147-
... output_ids_list.append(output_ids[start_token:split_idx])
148-
... start_token = split_idx
149-
... sentinel_token -= 1
150-
151-
>>> output_ids_list.append(output_ids[start_token:])
152-
>>> output_string = tokenizer.batch_decode(output_ids_list)
153-
>>> output_string
154-
['<pad>', 'is the one who does', ' in the disco', 'in the park. The dog is the one who does a ball in', ' in the park.']
96+
model = AutoModelForSeq2SeqLM.from_pretrained(
97+
"google/byt5-xl",
98+
torch_dtype=torch.bfloat16,
99+
device_map="auto",
100+
quantization_config=quantization_config
101+
)
102+
103+
tokenizer = AutoTokenizer.from_pretrained("google/byt5-xl")
104+
input_ids = tokenizer("translate English to French: The weather is nice today.", return_tensors="pt").to("cuda")
105+
106+
output = model.generate(**input_ids)
107+
print(tokenizer.decode(output[0], skip_special_tokens=True))
155108
```
156109

110+
## Notes
111+
112+
- It is recommended to use the tokenizer for batched inference and training.
113+
- The example below shows how to use the model without a tokenizer.
114+
115+
```python
116+
import torch
117+
from transformers import AutoModelForSeq2SeqLM
118+
119+
model = AutoModelForSeq2SeqLM.from_pretrained("google/byt5-small")
120+
121+
num_special_tokens = 3
122+
123+
input_ids = torch.tensor([list("Life is like a box of chocolates.".encode("utf-8"))]) + num_special_tokens
124+
labels = torch.tensor([list("La vie est comme une boîte de chocolat.".encode("utf-8"))]) + num_special_tokens
125+
loss = model(input_ids, labels=labels).loss
126+
loss.item()
127+
```
128+
129+
- ByT5 uses the top byte values (258, 257, etc.) for masking instead of sentinel tokens like `{extra_id_0}`.
130+
131+
```python
132+
# Example: character-level denoising with mask tokens
133+
input_ids = tokenizer("The dog chases a ball in the park.").input_ids
134+
masked_input = torch.tensor([input_ids[:8] + [258] + input_ids[14:21] + [257] + input_ids[28:]])
135+
output = model.generate(masked_input, max_length=100)
136+
```
157137

158138
## ByT5Tokenizer
159139

160140
[[autodoc]] ByT5Tokenizer
161-
162-
See [`ByT5Tokenizer`] for all details.

0 commit comments

Comments
 (0)