# ByT5

[ByT5](https://huggingface.co/papers/2105.13626)は、[T5](./t5)モデルのトークナイザー不要版であり、生のUTF-8バイト列を直接処理するように設計されています。そのため、あらゆる言語を処理でき、誤字などのノイズに対してより頑健で、前処理パイプラインを必要としないため、使用がよりシンプルになります。

すべての ByT5 の元のチェックポイントは、[Google](https://huggingface.co/google?search_models=byt5) 組織の下で確認できます。

> [!TIP]
> ByT5 を異なる言語タスクに適用する方法のより多くの例については、[T5](./t5) のドキュメントを参照してください。

以下の例では、[Pipeline](/docs/transformers/main/ja/main_classes/pipelines#transformers.Pipeline)、[AutoModel](/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel)、およびコマンドラインからテキストを生成する方法を示しています。

```python
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained(
    "google/byt5-small"
)
model = AutoModelForSeq2SeqLM.from_pretrained(
    "google/byt5-small",
    device_map="auto"
)

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(model.device)

output = model.generate(**input_ids)
print(tokenizer.decode(output[0], skip_special_tokens=True))
```

## 量子化

Quantization は、重みを低精度で表現することで、大規模モデルのメモリ負荷を軽減します。利用可能な Quantization バックエンドの詳細については、[Quantization](../quantization/overview) の概要を参照してください。

以下の例では、[torchao](../quantization/torchao)を使用して、重みを int4 にのみ量子化します。

```python
# pip install torchao
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, TorchAoConfig

quantization_config = TorchAoConfig("int4_weight_only", group_size=128)

model = AutoModelForSeq2SeqLM.from_pretrained(
    "google/byt5-xl",
    device_map="auto",
    quantization_config=quantization_config
)

tokenizer = AutoTokenizer.from_pretrained("google/byt5-xl")
input_ids = tokenizer("translate English to French: The weather is nice today.", return_tensors="pt").to(model.device)

output = model.generate(**input_ids)
print(tokenizer.decode(output[0], skip_special_tokens=True))
```

## 注記

- バッチ推論および学習では、tokenizerを使用することをお勧めします。
- 以下の例は、トークナイザなしでモデルを使用する方法を示しています。

    ```python
    import torch
    from transformers import AutoModelForSeq2SeqLM

    model = AutoModelForSeq2SeqLM.from_pretrained("google/byt5-small", device_map="auto")

    num_special_tokens = 3

    input_ids = torch.tensor([list("Life is like a box of chocolates.".encode("utf-8"))]) + num_special_tokens
    labels = torch.tensor([list("La vie est comme une boîte de chocolat.".encode("utf-8"))]) + num_special_tokens
    loss = model(input_ids, labels=labels).loss
    loss.item()
    ```

- ByT5は、`{extra_id_0}`のようなセンチネルトークンではなく、マスク用に上位バイト値（258、257など）を使用します。

    ```python
    # Example: character-level denoising with mask tokens
    input_ids = tokenizer("The dog chases a ball in the park.").input_ids
    masked_input = torch.tensor([input_ids[:8] + [258] + input_ids[14:21] + [257] + input_ids[28:]])
    output = model.generate(masked_input, max_length=100)
    ```

## ByT5Tokenizer[[transformers.ByT5Tokenizer]]

#### transformers.ByT5Tokenizer[[transformers.ByT5Tokenizer]]

```python
transformers.ByT5Tokenizer(eos_token = '</s>', unk_token = '<unk>', pad_token = '<pad>', extra_ids = 125, additional_special_tokens = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/byt5/tokenization_byt5.py#L25)

**パラメータ:**

eos_token (`str`、*任意*、デフォルトは`"</s>"`) : シーケンスの終了トークン。特殊トークンを使用してシーケンスを構築する場合は、シーケンスの終了に使用されるトークンではありません。使用されるトークンは`sep_token`です。

unk_token (`str`、*任意*、デフォルトは `"<unk>"`) : 不明トークン。語彙に存在しないトークンは ID に変換できず、代わりにこのトークンが設定されます。

pad_token (`str`、*任意*、デフォルトは `"<pad>"`) : パディングに使用されるトークンです。長さの異なるシーケンスをバッチ処理する場合などに使用します。

extra_ids (`int`、*optional*、デフォルト値は 125) : センチネルとして使用するために、語彙の末尾に追加する追加 ID の数を指定します。これらのトークンは、"{%d}" が 0 から extra_ids-1 までの数値である "" としてアクセスできます。追加トークンは、語彙の末尾から先頭に向かってインデックス付けられます（"" は語彙の最後のトークンです。ByT5 の前処理と同様、詳細は[こちら](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)を参照してください）。

additional_special_tokens (`list[str]`、*任意*) : トークナイザーで使用される追加の特殊トークン。

ByT5 トークナイザーを構築します。ByT5 は、生のバイトの utf-8 エンコーディングをそのまま使用します。

このトークナイザーは、[PreTrainedTokenizer](/docs/transformers/main/ja/main_classes/tokenizer#transformers.PythonBackend) を継承しており、主要なメソッドのほとんどが含まれています。これらのメソッドに関する詳細については、このスーパークラスを参照してください。

#### build_inputs_with_special_tokens[[transformers.ByT5Tokenizer.build_inputs_with_special_tokens]]

```python
build_inputs_with_special_tokens(token_ids_0: list, token_ids_1: list[int] | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/byt5/tokenization_byt5.py#L169)

**パラメータ:**

token_ids_0 (`list[int]`) : 特殊トークンが追加されるIDのリスト。

token_ids_1 (`list[int]`, *任意*) : シーケンスペア用の任意の第2のIDリスト。

**戻り値:** `list[int]`

適切な特殊トークンを含む[入力 ID](../glossary#input-ids)のリスト。

シーケンス分類タスクにおいて、シーケンスまたはシーケンスのペアからモデルの入力を構築するために、特殊トークンを追加して連結します。シーケンスの形式は以下の通りです：

- 単一シーケンス: `X </s>`
- シーケンスのペア: `A </s> B </s>`

#### convert_tokens_to_string[[transformers.ByT5Tokenizer.convert_tokens_to_string]]

```python
convert_tokens_to_string(tokens)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/byt5/tokenization_byt5.py#L215)

単一の文字列内のトークン（文字列）のシーケンスに変換します。

#### create_token_type_ids_from_sequences[[transformers.ByT5Tokenizer.create_token_type_ids_from_sequences]]

```python
create_token_type_ids_from_sequences(token_ids_0: list, token_ids_1: list[int] | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/byt5/tokenization_byt5.py#L147)

**パラメータ:**

token_ids_0 (`list[int]`) : ID のリスト。

token_ids_1 (`list[int]`, *任意*) : シーケンスペア用の任意の第2のIDリスト。

**戻り値:** `list[int]`

ゼロのリスト。

シーケンスペア分類タスクで使用するために、渡された2つのシーケンスからマスクを作成します。ByT5はトークンタイプIDを使用しないため、ゼロのリストが返されます。

#### get_special_tokens_mask[[transformers.ByT5Tokenizer.get_special_tokens_mask]]

```python
get_special_tokens_mask(token_ids_0: list, token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/byt5/tokenization_byt5.py#L108)

**パラメータ:**

token_ids_0 (`list[int]`) : ID のリスト。

token_ids_1 (`list[int]`, *任意*) : シーケンスペア用の任意の第2のIDリスト。

already_has_special_tokens (`bool`、*任意*、デフォルトは`False`) : トークンリストが、モデル用の特殊トークンを含む形式で既に整形されているかどうかを示します。

**戻り値:** `list[int]`

範囲 [0, 1] の整数のリスト: 特殊トークンは 1、シーケンストークンは 0。

特殊トークンが追加されていないトークンリストからシーケンスIDを取得します。このメソッドは、トークナイザーの`prepare_for_model`メソッドを使用して特殊トークンを追加する際に呼び出されます。

