Transformers documentation
Llama4
このモデルは2025年4月5日にHugging Face Transformersに貢献されました。
Llama4
Llama 4, 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 のエキスパートを使用しています。
両方のモデルは、ネイティブなマルチモーダル性を実現するために早期融合を活用しており、テキストと画像の両方の入力を処理できます。 Maverick と Scout は、200 言語にまたがるデータセットの最大 40 兆トークンで学習されています(アラビア語、スペイン語、ドイツ語、ヒンディー語を含む 12 言語には、特定のファインチューニング対応があります)。
デプロイメントにおいて、Llama 4 Scout はアクセシビリティを重視して設計されており、オンザフライの 4 ビットまたは 8 ビット int4 量子化により、サーバーグレードの GPU 1 枚に収まるようになっています。一方、Maverick は BF16 と FP8 の形式で提供されています。これらのモデルは、モデルリポジトリで入手可能なカスタム Llama 4 Community License Agreement の下で公開されています。
すべてのオリジナルの Llama チェックポイントは、meta-llama 組織の下で確認できます。
Llama 4モデルファミリーには、109Bパラメータと402Bパラメータの2つのバリエーションがあります。どちらも非常に大規模であり、一般的なデバイスには収まりません。モデルのメモリ使用量を削減するための例を以下に示します。
ダウンロードをより高速かつ堅牢にするため、
hf_xet依存関係を次のようにインストールすることをお勧めします:pip install transformers[hf_xet]
以下の例では、PipelineまたはAutoModelを使用して生成を行う方法を示しています。また、Llama 4のいくつかのバリエーションではコンテキスト長が最大1000万トークンに達するため、非常に長いコンテキストでの生成を有効化するために必要な属性を切り替える方法を示す例も追加しています。
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"])
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])
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)
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による実行を可能にするよう取り組んでまいります。
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の概要を参照してください。
リリース時点では、Llama 4モデルは以下のアテンションメソッドをサポートしています: eager、flex_attention、sdpa。最適な結果を得るには、flex_attentionの使用を推奨します。
アテンションメカニズムの切り替えは、モデルの初期化ステップで行われます:
Flex Attentionを設定することで、モデルが処理できる非常に長いコンテキストにおいて、最適な結果が得られます。
注意: 以下の例では、
device_map="auto"と flex-attention の両方が使用されています。 この例をテンソル並列モードで実行するには、torchrunを使用してください。今後、テンソル並列なしで
device_map="auto"およびflex-attentionによる実行を可能にするよう取り組んでまいります。
from transformers import Llama4ForConditionalGeneration
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
attn_implementation="flex_attention",
device_map="auto",
)sdpa アテンション方式は、一般的にeager方式よりも計算効率が高いです。
from transformers import Llama4ForConditionalGeneration
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
attn_implementation="sdpa",
device_map="auto",
)eager 注意機構メソッドがデフォルトで設定されているため、モデルの読み込み時に特別な対応は不要です。
from transformers import Llama4ForConditionalGeneration
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
device_map="auto",
)量子化
Quantizationは、重みを低精度で表現することで、大規模モデルのメモリ負荷を軽減します。利用可能なQuantizationバックエンドについては、Quantizationの概要を参照してください。 リリース時点では、FBGEMMとLLM-Compressorの両方がサポートされています。リリース後、数日以内に追加のQuantization手法がサポートされる予定です。
両方を使用した例を以下に示します。
FBGEMMアプローチを使用して、BF16モデルをFP8で読み込む例を以下に示します。
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チェックポイントの利用を推奨します。
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に指定するだけです。
from transformers import Llama4ForConditionalGeneration
model = Llama4ForConditionalGeneration.from_pretrained(
model_id,
device_map="auto",
)Llama4Config
class transformers.Llama4Config
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneboi_token_index: int = 200080eoi_token_index: int = 200081image_token_index: int = 200092tie_word_embeddings: bool = False )
パラメータ
- vision_config (
Union[dict, ~configuration_utils.PreTrainedConfig]、任意) — ビジョンバックボーンの config オブジェクトまたは辞書です。 - text_config (
Union[dict, ~configuration_utils.PreTrainedConfig]、省略可) — テキストバックボーンの設定オブジェクトまたは辞書。 - boi_token_index (
int、省略可能、デフォルトは 200080) — 画像プロンプトをラップするために使用する begin-of-image トークンのインデックスです。 - eoi_token_index (
int、任意、デフォルト値は 200081) — 画像プロンプトをラップするために使用する end-of-image トークンのインデックスです。 - image_token_index (
int、任意、デフォルトは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
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
>>> 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.configLlama4TextConfig
クラス transformers.Llama4TextConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 202048hidden_size: int = 5120intermediate_size: int = 8192intermediate_size_mlp: int = 16384num_hidden_layers: int = 48num_attention_heads: int = 40num_key_value_heads: int = 8head_dim: int = 128hidden_act: str = 'silu'max_position_embeddings: int = 131072initializer_range: float = 0.02rms_norm_eps: float = 1e-05use_cache: bool = Truepad_token_id: int | None = Nonebos_token_id: int | None = 1eos_token_id: int | list[int] | None = 2tie_word_embeddings: bool = Falseattention_dropout: float | int = 0.0num_experts_per_tok: int = 1num_local_experts: int = 16moe_layers: list[int] | None = Noneinterleave_moe_layer_step: int = 1use_qk_norm: bool = Trueoutput_router_logits: bool = Falserouter_aux_loss_coef: float = 0.001router_jitter_noise: float = 0.0rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneno_rope_layers: list[int] | None = Noneno_rope_layer_interval: int = 4attention_chunk_size: int | None = 8192layer_types: list[str] | None = Noneattn_temperature_tuning: bool = Truefloor_scale: int = 8192attn_scale: float = 0.1attention_bias: bool = False )
パラメータ
- vocab_size (
int、任意、デフォルトは202048) — モデルの語彙サイズ。input_idsで表現できるトークンの種類数を定義します。 - hidden_size (
int、任意、デフォルトは5120) — 隠れ表現の次元数です。 - intermediate_size (
int、任意、デフォルトは8192) — MLP 表現の次元数。 - intermediate_size_mlp (
int、任意、デフォルト値は 16384) — Dense MLP レイヤーの中間サイズ。値を大きくすると、FFN の容量と計算量が増加します。 - num_hidden_layers (
int、任意、デフォルトは48) — Transformer デコーダーの隠れ層の数。 - num_attention_heads (
int、任意、デフォルトは40) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。 - num_key_value_heads (
int、任意、デフォルトは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 ヘッドを、そのグループ内の元のすべてのヘッドの平均プーリングによって構築する必要があります。詳細については、この論文を参照してください。指定しない場合、デフォルトで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、任意、デフォルト値は 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], 省略可) — 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、任意、デフォルトは 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
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
例:
Llama4VisionConfig
class transformers.Llama4VisionConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 768hidden_act: str = 'gelu'num_hidden_layers: int = 34num_attention_heads: int = 16num_channels: int = 3intermediate_size: int = 5632vision_output_dim: int = 7680image_size: int | list[int] | tuple[int, int] = 448patch_size: int | list[int] | tuple[int, int] = 14norm_eps: float = 1e-05vision_feature_select_strategy: str = 'default'initializer_range: float = 0.02pixel_shuffle_ratio: float = 0.5projector_input_dim: int = 4096projector_output_dim: int = 4096multi_modal_projector_bias: bool = Falseprojector_dropout: float | int = 0.0attention_dropout: float | int = 0.0rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None )
パラメータ
- 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) — レイヤーノーマライゼーション層で使用する epsilon です。 - vision_feature_select_strategy (
str、任意、デフォルトはdefault) — ビジョンバックボーンからビジョン特徴を選択するために使用される特徴選択戦略です。 - initializer_range (
float、任意、デフォルトは0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。 - pixel_shuffle_ratio (
float、任意、デフォルトは 0.5) — パッチトークンをダウンサンプリングするためのピクセルシャッフル比率です。値が小さいほど、トークン数が少なくなります(ダウンサンプリングの度合いが大きくなります)。 - projector_input_dim (
int、任意、デフォルトは 4096) — ピクセルシャッフル前のビジョンアダプタ MLP の幅。値を大きくすると容量と計算量が増加します。 - projector_output_dim (
int、任意、デフォルトは 4096) — ビジョンアダプターの出力幅です。値を大きくすると、より高次元の画像特徴が得られます。 - multi_modal_projector_bias (
bool、任意、デフォルトはFalse) — マルチモーダルプロジェクターでバイアスを使用するかどうか。 - projector_dropout (
float、省略可、デフォルト値は 0.0) — ビジョンアダプタの MLP 内で使用される Dropout 率です。値を高くすると、正則化が強化されます。 - attention_dropout (
Union[float, int]、任意、デフォルトは0.0) — アテンション確率のドロップアウト率です。 - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], 省略可) — 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
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
Llama4Processor
class transformers.Llama4Processor
< source >( image_processor = Nonetokenizer = Nonepatch_size: int = 14pixel_shuffle_ratio: float = 0.5fake_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 )
パラメータ
- image_processor (
Llama4ImageProcessor) — 画像プロセッサは必須の入力です。 - tokenizer (
tokenizer_class) — トークナイザーは必須の入力です。 - patch_size (
int、任意、デフォルトは 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 %} — {#- 最初のユーザーメッセージを抽出し、ここで挿入できるようにする #} {%- 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 は、Llama4ImageProcessor と tokenizer_class のすべての機能を提供します。詳細については、~Llama4ImageProcessor および ~tokenizer_class を参照してください。
__call__
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = Nonevideos: 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] = Noneaudio: 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'> )
パラメータ
- 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, 省略可) — 設定すると、特定のフレームワークのテンソルを返します。使用可能な値は以下の通りです:'pt': PyTorchのtorch.Tensorオブジェクトを返します。'np': NumPyのnp.ndarrayオブジェクトを返します。
- **kwargs (ProcessingKwargs、任意) — 各モダリティ(テキスト、画像、動画、音声)の追加処理オプション。モデル固有のパラメータは上記にリストされています。サポートされている引数の完全なリストについては、TypedDictクラスを参照してください。
Llama4ImageProcessor
クラス transformers.Llama4ImageProcessor
< source >( **kwargs: *<class 'transformers.models.llama4.image_processing_llama4.Llama4ImageProcessorKwargs'> )
パラメータ
- 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 が 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, デフォルトは2) — 画像のリサイズ時に使用するリサンプリングフィルタです。PILImageResamplingの列挙型のいずれかを使用できます。do_resizeがTrueに設定されている場合のみ、効果が現れます。 - do_rescale (
bool、kwargs、任意、デフォルトはTrue) — 画像をリスケールするかどうかを指定します。 - rescale_factor (
float、kwargs、任意、デフォルト値は0.00392156862745098) —do_rescaleがTrueに設定されている場合、画像をリスケールするための係数です。 - do_normalize (
bool、kwargs、optional、デフォルトはTrue) — 画像を正規化するかどうかを指定します。 - image_mean (
Union[float, list[float], tuple[float, ...]]、kwargs、任意、デフォルトは[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, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。 - 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、任意) — サポートされているのは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: (高さ, 幅, チャネル数) 形式の画像。"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、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。 - image_seq_length (
int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。 - max_patches (
int、kwargs、任意、デフォルト値は 16) — 画像から抽出するパッチの最大数です。preprocessメソッドのmax_patchesパラメータによって上書きできます。 - resize_to_max_canvas (
bool、kwargs、optional、デフォルトは False)— 画像を最大キャンバスサイズにリサイズするかどうかを指定します。 True の場合、歪みなく最大限のリサイズを許可するキャンバスを選択します。 False の場合、リサイズしないことも含め、可能な限りダウンスケールのみを行います。ただし、画像がパッチサイズより小さい場合はアップスケールします。
Llama4ImageProcessor の画像プロセッサを構築します。
preprocess
< source >( 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'> ) → ~image_processing_base.BatchFeature
パラメータ
- 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、任意) — 画像を RGB に変換するかどうかを指定します。 - do_resize (
bool、kwargs、optional) — 画像をリサイズするかどうか。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — モデルへの最大入力次元を記述します。 - default_to_square (
bool、kwargs、任意) — サイズが整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。 - 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、optional) — 画像をリスケールするかどうかを指定します。 - rescale_factor (
float、kwargs、任意) —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, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。 - 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、任意) — サポートされているのは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: (高さ, 幅, チャネル数) 形式の画像。"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、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。 - image_seq_length (
int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。 - max_patches (
int、kwargs、任意、デフォルト値は 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
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonevision_feature_select_strategy: str | None = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Llama4CausalLMOutputWithPast or tuple(torch.FloatTensor)
パラメータ
- input_ids (
torch.LongTensorの形状(batch_size, sequence_length), 、省略可) — 語彙における入力シーケンスのトークンインデックスです。デフォルトではパディングは無視されます。インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。
- pixel_values (
torch.FloatTensor、形状(batch_size, num_channels, image_size, image_size)、任意) — 入力画像に対応するテンソルです。ピクセル値は Llama4ImageProcessor を使用して取得できます。詳細については Llama4ImageProcessor.call() を参照してください(Llama4Processor は画像の処理に Llama4ImageProcessor を使用します)。 - attention_mask (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。[0, 1]:- マスクされていないトークンに対して1
- マスクされたトークンに対しては 0 です。
- position_ids (
torch.LongTensorの形状(batch_size, sequence_length), 、任意) — 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックス。範囲[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 省略可) — 逐次デコードを高速化するために使用できる、事前計算された隠れ状態(自己アテンションブロックおよびクロスアテンションブロックのキーとバリュー)。通常、これはデコードの以前の段階でモデルが返したpast_key_valuesであり、use_cache=Trueまたはconfig.use_cache=True.入力として許可されるのは Cache インスタンスのみです。kv cache ガイドを参照してください。
past_key_valuesが渡されない場合、デフォルトで DynamicCache が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。
past_key_valuesを使用する場合、すべてのinput_ids(形状(batch_size, sequence_length))ではなく、このモデルに過去のキー・バリュー状態が与えられていない未処理のinput_ids(形状(batch_size, unprocessed_length))のみを入力することになります。 - inputs_embeds (
torch.FloatTensor、形状(batch_size, sequence_length, hidden_size)、任意) —input_idsを渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込みルックアップ行列よりも、input_idsのインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。 - vision_feature_select_strategy (
str, 任意) — ビジョンバックボーンからビジョン特徴を選択するために使用される特徴選択戦略です。"default"または"full"のいずれかになります。 - labels (
torch.LongTensor、shape(batch_size, sequence_length)、任意) — マスク言語モデリング損失を計算するためのラベルです。インデックスは[0, ..., config.vocab_size]の範囲内であるか、-100 である必要があります(input_idsの docstring を参照)。インデックスが-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 を返すかどうか。 - 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), 省略可) からなるタプルです。pooler_outputは、エンコーダーのマルチモーダル特徴量をテキスト埋め込みにマージしたシーケンスです。
戻り値
Llama4CausalLMOutputWithPast または tuple(torch.FloatTensor)
Llama4CausalLMOutputWithPast または、torch.FloatTensor のタプル(return_dict=False が渡された場合、または config.return_dict=False の場合)。設定(Llama4Config)や入力に応じて、さまざまな要素で構成されます。
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 のインスタンスです。詳細については、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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
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)です。
例:
>>> 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
< source >( pixel_values: FloatTensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.FloatTensor)
パラメータ
- pixel_values (
torch.FloatTensor、形状(batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値は Llama4ImageProcessor を使用して取得できます。詳細については Llama4ImageProcessor.call() を参照してください(Llama4Processor は画像の処理に Llama4ImageProcessor を使用します)。
戻り値
BaseModelOutputWithPooling または tuple(torch.FloatTensor)
torch.FloatTensor のタプル(return_dict=False が渡された場合、または config.return_dict=False の場合)または BaseModelOutputWithPooling。設定(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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
例:
>>> 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
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeCausalLMOutputWithPast or tuple(torch.FloatTensor)
パラメータ
- input_ids (
torch.LongTensorの形状(batch_size, sequence_length), 、省略可) — 語彙における入力シーケンスのトークンインデックスです。デフォルトではパディングは無視されます。インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。
- attention_mask (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。[0, 1]:- マスクされていないトークンに対して1
- マスクされたトークンに対しては 0 です。
- position_ids (
torch.LongTensorの形状(batch_size, sequence_length), 、任意) — 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックス。範囲[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 省略可) — 逐次デコードを高速化するために使用できる、事前計算された隠れ状態(自己アテンションブロックおよびクロスアテンションブロックのキーとバリュー)。通常、これはデコードの以前の段階でモデルが返したpast_key_valuesであり、use_cache=Trueまたはconfig.use_cache=True.入力として許可されるのは Cache インスタンスのみです。kv cache ガイドを参照してください。
past_key_valuesが渡されない場合、デフォルトで DynamicCache が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。
past_key_valuesを使用する場合、すべてのinput_ids(形状(batch_size, sequence_length))ではなく、このモデルに過去のキー・バリュー状態が与えられていない未処理のinput_ids(形状(batch_size, unprocessed_length))のみを入力することになります。 - inputs_embeds (
torch.FloatTensor、形状(batch_size, sequence_length, hidden_size)、任意) —input_idsを渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込みルックアップ行列よりも、input_idsのインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。 - labels (
torch.LongTensor、shape(batch_size, sequence_length)、任意) — マスク言語モデリング損失を計算するためのラベルです。インデックスは[0, ..., config.vocab_size]の範囲内であるか、-100 である必要があります(input_idsの docstring を参照)。インデックスが-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)や入力に応じて、さまざまな要素で構成されます。
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)、任意、output_router_logits=Trueが渡された場合またはconfig.output_router_logits=Trueの場合に返されます) — 各スパース層に対応するtorch.FloatTensorのタプルで、形状は(batch_size * sequence_length, num_experts)です。MoEルーターによって計算される生のルーターロジットです。ロードバランシング損失の計算や、トークンがどのようにエキスパートにディスパッチされるかの確認に使用できます。
past_key_values (
Cache、任意、use_cache=Trueが渡された場合またはconfig.use_cache=Trueの場合に返されます) — Cache のインスタンスです。詳細については、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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
例:
>>> 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
class transformers.Llama4TextModel
< source >( config: Llama4TextConfig )
パラメータ
- config (Llama4TextConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
裸の Llama4 Text Modelは、特定のヘッドを上に載せずに生の hidden-states を出力します。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeModelOutputWithPast or tuple(torch.FloatTensor)
パラメータ
- input_ids (
torch.LongTensorの形状(batch_size, sequence_length), 、省略可) — 語彙における入力シーケンスのトークンインデックスです。デフォルトではパディングは無視されます。インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。
- attention_mask (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。[0, 1]:- マスクされていないトークンに対して1
- マスクされたトークンに対しては 0 です。
- position_ids (
torch.LongTensorの形状(batch_size, sequence_length), 、任意) — 各入力シーケンスのトークンが位置埋め込み内で占める位置のインデックス。範囲[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 省略可) — 逐次デコードを高速化するために使用できる、事前計算された隠れ状態(自己アテンションブロックおよびクロスアテンションブロックのキーとバリュー)。通常、これはデコードの以前の段階でモデルが返したpast_key_valuesであり、use_cache=Trueまたはconfig.use_cache=True.入力として許可されるのは Cache インスタンスのみです。kv cache ガイドを参照してください。
past_key_valuesが渡されない場合、デフォルトで DynamicCache が初期化されます。モデルは、入力として与えられたのと同じキャッシュ形式を出力します。
past_key_valuesを使用する場合、すべてのinput_ids(形状(batch_size, sequence_length))ではなく、このモデルに過去のキー・バリュー状態が与えられていない未処理のinput_ids(形状(batch_size, unprocessed_length))のみを入力することになります。 - inputs_embeds (
torch.FloatTensor、形状(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)や入力に応じて、さまざまな要素で構成されます。
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 のインスタンスです。詳細については、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の場合に返されます) — 各層ごとに1つずつ含まれるtorch.FloatTensorのタプルで、形状は(batch_size, sequence_length, num_experts)です。MoE ルーターによって計算される生(raw)のルーター logits(softmax 適用後)であり、Mixture of Experts モデルの補助損失を計算するためにこれらの用語が使用されます。
Llama4VisionModel
forward
< source >( pixel_values: Tensorattention_mask: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs )
例:
>>> 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])