# Llama4

    
        
        
    

[Llama 4](https://ai.meta.com/blog/llama-4-multimodal-intelligence/), developed by Meta, introduces a new auto-regressive Mixture-of-Experts (MoE) architecture. This generation includes two models:

- 総パラメータ数約400Bのうち17Bがアクティブな128のエキスパートを持つ、高性能なLlama 4 Maverick。
- 効率的な Llama 4 Scout も、総パラメータ数約 109B のうち 17B のアクティブパラメータを持ち、わずか 16 のエキスパートを使用しています。
-

両方のモデルは、テキストと画像の入力を処理できるネイティブなマルチモーダル性を実現するために、早期融合（early fusion）を活用しています。Maverick と Scout は、200言語にまたがるデータ（アラビア語、スペイン語、ドイツ語、ヒンディー語を含む12言語の特定のファインチューニングをサポート）で、最大40兆トークンにわたって学習されています。

デプロイメントにおいて、Llama 4 Scoutはアクセシビリティを重視して設計されており、オンザフライの4ビットまたは8ビットint4量子化により、サーバーグレードのGPU 1基に収まるようになっています。一方、MaverickはBF16およびFP8形式で提供されています。これらのモデルは、モデルリポジトリで入手可能なカスタムLlama 4 Community License Agreementの下で公開されています。

すべてのオリジナルの Llama チェックポイントは、[meta-llama](https://huggingface.co/meta-llama) 組織の下で確認できます。

> [!TIP]
> Llama 4モデルファミリーには、109Bと402Bのパラメータ数を持つ2つのバリエーションがあります。どちらも非常に大規模であり、一般的なデバイスには収まりません。モデルのメモリ使用量を削減するための例を以下に示します。
>
> ダウンロードをより高速かつ堅牢にするため、`hf_xet` 依存関係を次のようにインストールすることをお勧めします: `pip install transformers[hf_xet]`

以下の例では、[Pipeline](/docs/transformers/main/ja/main_classes/pipelines#transformers.Pipeline)または[AutoModel](/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel)を使用して生成を行う方法を示しています。また、Llama 4のいくつかのバリエーションではコンテキスト長が最大1000万トークンに達するため、非常に長いコンテキストでの生成を有効化するために必要な属性を切り替える方法を示す例も追加しています。

```python

from transformers import pipeline

model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"

messages = [
    {"role": "user", "content": "what is the recipe of mayonnaise?"},
]

pipe = pipeline(
    "text-generation",
    model=model_id,
    device_map="auto",
)

output = pipe(messages, do_sample=False, max_new_tokens=200)
print(output[0]["generated_text"][-1]["content"])
```

```python

from transformers import AutoTokenizer, Llama4ForConditionalGeneration

model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    device_map="auto",
)

messages = [
    {"role": "user", "content": "Who are you?"},
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=100)
outputs = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])
print(outputs[0])
```

```python

from transformers import AutoProcessor, Llama4ForConditionalGeneration

model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"

processor = AutoProcessor.from_pretrained(model_id)
model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    device_map="auto",
)

img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg"
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": img_url},
            {"type": "text", "text": "Describe this image in two sentences."},
        ]
    },
]

inputs = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
).to(model.device)

outputs = model.generate(
    **inputs,
    max_new_tokens=256,
)

response = processor.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])[0]
print(response)
```

```python

from transformers import AutoProcessor, Llama4ForConditionalGeneration

model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"

processor = AutoProcessor.from_pretrained(model_id)
model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    device_map="auto",
)

url1 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg"
url2 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/cat_style_layout.png"
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": url1},
            {"type": "image", "url": url2},
            {"type": "text", "text": "Can you describe how these two images are similar, and how they differ?"},
        ]
    },
]

inputs = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
).to(model.device)

outputs = model.generate(
    **inputs,
    max_new_tokens=256,
)

response = processor.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])[0]
print(response)
```

注意: 以下の例では、`device_map="auto"` と flex-attention の両方が使用されています。この例をテンソル並列モードで実行するには、`torchrun` を使用してください。

今後、テンソル並列なしで`device_map="auto"`およびflex-attentionによる実行を可能にするよう取り組んでまいります。

```python
import time

import torch

from transformers import AutoTokenizer, Llama4ForConditionalGeneration

file = "very_long_context_prompt.txt"
model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"

with open(file, "r") as f:
    very_long_text = "\n".join(f.readlines())

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    device_map="auto",
    attn_implementation="flex_attention",
)

messages = [
    {"role": "user", "content": f"Look at the following texts: [{very_long_text}]\n\n\n\nWhat are the books, and who wrote them? Make me a nice list."},
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)

torch_device_module = getattr(torch, model.device.type, torch.cuda)
torch_device_module.synchronize()
start = time.time()
out = model.generate(
    **inputs,
    prefill_chunk_size=2048*8,
    max_new_tokens=300,
    cache_implementation="hybrid",
)
print(time.time()-start)
print(tokenizer.batch_decode(out[:, inputs["input_ids"].shape[-1]:]))
print(f"{torch_device_module.max_memory_allocated(model.device) / 1024**3:.2f} GiB")
```

## 効率性;llama 4から最大限のパフォーマンスを引き出す方法

### アテンション手法

デフォルトのattention関数を変更すると、計算パフォーマンスとメモリ使用量が大幅に改善される場合があります。インターフェースの詳細については、[Attention Interface](../attention_interface)の概要を参照してください。

リリース時点では、Llama 4 モデルは以下のアテンションメソッドをサポートしています: `eager`、`flex_attention`、`sdpa`。最適な結果を得るには、`flex_attention` の使用を推奨します。アテンションメカニズムの切り替えは、モデルの初期化ステップで行います:

Flex Attentionを設定することで、モデルが処理できる非常に長いコンテキストにおいて、最適な結果が得られます。

> [!TIP] 注意: 以下の例では `device_map="auto"` と flex-attention の両方が使用されています。この例をテンソル並列モードで実行するには、`torchrun` を使用してください。
>
> 今後、テンソル並列なしで`device_map="auto"`およびflex-attentionによる実行を可能にするよう取り組んでまいります。

```python

from transformers import Llama4ForConditionalGeneration

model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    attn_implementation="flex_attention",
    device_map="auto",
)
```

`sdpa` アテンション方式は、一般的に`eager`方式よりも計算効率が高いです。

```python

from transformers import Llama4ForConditionalGeneration

model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    attn_implementation="sdpa",
    device_map="auto",
)
```

`eager` 注意機構メソッドがデフォルトで設定されているため、モデルの読み込み時に特別な対応は不要です。

```python

from transformers import Llama4ForConditionalGeneration

model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    device_map="auto",
)
```

### 量子化

Quantizationは、重みを低精度で表現することで、大規模モデルのメモリ負荷を軽減します。利用可能なQuantizationバックエンドについては、[Quantization](../quantization/overview)の概要を参照してください。リリース時点では、FBGEMMとLLM-Compressorの両方がサポートされており、リリース日以降の数日以内に、さらに多くのQuantization手法がサポートされる予定です。

両方を使用した例を以下に示します。

FBGEMMアプローチを使用して、BF16モデルをFP8で読み込む例を以下に示します。

```python

from transformers import AutoTokenizer, FbgemmFp8Config, Llama4ForConditionalGeneration

model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct"

tokenizer = AutoTokenizer.from_pretrained(model_id)

messages = [
    {"role": "user", "content": "Who are you?"},
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)

model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    device_map="auto",
    quantization_config=FbgemmFp8Config()
)

outputs = model.generate(**inputs.to(model.device), max_new_tokens=100)
outputs = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])
print(outputs[0])
```

LLM-Compressorの手法を使用するには、リリースで提供されている事前量子化済みFP8チェックポイントの利用を推奨します。

```python

from transformers import AutoTokenizer, Llama4ForConditionalGeneration

model_id = "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8"

tokenizer = AutoTokenizer.from_pretrained(model_id)

messages = [
    {"role": "user", "content": "Who are you?"},
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)

model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    tp_plan="auto",
    device_map="auto",
)

outputs = model.generate(**inputs.to(model.device), max_new_tokens=100)
outputs = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:])
print(outputs[0])
```

### オフローディング

CPUオフローディングを有効にすると、GPUのメモリがモデル全体をロードするのに十分でない場合、モデルのコンポーネントの一部がGPUではなくCPUに移動されます。推論時には、異なるコンポーネントがオンザフライでGPUにロード/アンロードされます。これにより、CPUメモリが十分であれば、より小さなマシンでもモデルをロードできるようになります。ただし、通信オーバーヘッドが発生するため、推論速度は低下します。

CPUオフローディングを有効にするには、モデルの読み込み時に`device_map`を`auto`に指定するだけです。

```python

from transformers import Llama4ForConditionalGeneration

model = Llama4ForConditionalGeneration.from_pretrained(
    model_id,
    device_map="auto",
)
```

## Llama4Config[[transformers.Llama4Config]]

#### transformers.Llama4Config[[transformers.Llama4Config]]

```python
transformers.Llama4Config(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, boi_token_index: int = 200080, eoi_token_index: int = 200081, image_token_index: int = 200092, tie_word_embeddings: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/configuration_llama4.py#L208)

**パラメータ:**

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *任意*) : ビジョンバックボーンの config オブジェクトまたは辞書。

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *任意*) : テキストバックボーンの config オブジェクトまたは辞書。

boi_token_index (`int`, *optional*, デフォルトは 200080) : 画像プロンプトをラップするための begin-of-image トークンのインデックスです。

eoi_token_index (`int`、*optional*、デフォルトは 200081) : 画像プロンプトをラップするための画像終了トークンのインデックス。

image_token_index (`int`、*optional*、デフォルトは`200092`) : 入力画像のプレースホルダーとして使用される画像トークンのインデックス。

tie_word_embeddings (`bool`, *任意*, デフォルトは `False`) : モデルの `tied_weights_keys` マッピングに従って重み埋め込みを共有するかどうか。

This is the configuration class to store the configuration of a Llama4ForConditionalGeneration. It is used to instantiate a Llama4 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [meta-llama/Llama-4-Scout-17B-16E](https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E)

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

```python
>>> from transformers import Llama4Model, Llama4Config

>>> # Initializing a Llama4 7B style configuration
>>> configuration = Llama4Config()

>>> # Initializing a model from the Llama4 7B style configuration
>>> model = Llama4Model(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## Llama4TextConfig[[transformers.Llama4TextConfig]]

#### transformers.Llama4TextConfig[[transformers.Llama4TextConfig]]

```python
transformers.Llama4TextConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vocab_size: int = 202048, hidden_size: int = 5120, intermediate_size: int = 8192, intermediate_size_mlp: int = 16384, num_hidden_layers: int = 48, num_attention_heads: int = 40, num_key_value_heads: int = 8, head_dim: int = 128, hidden_act: str = 'silu', max_position_embeddings: int = 131072, initializer_range: float = 0.02, rms_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = None, bos_token_id: int | None = 1, eos_token_id: int | list[int] | None = 2, tie_word_embeddings: bool = False, attention_dropout: float | int = 0.0, num_experts_per_tok: int = 1, num_local_experts: int = 16, moe_layers: list[int] | None = None, interleave_moe_layer_step: int = 1, use_qk_norm: bool = True, output_router_logits: bool = False, router_aux_loss_coef: float = 0.001, router_jitter_noise: float = 0.0, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, no_rope_layers: list[int] | None = None, no_rope_layer_interval: int = 4, attention_chunk_size: int | None = 8192, layer_types: list[str] | None = None, attn_temperature_tuning: bool = True, floor_scale: int = 8192, attn_scale: float = 0.1, attention_bias: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/configuration_llama4.py#L79)

**パラメータ:**

vocab_size (`int`、*任意*、デフォルトは`202048`) : モデルの語彙サイズ。`input_ids`で表現できるトークンの種類数を定義します。

hidden_size (`int`、*任意*、デフォルトは`5120`) : 隠れ表現の次元数。

intermediate_size (`int`、*任意*、デフォルトは`8192`) : MLP 表現の次元数。

intermediate_size_mlp (`int`、*任意*、デフォルトは 16384) : 密結合 MLP レイヤーの中間サイズ。値を大きくすると FFN の容量と計算量が増加します。

num_hidden_layers (`int`、*任意*、デフォルトは `48`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `40`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

num_key_value_heads (`int`, *optional*, デフォルトは `8`) : Grouped Query Attention を実装するために使用する key_value ヘッドの数です。`num_key_value_heads=num_attention_heads` の場合、モデルは Multi Head Attention (MHA) を使用し、`num_key_value_heads=1` の場合は Multi Query Attention (MQA) を使用し、それ以外の場合は GQA が使用されます。マルチヘッドのチェックポイントを GQA のチェックポイントに変換する際は、各グループの key ヘッドと value ヘッドは、そのグループ内の元のすべてのヘッドを平均プーリングして構築する必要があります。詳細については、[この論文](https://huggingface.co/papers/2305.13245)を参照してください。指定されない場合、デフォルトで `num_attention_heads` が使用されます。

head_dim (`int`、*任意*、デフォルトは`128`) : アテンションヘッドの次元です。None の場合、hidden_size // num_attention_heads がデフォルトとして使用されます。

hidden_act (`str`、*任意*、デフォルトは`silu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

max_position_embeddings (`int`、*任意*、デフォルトは `131072`) : このモデルが使用される可能性のある最大シーケンス長です。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

rms_norm_eps (`float`、*任意*、デフォルトは`1e-05`) : rms 正規化レイヤーで使用する epsilon。

use_cache (`bool`、*任意*、デフォルトは `True`) : モデルが最後のキー/バリューアテンションを返すかどうか（すべてのモデルで利用されるわけではありません）。`config.is_decoder=True` の場合、またはモデルがデコーダー専用の生成モデルである場合にのみ関連します。

pad_token_id (`int`, *任意*) : 語彙内でパディングに使用されるトークンID。

bos_token_id (`int`, *任意*, デフォルトは `1`) : 語彙内でストリームの開始に使用されるトークン ID。

eos_token_id (`Union[int, list[int]]`、*任意*、デフォルトは`2`) : 語彙内でストリーム終了に使用されるトークン ID。

tie_word_embeddings (`bool`, *任意*, デフォルトは `False`) : モデルの `tied_weights_keys` マッピングに従って重み埋め込みを共有するかどうか。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

num_experts_per_tok (`int`、*任意*、デフォルトは`1`) : 各トークンをルーティングするエキスパートの数です。これは、トークン選択ルーティングにおけるtop-kの値です。

num_local_experts (`int`、*任意*、デフォルトは`16`) : 各デバイス上のローカルエキスパートの数。`num_experts`は`num_local_experts`で割り切れる必要があります。

moe_layers (`list[int]`、*任意*) : MoE を使用するレイヤーのインデックスのリストです。設定されている場合、`interleave_moe_layer_step` を上書きします。

interleave_moe_layer_step (`int`、*optional*、デフォルトは 1) : `moe_layers` が `None` の場合の MoE レイヤー間の間隔です。値が大きいほど、MoE レイヤーの数は少なくなります。

use_qk_norm (`bool`、*任意*、デフォルトは`True`) : RoPE レイヤーでクエリ/キーを L2 正規化するかどうか。有効にするとアテンションを安定させることができます。

output_router_logits (`bool`, *任意*, デフォルトは `False`) : モデルがルーターのロジスティック値を返すかどうかを指定します。これを有効にすると、モデルはロードバランシングロスやルーターのzロスを含む補助ロスの出力も可能になります。

router_aux_loss_coef (`float`、*任意*、デフォルトは `0.001`) : 補助的なロードバランシング損失の係数です。MoE モデルにおける不均一なエキスパートルーティングをペナルティするために使用されます。

router_jitter_noise (`float`、*任意*、デフォルトは`0.0`) : 学習時にルーターのロジットに追加するノイズの量です。より良い負荷分散のために使用します。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *optional*) : RoPE 埋め込みの設定パラメータを含む辞書です。この辞書には `rope_theta` の値が含まれていなければならず、より長い `max_position_embeddings` で RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。

no_rope_layers (`list[int]`、*任意*) : モデルの層数以上の長さを持つリスト。インデックス位置の値が`1`の場合、対応する層でRoPEが使用され、`0`の場合はNoPE層であることを示します。

no_rope_layer_interval (`int`、*任意*、デフォルトは 4) : `no_rope_layers` が `None` の場合、`no_rope_layer_interval` 層ごとに NoPE 層を使用して作成されます。

attention_chunk_size (`int`、*optional*、デフォルトは 8192) : 注意機構の計算におけるチャンクサイズ。値を小さくすると、より局所的な注意機構が強制され、メモリ使用量が低下します。

layer_types (`list[str]`、*任意*) : 各レイヤーのインデックスとそのレイヤータイプを明示的にマッピングするリストです。指定しない場合、config の値に基づいて自動的に生成されます。

attn_temperature_tuning (`bool`、*任意*、デフォルトは`True`) : シーケンス長に基づいて、各クエリトークンのアテンション温度を動的にスケーリングするかどうか。安定した出力結果を維持するために、長いシーケンス（例：>32k トークン）での使用が推奨されます。

floor_scale (`int`, *任意*, デフォルトは 8192) : 注意温度のチューニングにおけるベーススケール（トークン数）。値を大きくすると、長い位置でのスケーリングが遅延します。

attn_scale (`float`、*任意*、デフォルト値は 0.1) : 注意温度チューニングの強度。値が大きいほど、長い位置でのスケーリングが増加します。

attention_bias (`bool`、*任意*、デフォルトは`False`) : セルフアテンションにおけるクエリ、キー、バリュー、出力の投影層でバイアスを使用するかどうか。

This is the configuration class to store the configuration of a Llama4ForConditionalGeneration. It is used to instantiate a Llama4 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [meta-llama/Llama-4-Scout-17B-16E](https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E)

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

## Llama4VisionConfig[[transformers.Llama4VisionConfig]]

#### transformers.Llama4VisionConfig[[transformers.Llama4VisionConfig]]

```python
transformers.Llama4VisionConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 768, hidden_act: str = 'gelu', num_hidden_layers: int = 34, num_attention_heads: int = 16, num_channels: int = 3, intermediate_size: int = 5632, vision_output_dim: int = 7680, image_size: int | list[int] | tuple[int, int] = 448, patch_size: int | list[int] | tuple[int, int] = 14, norm_eps: float = 1e-05, vision_feature_select_strategy: str = 'default', initializer_range: float = 0.02, pixel_shuffle_ratio: float = 0.5, projector_input_dim: int = 4096, projector_output_dim: int = 4096, multi_modal_projector_bias: bool = False, projector_dropout: float | int = 0.0, attention_dropout: float | int = 0.0, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/configuration_llama4.py#L29)

**パラメータ:**

hidden_size (`int`、*任意*、デフォルトは`768`) : 隠れ表現の次元数。

hidden_act (`str`、*任意*、デフォルトは`gelu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

num_hidden_layers (`int`、*任意*、デフォルトは `34`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは`16`) : Transformerデコーダーの各アテンション層におけるアテンションヘッドの数。

num_channels (`int`、*任意*、デフォルトは`3`) : 入力チャネル数。

intermediate_size (`int`、*任意*、デフォルトは`5632`) : MLP 表現の次元数。

vision_output_dim (`int`、*任意*、デフォルト値は 7680) : ビジョンモデルの出力の次元数。中間層を含む Transformer エンコーダーの出力と、グローバル Transformer エンコーダーの出力を含みます。

image_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`448`) : 各画像のサイズ（解像度）。

patch_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`14`) : 各パッチのサイズ（解像度）。

norm_eps (`float`、*任意*、デフォルトは`1e-05`) : Layer Normalization 層で使用する epsilon。

vision_feature_select_strategy (`str`、*任意*、デフォルトは`default`) : ビジョンバックボーンからビジョン特徴を選択するために使用される特徴選択戦略。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

pixel_shuffle_ratio (`float`, *optional*, デフォルトは 0.5) : パッチトークンをダウンサンプリングするためのピクセルシャッフル比率。値が小さいほど、トークン数が少なくなります（より強いダウンサンプリング）。

projector_input_dim (`int`、*任意*、デフォルトは 4096) : pixel shuffle 前の vision adapter MLP の幅。値を大きくすると容量と計算量が増加します。

projector_output_dim (`int`、*optional*、デフォルトは 4096) : ビジョンアダプターの出力幅です。値を大きくすると、より高次元の画像特徴が得られます。

multi_modal_projector_bias (`bool`、*任意*、デフォルトは`False`) : マルチモーダルプロジェクターでバイアスを使用するかどうか。

projector_dropout (`float`、*optional*、デフォルト値は 0.0) : ビジョンアダプタの MLP 内の Dropout レート。値を高くすると、より強い正則化が加わります。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *optional*) : RoPE 埋め込みの設定パラメータを含む辞書です。この辞書には `rope_theta` の値が含まれていなければならず、より長い `max_position_embeddings` で RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。

This is the configuration class to store the configuration of a Llama4ForConditionalGeneration. It is used to instantiate a Llama4 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [meta-llama/Llama-4-Scout-17B-16E](https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E)

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

## Llama4Processor[[transformers.Llama4Processor]]

#### transformers.Llama4Processor[[transformers.Llama4Processor]]

```python
transformers.Llama4Processor(image_processor = None, tokenizer = None, patch_size: int = 14, pixel_shuffle_ratio: float = 0.5, fake_image_token = '<|image|>', image_token = '<|image|>', start_of_image_token = '<|image_start|>', end_of_image_token = '<|image_end|>', patch_token = '<|patch|>', tile_x_separator_token = '<|tile_x_separator|>', tile_y_separator_token = '<|tile_y_separator|>', chat_template = '{{- bos_token }}\n{%- if custom_tools is defined %}\n    {%- set tools = custom_tools %}\n{%- endif %}\n{%- if not tools_in_user_message is defined %}\n    {%- set tools_in_user_message = true %}\n{%- endif %}\n{%- if not date_string is defined %}\n    {%- if strftime_now is defined %}\n        {%- set date_string = strftime_now("%d %b %Y") %}\n    {%- else %}\n        {%- set date_string = "26 Jul 2024" %}\n    {%- endif %}\n{%- endif %}\n{%- if not tools is defined %}\n    {%- set tools = none %}\n{%- endif %}\n\n{#- This block extracts the system message, so we can slot it into the right place. #}\n{%- if messages[0][\'role\'] == \'system\' %}    \n    {%- if messages[0][\'content\'] is string %}\n        {%- set system_message = messages[0][\'content\']|trim %}\n    {%- else %}\n        {#- FIXME: The processor requires an array, always. #}\n        {%- set system_message = messages[0][\'content\'][0][\'text\']|trim %}\n    {%- endif %}\n    {%- set messages = messages[1:] %}\n    {%- set user_supplied_system_message = true %}\n{%- else %}\n    {%- set system_message = "" %}\n    {%- set user_supplied_system_message = false %}\n{%- endif %}\n\n{#- System message if the user supplied one #}\n{%- if user_supplied_system_message %}\n    {{- "<|header_start|>system<|header_end|>\n\n" }}\n    {%- if tools is not none %}\n        {{- "Environment: ipython\n" }}\n    {%- endif %}\n    {%- if tools is not none and not tools_in_user_message %}\n        {{- "You have access to the following functions. To call a function, please respond with JSON for a function call." }}\n        {{- \'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.\' }}\n        {{- "Do not use variables.\n\n" }}\n        {%- for t in tools %}\n            {{- t | tojson(indent=4) }}\n            {{- "\n\n" }}\n        {%- endfor %}\n    {%- endif %}\n    {{- system_message }}\n    {{- "<|eot|>" }}\n{%- endif %}\n\n{#- Custom tools are passed in a user message with some extra guidance #}\n{%- if tools_in_user_message and not tools is none %}\n    {#- Extract the first user message so we can plug it in here #}\n    {%- if messages | length != 0 %}\n        {%- set first_user_message = messages[0][\'content\']|trim %}\n        {%- set messages = messages[1:] %}\n    {%- else %}\n        {{- raise_exception("Cannot put tools in the first user message when there\'s no first user message!") }}\n{%- endif %}\n    {{- \'<|header_start|>user<|header_end|>\n\n\' -}}\n    {{- "Given the following functions, please respond with a JSON for a function call " }}\n    {{- "with its proper arguments that best answers the given prompt.\n\n" }}\n    {{- \'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.\' }}\n    {{- "Do not use variables.\n\n" }}\n    {%- for t in tools %}\n        {{- t | tojson(indent=4) }}\n        {{- "\n\n" }}\n    {%- endfor %}\n    {{- first_user_message + "<|eot|>"}}\n{%- endif %}\n\n{%- for message in messages %}\n    {%- if not (message.role == \'ipython\' or message.role == \'tool\' or \'tool_calls\' in message) %}\n    {{- \'<|header_start|>\' + message[\'role\'] + \'<|header_end|>\n\n\' }}\n        {%- if message[\'content\'] is string %}\n            {{- message[\'content\'] }}\n        {%- else %}\n            {%- for content in message[\'content\'] %}\n                {%- if content[\'type\'] == \'image\' %}\n                    {{- \'<|image|>\' }}\n                {%- elif content[\'type\'] == \'text\' %}\n                    {{- content[\'text\'] }}\n                {%- endif %}\n            {%- endfor %}\n        {%- endif %}\n        {{- "<|eot|>" }}\n    {%- elif \'tool_calls\' in message and message.tool_calls|length > 0 %}\n       {{- \'<|header_start|>assistant<|header_end|>\n\n\' -}}\n       {{- \'<|python_start|>\' }}\n        {%- if message[\'content\'] is string %}\n            {{- message[\'content\'] }}\n        {%- else %}\n            {%- for content in message[\'content\'] %}\n                {%- if content[\'type\'] == \'image\' %}\n                    {{- \'<|image|>\' }}\n                {%- elif content[\'type\'] == \'text\' %}\n                    {{- content[\'text\'] }}\n                {%- endif %}\n            {%- endfor %}\n        {%- endif %}\n       {{- \'<|python_end|>\' }}\n        {%- for tool_call in message.tool_calls %}\n           {{- \'{"name": "\' + tool_call.function.name + \'", \' }}\n           {{- \'"parameters": \' }}\n           {{- tool_call.function.arguments | tojson }}\n           {{- "}" }}\n        {%- endfor %}\n       {{- "<|eot|>" }}\n    {%- elif message.role == "tool" or message.role == "ipython" %}\n        {{- "<|header_start|>ipython<|header_end|>\n\n" }}\n        {%- if message.content is mapping or message.content is iterable %}\n            {{- message.content | tojson }}\n        {%- else %}\n            {{- message.content }}\n        {%- endif %}\n        {{- "<|eot|>" }}\n    {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n    {{- \'<|header_start|>assistant<|header_end|>\n\n\' }}\n{%- endif %}\n', **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/processing_llama4.py#L34)

**パラメータ:**

image_processor (`Llama4ImageProcessor`) : 画像プロセッサは必須の入力です。

tokenizer (`tokenizer_class`) : トークナイザーは必須の入力です。

patch_size (`int`、*optional*、デフォルトは 28) : トークン化における画像パッチのサイズです。

pixel_shuffle_ratio (`float`、*任意*、デフォルトは`0.5`) : 画像処理時にピクセルシャッフルに使用される比率です。これは、画像パッチに適用されるダウンサンプリング係数を制御します。実際のダウンサンプリング比率は`1 / (pixel_shuffle_ratio^2)`として計算されます。

fake_image_token (`str`、*任意*、デフォルトは`"<|image|>"`) : テキスト内で実際の画像トークンに置き換えられるプレースホルダトークンです。このトークンは、テキストシーケンス内のどこに画像を挿入すべきかを示すマーカーとして機能します。

image_token (`str`、*任意*、デフォルトは `"<|image|>"`) : テキスト内で画像を表すために使用されるトークン。

start_of_image_token (`str`、*任意*、デフォルトは`"<|image_start|>"`) : テキスト内の画像シーケンスの開始を示す特殊トークンです。このトークンは画像トークンシーケンスの先頭に付加され、画像の境界を区切ります。

end_of_image_token (`str`、*任意*、デフォルトは`"<|image_end|>"`) : テキスト内の画像シーケンスの終了を示す特殊トークンです。このトークンは画像トークンシーケンスの末尾に追加され、画像の境界を区切ります。

patch_token (`str`、*任意*、デフォルトは `"<|patch|>"`) : 個々の画像パッチを表すために使用されるトークンです。画像全体を表すには複数のパッチトークンが使用され、その数は画像サイズとパッチ設定によって決まります。

tile_x_separator_token (`str`、*任意*、デフォルトは `"<|tile_x_separator|>"`) : 画像内のタイル（パッチ）を水平方向に区切るために使用されるトークン。画像が複数のタイルに分割される場合、同じ行内のパッチ間にこのトークンが挿入されます。

tile_y_separator_token (`str`、*任意*、デフォルトは`"<|tile_y_separator|>"`) : 画像内でタイル（パッチ）を垂直方向に区切るために使用されるトークン。画像が複数のタイルに分割される場合、パッチの行の間にこのトークンが挿入されます。

chat_template (`str`、デフォルトは `{{- bos_token }}

{%- if custom_tools is defined %} : {%- set tools = custom_tools %}

{%- endif %} --

{%- if not tools_in_user_message is defined %} : {%- set tools_in_user_message = true %}

{%- endif %} --

{%- if not date_string is defined %} : {%- if strftime_now is defined %} {%- set date_string = strftime_now("%d %b %Y") %} {%- else %} {%- set date_string = "26 Jul 2024" %} {%- endif %}

{%- endif %} --

{%- if not tools is defined %} : {%- set tools = none %}

{%- endif %} :

{#- このブロックはシステムメッセージを抽出するため、適切な位置に挿入できるようにします。 #} --

{%- if messages[0]['role'] == 'system' %} : {%- if messages[0]['content'] is string %} {%- set system_message = messages[0]['content']|trim %} {%- else %} {#- FIXME: The processor requires an array, always. #} {%- set system_message = messages[0]['content'][0]['text']|trim %} {%- endif %} {%- set messages = messages[1:] %} {%- set user_supplied_system_message = true %}

{%- else %} : {%- set system_message = "" %} {%- set user_supplied_system_message = false %}

{%- endif %} :

{#- ユーザーがシステムメッセージを指定した場合のシステムメッセージ #} --

{%- if user_supplied_system_message %} : {{- "<|header_start|>system<|header_end|>

" }} : {%- if tools is not none %} {{- "Environment: ipython

" }} : {%- endif %} {%- if tools is not none and not tools_in_user_message %} {{- "以下の関数にアクセスできます。関数を呼び出す場合は、関数呼び出しの JSON で応答してください。" }} {{- '{"name": 関数名, "parameters": 引数名とその値の辞書} という形式で応答してください。' }} {{- "変数を使用しないでください。

}} : {%- for t in tools %} {{- t | tojson(indent=4) }} {{- "

" }} : {%- endfor %} {%- endif %} {{- system_message }} {{- "<|eot|>" }}

{%- endif %} :

{#- カスタムツールは、追加のガイダンスとともにユーザーメッセージに渡されます #} --

{%- if tools_in_user_message and not tools is none %} : {#- Extract the first user message so we can plug it in here #} {%- if messages | length != 0 %} {%- set first_user_message = messages[0]['content']|trim %} {%- set messages = messages[1:] %} {%- else %} {{- raise_exception("Cannot put tools in the first user message when there's no first user message!") }}

{%- endif %} : {{- '<|header_start|>user<|header_end|>

' -}} : {{- "以下の関数が与えられた場合、与えられたプロンプトに最も適切に答える関数呼び出しのJSONを、適切な引数とともに返してください。

" }} : {{- '{"name": 関数名, "parameters": 引数名とその値の辞書} という形式で応答してください。' }} {{- "変数を使用しないでください。

}} : {%- for t in tools %} {{- t | tojson(indent=4) }} {{- "

" }} : {%- endfor %} {{- first_user_message + "<|eot|>"}}

{%- endif %} :

{%- for message in messages %} : {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %} {{- '<|header_start|>' + message['role'] + '<|header_end|>

' }} : {%- if message['content'] is string %} {{- message['content'] }} {%- else %} {%- for content in message['content'] %} {%- if content['type'] == 'image' %} {{- '<|image|>' }} {%- elif content['type'] == 'text' %} {{- content['text'] }} {%- endif %} {%- endfor %} {%- endif %} {{- "<|eot|>" }} {%- elif 'tool_calls' in message and message.tool_calls|length > 0 %} {{- '<|header_start|>assistant<|header_end|>

' -}} : {{- '<|python_start|>' }} {%- if message['content'] is string %} {{- message['content'] }} {%- else %} {%- for content in message['content'] %} {%- if content['type'] == 'image' %} {{- '<|image|>' }} {%- elif content['type'] == 'text' %} {{- content['text'] }} {%- endif %} {%- endfor %} {%- endif %} {{- '<|python_end|>' }} {%- for tool_call in message.tool_calls %} {{- '{"name": "' + tool_call.function.name + '", ' }} {{- '"parameters": ' }} {{- tool_call.function.arguments | tojson }} {{- "}" }} {%- endfor %} {{- "<|eot|>" }} {%- elif message.role == "tool" or message.role == "ipython" %} {{- "<|header_start|>ipython<|header_end|>

" }} : {%- if message.content is mapping or message.content is iterable %} {{- message.content | tojson }} {%- else %} {{- message.content }} {%- endif %} {{- "<|eot|>" }} {%- endif %}

{%- endfor %} --

{%- if add_generation_prompt %} : {{- '<|header_start|>assistant<|header_end|>

' }} --

{%- endif %} --

`) : チャット内のメッセージのリストをトークン化可能な文字列に変換するための Jinja テンプレート。

画像プロセッサとトークナイザーを単一のプロセッサにラップするLlama4Processorを構築します。

[Llama4Processor](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4Processor) は、[Llama4ImageProcessor](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4ImageProcessor) と `tokenizer_class` のすべての機能を提供します。詳細については、[~Llama4ImageProcessor](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4ImageProcessor) および `~tokenizer_class` を参照してください。

#### __call__[[transformers.Llama4Processor.__call__]]

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, text: str | list[str] | list[list[str]] | None = None, videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None, audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L657)

**パラメータ:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`, *任意*) : 前処理を行う画像。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチの画像を想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、`do_rescale=False` を設定してください。

text (`Union[str, list[str], list[list[str]]]`、*任意*) : エンコード対象のシーケンスまたはシーケンスのバッチです。各シーケンスは文字列、または文字列のリスト（プレトークナイズ済み文字列）であることができます。プレトークナイズ済み入力を渡す場合は、バッチ入力との曖昧さを避けるために `is_split_into_words=True` を設定してください。

videos (`Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]`, *任意*) : 前処理対象の動画。ピクセル値が 0 から 255 の範囲にある単一の動画またはバッチを想定しています。ピクセル値が 0 から 1 の範囲にある動画を渡す場合は、`do_rescale=False` を設定してください。

audio (`Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]]`, *任意*) : 準備対象のオーディオまたはオーディオのバッチです。各オーディオは NumPy 配列または PyTorch テンソルであることができます。NumPy 配列/PyTorch テンソルの場合、各オーディオの形状は (C, T) である必要があります。ここで C はチャネル数、T はオーディオのサンプル長を表します。

return_tensors (`str` または [TensorType](/docs/transformers/main/ja/internal/file_utils#transformers.TensorType)、*optional*) : 設定されている場合、特定のフレームワークのテンソルを返します。受け入れ可能な値は以下の通りです:  - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: NumPy の `np.ndarray` オブジェクトを返します。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/main/ja/main_classes/processors#transformers.ProcessingKwargs), *optional*) : 各モダリティ（テキスト、画像、動画、音声）の追加処理オプション。モデル固有のパラメータは上記にリストされています。サポートされている引数の完全なリストについては、TypedDict クラスを参照してください。

## Llama4ImageProcessor[[transformers.Llama4ImageProcessor]]

#### transformers.Llama4ImageProcessor[[transformers.Llama4ImageProcessor]]

```python
transformers.Llama4ImageProcessor(**kwargs: *<class 'transformers.models.llama4.image_processing_llama4.Llama4ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/image_processing_llama4.py#L296)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は`{'height' : 336, 'width': 336}`): モデルへの最大入力サイズを指定します。

default_to_square (`bool`, *kwargs*, *任意*、デフォルトは `True`) : size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.5, 0.5, 0.5]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

max_patches (`int`, *kwargs*, *optional*, デフォルトは 16) : 画像から抽出するパッチの最大数。`preprocess` メソッドの `max_patches` パラメータによって上書きできます。

resize_to_max_canvas (`bool`, *kwargs*, *optional*, デフォルトは False) : 画像を最大キャンバスサイズにリサイズするかどうかを指定します。True の場合、歪みなく最大限にリサイズできるキャンバスを選択します。False の場合、リサイズしないことも含め、ダウンサンプリングを最小限に抑えますが、画像がパッチサイズより小さい場合を除き、アップサンプリングは行いません。

Llama4ImageProcessor の画像プロセッサを構築します。

#### preprocess[[transformers.Llama4ImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], **kwargs: *<class 'transformers.models.llama4.image_processing_llama4.Llama4ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/image_processing_llama4.py#L312)

**パラメータ:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 前処理対象の画像。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチの画像を想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、`do_rescale=False` を設定してください。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

max_patches (`int`, *kwargs*, *optional*, デフォルトは 16) : 画像から抽出するパッチの最大数。`preprocess` メソッドの `max_patches` パラメータによって上書きできます。

resize_to_max_canvas (`bool`, *kwargs*, *optional*, デフォルトは False) : 画像を最大キャンバスサイズにリサイズするかどうかを指定します。True の場合、歪みなく最大限にリサイズできるキャンバスを選択します。False の場合、リサイズしないことも含め、ダウンサンプリングを最小限に抑えますが、画像がパッチサイズより小さい場合を除き、アップサンプリングは行いません。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

## Llama4ForConditionalGeneration[[transformers.Llama4ForConditionalGeneration]]

#### transformers.Llama4ForConditionalGeneration[[transformers.Llama4ForConditionalGeneration]]

```python
transformers.Llama4ForConditionalGeneration(config: Llama4Config)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/modeling_llama4.py#L1149)

#### forward[[transformers.Llama4ForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.FloatTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.FloatTensor] = None, vision_feature_select_strategy: str | None = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/modeling_llama4.py#L1214)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

pixel_values (`torch.FloatTensor`、shape `(batch_size, num_channels, image_size, image_size)`、*任意*) : 入力画像に対応するテンソルです。ピクセル値は [Llama4ImageProcessor](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4ImageProcessor) を使用して取得できます。詳細については [Llama4ImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（[Llama4Processor](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4Processor) は画像の処理に [Llama4ImageProcessor](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4ImageProcessor) を使用します）。

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

position_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックスです。`[0, config.n_positions - 1]` の範囲から選択されます。 [位置 ID とは何か？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`, *任意*) : 逐次デコードを高速化するために使用できる、事前計算された hidden-states（self-attention ブロックおよび cross-attention ブロック内の key と value）です。通常、`use_cache=True` または `config.use_cache=True` の場合、モデルがデコードの以前の段階で返した `past_key_values` で構成されます。入力として許可されるのは [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/main/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

inputs_embeds (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、`input_ids` のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。

vision_feature_select_strategy (`str`, *任意*) : ビジョンバックボーンからビジョン特徴を選択するために使用される特徴選択戦略。`"default"` または `"full"` のいずれかです。

labels (`torch.LongTensor`、形状 `(batch_size, sequence_length)`、*任意*) : マスク言語モデリング損失を計算するためのラベル。インデックスは `[0, ..., config.vocab_size]` の範囲内であるか、-100 である必要があります（`input_ids` のドキュメント文字列を参照）。インデックスが `-100` に設定されたトークンは無視（マスク）され、損失は `[0, ..., config.vocab_size]` の範囲内のラベルを持つトークンに対してのみ計算されます。

use_cache (`bool`, *任意*) : `True`に設定すると、`past_key_values`のキーバリュー状態が返され、デコーディングの高速化に利用できます（`past_key_values`を参照）。

output_attentions (`bool`, *任意*) : すべてのアテンション層のアテンションテンソルを返すかどうか。詳細は、返されるテンソルの `attentions` を参照してください。

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

logits_to_keep (`Union[int, torch.Tensor]`、*任意*、デフォルトは `0`) : `int` の場合、最後の `logits_to_keep` トークンについて logits を計算します。`0` の場合、すべての `input_ids` について logits を計算します（特殊ケース）。生成には最後のトークンの logits だけで十分であり、そのトークンのみについて計算することでメモリを節約できます。これは、長いシーケンスや大規模な語彙サイズの場合に特に顕著な効果があります。`torch.Tensor` の場合、シーケンス長次元で保持するインデックスに対応する 1 次元である必要があります。これは、パックされたテンソル形式（バッチとシーケンス長を単一の次元にまとめる形式）を使用する場合に有用です。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *任意*) : キーがサポートされているモダリティ、値がそのモダリティのエンコード済み出力である辞書。各エンコード済み出力は、(`pooler_output`、*任意*: `last_hidden_states`、*任意*: `hidden_states`、*任意*: `attentions`) という形式のタプルで、`pooler_output` の形状は `(batch_size, sequence_length, hidden_size)`、*任意*) であり、エンコーダーのマルチモーダル特徴量をテキスト埋め込みにマージしたシーケンスです。

**戻り値:** `Llama4CausalLMOutputWithPast` または `tuple(torch.FloatTensor)`

`Llama4CausalLMOutputWithPast`、または `torch.FloatTensor` のタプル（`return_dict=False` が渡された場合、または `config.return_dict=False` の場合）。設定（[Llama4Config](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4Config)）や入力に応じて、さまざまな要素で構成されます。

[Llama4ForConditionalGeneration](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4ForConditionalGeneration)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 言語モデリングの損失(次のトークンの予測用)。
- **logits** (`torch.FloatTensor`、shape `(batch_size, sequence_length, config.vocab_size)`) -- 言語モデリングヘッドの予測スコア（SoftMax 適用前の各語彙トークンのスコア）。
- **past_key_values** (`Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。

  逐次デコーディングを高速化するために使用できる（`past_key_values` 入力参照）、事前計算済みの隠れ状態（自己注意ブロックのキーとバリュー）が含まれます。
- **hidden_states** (`tuple[torch.FloatTensor]`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（モデルに埋め込み層がある場合はその出力用 + 各層の出力用）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple[torch.FloatTensor]`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **image_hidden_states** (`torch.FloatTensor`、*任意*) -- サイズが (batch_size, num_images, sequence_length, hidden_size) の `torch.FloatTensor`。ビジョンエンコーダーによって生成され、最後の隠れ状態を投影した後のモデルの image_hidden_states です。
- **router_logits** (`tuple(torch.FloatTensor)`、*optional*、`output_router_logits=True` が渡された場合に返されます) -- 各 MoE レイヤーに対応する `torch.FloatTensor` のタプルで、形状は `(batch_size * sequence_length, num_experts)` です。

例:

```python
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, LlavaForConditionalGeneration

>>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")

>>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> inputs = processor(images=image, text=prompt, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(**inputs, max_new_tokens=15)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"USER:  \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
```

#### get_image_features[[transformers.Llama4ForConditionalGeneration.get_image_features]]

```python
get_image_features(pixel_values: FloatTensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/modeling_llama4.py#L1181)

**パラメータ:**

pixel_values (`torch.FloatTensor`、shape `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は [Llama4ImageProcessor](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4ImageProcessor) を使用して取得できます。詳細は [Llama4ImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（[Llama4Processor](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4Processor) は画像の処理に [Llama4ImageProcessor](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4ImageProcessor) を使用します）。

**戻り値:** [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) または `tuple(torch.FloatTensor)`

[BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling)、または`torch.FloatTensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[Llama4Config](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4Config)）や入力に応じて、さまざまな要素で構成されます。

ビジョンタワーから画像の最後の隠れ状態を取得し、al 投影を適用します。

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.FloatTensor`、shape `(batch_size, hidden_size)`) -- 補助事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン（分類トークン）の最終層の隠れ状態です。例えば、BERT 系のモデルでは、線形層と tanh 活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次文予測（分類）目的から学習されます。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）で、形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, Llama4ForConditionalGeneration

>>> model = Llama4ForConditionalGeneration.from_pretrained("meta-llama/Llama-4-Scout-17B-16E")
>>> processor = AutoProcessor.from_pretrained("meta-llama/Llama-4-Scout-17B-16E")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
```

## Llama4ForCausalLM[[transformers.Llama4ForCausalLM]]

#### transformers.Llama4ForCausalLM[[transformers.Llama4ForCausalLM]]

```python
transformers.Llama4ForCausalLM(config: Llama4TextConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/modeling_llama4.py#L568)

#### forward[[transformers.Llama4ForCausalLM.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.FloatTensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/modeling_llama4.py#L585)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

position_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックスです。`[0, config.n_positions - 1]` の範囲から選択されます。 [位置 ID とは何か？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`, *任意*) : 逐次デコードを高速化するために使用できる、事前計算された hidden-states（self-attention ブロックおよび cross-attention ブロック内の key と value）です。通常、`use_cache=True` または `config.use_cache=True` の場合、モデルがデコードの以前の段階で返した `past_key_values` で構成されます。入力として許可されるのは [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/main/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

inputs_embeds (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、`input_ids` のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。

labels (`torch.LongTensor`、形状 `(batch_size, sequence_length)`、*任意*) : マスク言語モデリング損失を計算するためのラベル。インデックスは `[0, ..., config.vocab_size]` の範囲内であるか、-100 である必要があります（`input_ids` のドキュメント文字列を参照）。インデックスが `-100` に設定されたトークンは無視（マスク）され、損失は `[0, ..., config.vocab_size]` の範囲内のラベルを持つトークンに対してのみ計算されます。

use_cache (`bool`, *任意*) : `True`に設定すると、`past_key_values`のキーバリュー状態が返され、デコーディングの高速化に利用できます（`past_key_values`を参照）。

logits_to_keep (`Union[int, torch.Tensor]`、*任意*、デフォルトは `0`) : `int` の場合、最後の `logits_to_keep` トークンについて logits を計算します。`0` の場合、すべての `input_ids` について logits を計算します（特殊ケース）。生成には最後のトークンの logits だけで十分であり、そのトークンのみについて計算することでメモリを節約できます。これは、長いシーケンスや大規模な語彙サイズの場合に特に顕著な効果があります。`torch.Tensor` の場合、シーケンス長次元で保持するインデックスに対応する 1 次元である必要があります。これは、パックされたテンソル形式（バッチとシーケンス長を単一の次元にまとめる形式）を使用する場合に有用です。

**戻り値:** `MoeCausalLMOutputWithPast` または `tuple(torch.FloatTensor)`

`MoeCausalLMOutputWithPast`、または`torch.FloatTensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[Llama4Config](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4Config)）や入力に応じて、さまざまな要素で構成されます。

[Llama4ForCausalLM](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4ForCausalLM)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **loss** (`torch.FloatTensor`、shape `(1,)`、*optional*、`labels` が指定された場合に返されます) -- 言語モデリングの損失(次のトークンの予測用)。
- **logits** (`torch.FloatTensor`、shape `(batch_size, sequence_length, config.vocab_size)`) -- 言語モデリングヘッドの予測スコア（SoftMax 適用前の各語彙トークンのスコア）。
- **aux_loss** (`torch.FloatTensor`、*optional*、`output_router_logits=True` が渡された場合、または `config.output_router_logits=True` の場合、かつモデルがロードバランシング損失でルーターを学習する場合に返されます) -- スパースモジュール用のロードバランシング補助損失。ルーターバイアスでエキスパートをバランスさせるモデル（DeepSeek-V3 とそこから派生したアーキテクチャ）は、`router_logits` を返しながらも、ここでは `None` を返します。
- **router_logits** (`tuple(torch.FloatTensor)`、*optional*、`output_router_logits=True` が渡された場合または `config.output_router_logits=True` の場合に返されます) -- `torch.FloatTensor` のタプル（スパース層ごとに1つ）、形状は `(batch_size * sequence_length, num_experts)`。

  MoE ルーターによって計算される生のルーター logits です。ロードバランシング損失の計算や、トークンがどのようにエキスパートにディスパッチされるかの確認に使用できます。
- **past_key_values** (`Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。

  逐次デコーディングを高速化するために使用できる（`past_key_values` 入力参照）、事前計算済みの隠れ状態（自己注意ブロックのキーとバリュー）が含まれます。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）で、形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

```python
>>> from transformers import AutoTokenizer, Llama4ForCausalLM

>>> model = Llama4ForCausalLM.from_pretrained("meta-llama4/Llama4-2-7b-hf")
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama4/Llama4-2-7b-hf")

>>> prompt = "Hey, are you conscious? Can you talk to me?"
>>> inputs = tokenizer(prompt, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
```

## Llama4TextModel[[transformers.Llama4TextModel]]

#### transformers.Llama4TextModel[[transformers.Llama4TextModel]]

```python
transformers.Llama4TextModel(config: Llama4TextConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/modeling_llama4.py#L475)

**パラメータ:**

config ([Llama4TextConfig](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4TextConfig)) : モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

裸の Llama4 Text Modelは、特定のヘッドを上に載せずに生の hidden-states を出力します。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.Llama4TextModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.FloatTensor] = None, use_cache: bool | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/modeling_llama4.py#L502)

**パラメータ:**

input_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスは [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer) を使用して取得できます。詳細については、[PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) および [PreTrainedTokenizer.__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) を参照してください。 [入力IDとは何ですか？](../glossary#input-ids)

attention_mask (`torch.Tensor`、shape `(batch_size, sequence_length)`、*任意*) : padding トークンのインデックスに対する attention を回避するためのマスクです。マスクの値は `[0, 1]` から選択されます:  - **マスクされない**トークンは 1、- **マスクされる**トークンは 0。  [attention マスクとは?](../glossary#attention-mask)

position_ids (`torch.LongTensor`、shape `(batch_size, sequence_length)`、*任意*) : 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックスです。`[0, config.n_positions - 1]` の範囲から選択されます。 [位置 ID とは何か？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`, *任意*) : 逐次デコードを高速化するために使用できる、事前計算された hidden-states（self-attention ブロックおよび cross-attention ブロック内の key と value）です。通常、`use_cache=True` または `config.use_cache=True` の場合、モデルがデコードの以前の段階で返した `past_key_values` で構成されます。入力として許可されるのは [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) インスタンスのみです。[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。`past_key_values` が渡されない場合、デフォルトで [DynamicCache](/docs/transformers/main/ja/internal/generation_utils#transformers.DynamicCache) が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。`past_key_values` を使用する場合は、すべての `input_ids`（形状 `(batch_size, sequence_length)`）の代わりに、このモデルに過去の key value 状態が与えられていない未処理の `input_ids`（形状 `(batch_size, unprocessed_length)`）のみを入力する必要があります。

inputs_embeds (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`、*任意*) : `input_ids` を渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、`input_ids` のインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。

use_cache (`bool`, *任意*) : `True`に設定すると、`past_key_values`のキーバリュー状態が返され、デコーディングの高速化に利用できます（`past_key_values`を参照）。

**戻り値:** `MoeModelOutputWithPast` または `tuple(torch.FloatTensor)`

`MoeModelOutputWithPast`、または`torch.FloatTensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[Llama4Config](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4Config)）や入力に応じて、さまざまな要素で構成されます。

[Llama4TextModel](/docs/transformers/main/ja/model_doc/llama4#transformers.Llama4TextModel)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **past_key_values** (`Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- [Cache](/docs/transformers/main/ja/internal/generation_utils#transformers.Cache) のインスタンスです。詳細については、[kv cache ガイド](https://huggingface.co/docs/transformers/en/kv_cache)を参照してください。

  自己アテンションブロック（および `config.is_encoder_decoder=True` の場合、クロスカレンションブロック）の事前計算済みヒドゥンステート（キーとバリュー）を保持します。これらは逐次デコーディングを高速化するために使用できます（`past_key_values` 入力参照）。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）で、形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **router_logits** (`tuple(torch.FloatTensor)`、*optional*、`output_router_probs=True` と `config.add_router_probs=True` が渡された場合、または `config.output_router_probs=True` の場合に返されます) -- `torch.FloatTensor` のタプル（レイヤーごとに1つ）、形状は `(batch_size, sequence_length, num_experts)`。

  MoE ルーターによって計算される生（raw）のルーター logits（softmax 後）であり、Mixture of Experts モデルの補助損失を計算するためにこれらの用語が使用されます。

## Llama4VisionModel[[transformers.Llama4VisionModel]]

#### transformers.Llama4VisionModel[[transformers.Llama4VisionModel]]

```python
transformers.Llama4VisionModel(config: Llama4VisionConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/modeling_llama4.py#L1011)

#### forward[[transformers.Llama4VisionModel.forward]]

```python
forward(pixel_values: Tensor, attention_mask: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama4/modeling_llama4.py#L1048)

例:

```python
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, MllamaVisionModel

>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaVisionModel.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)

>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> inputs = processor(images=image, return_tensors="pt")

>>> output = model(**inputs)

>>> print(output.last_hidden_state.shape)
torch.Size([1, 1, 4, 1025, 7680])
```

