# VideoLLaMA3

## 概要

[VideoLLaMA3](https://huggingface.co/papers/2501.13106)モデルは、Alibaba DAMO Academyによる[VideoLLaMA2](https://huggingface.co/papers/2406.07476)の大幅なアップデートです。

論文の抄録は以下の通りです。

*本論文では、画像および動画の理解のためのより高度なマルチモーダル基盤モデルであるVideoLLaMA 3を提案します。VideoLLaMA3のコアな設計哲学は、ビジョン中心（vision-centric）です。「ビジョン中心」の意味は2つあります。ビジョン中心の学習パラダイムと、ビジョン中心のフレームワーク設計です。ビジョン中心の学習パラダイムの重要な洞察は、高品質な画像テキストデータが、画像理解と動画理解の両方にとって不可欠であるという点です。膨大な量の動画テキストデータセットを用意するのではなく、大規模で高品質な画像テキストデータセットの構築に焦点を当てています。VideoLLaMA3には4つの学習段階があります。1) Vision Encoder Adaptation（ビジョンエンコーダの適応）：ビジョンエンコーダが可変解像度の画像を入力として受け入れられるようにします。2) Vision-Language Alignment（ビジョンと言語の整合）：ビジョンエンコーダ、プロジェクター、LLMを、複数のタイプ（シーン画像、文書、チャートなどを含む）の大規模な画像テキストデータおよびテキストのみデータで共同チューニングします。3) Multi-task Fine-tuning（マルチタスクファインチューニング）：下流タスクのための画像テキストSFTデータと、動画理解の基盤を確立するための動画テキストデータを取り入れます。4) Video-centric Fine-tuning（動画中心のファインチューニング）：動画理解におけるモデルの能力をさらに向上させます。フレームワーク設計については、画像内の細粒度の詳細をよりよく捉えるために、事前学習済みのビジョンエンコーダを適応させ、固定されたトークン数ではなく、対応する数のビジョントークンに変換するようにします。動画入力については、類似度に基づいてビジョントークンの数を削減することで、動画の表現をより正確かつコンパクトにします。ビジョン中心の設計のおかげで、VideoLLaMA3は画像理解と動画理解の両方のベンチマークで優れたパフォーマンスを達成しています。*

<img src="https://github.com/DAMO-NLP-SG/VideoLLaMA3/raw/refs/heads/main/assets/pipeline.jpg"
alt="drawing" width="600"/>

 VideoLLaMA3のアーキテクチャ。技術レポートより引用。

このモデルは [lkhl](https://huggingface.co/lkhl) によって提供されました。

## 使用例

### 単一メディア推論

モデルは画像と動画の両方を入力として受け取ることができます。推論のコード例を以下に示します。

```python
from transformers import AutoProcessor, VideoLlama3ForConditionalGeneration

# Load the model in half-precision on the available device(s)
model = VideoLlama3ForConditionalGeneration.from_pretrained("lkhl/VideoLLaMA3-2B-Image-HF", device_map="auto")
processor = AutoProcessor.from_pretrained("lkhl/VideoLLaMA3-2B-Image-HF")

conversation = [
    {
        "role":"user",
        "content":[
            {"type": "image", "image": "https://github.com/DAMO-NLP-SG/VideoLLaMA3/raw/refs/heads/main/assets/sora.png"},
            {"type": "text", "text": "Describe this image."}
        ]
    }
]

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

# Inference: Generation of the output
output_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, output_ids)]
output_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
print(output_text)

# Video
conversation = [
    {
        "role": "user",
        "content": [
            {"type": "video", "video": "https://github.com/DAMO-NLP-SG/VideoLLaMA3/raw/refs/heads/main/assets/cat_and_chicken.mp4"},
            {"type": "text", "text": "What happened in the video?"},
        ],
    }
]

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

# Inference: Generation of the output
output_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, output_ids)]
output_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
print(output_text)
```

### バッチ混在メディア推論

モデルは、画像、動画、テキストなど、さまざまなタイプのサンプルが混在した入力をバッチ処理できます。以下に例を示します。

```python
# Image
conversation1 = [
    {
        "role": "user",
        "content": [
            {"type": "image", "image": "https://github.com/DAMO-NLP-SG/VideoLLaMA3/raw/refs/heads/main/assets/sora.png"},
            {"type": "text", "text": "Describe this image."}
        ]
    }
]

# Video
conversation2 = [
    {
        "role": "user",
        "content": [
            {"type": "video", "video": "https://github.com/DAMO-NLP-SG/VideoLLaMA3/raw/refs/heads/main/assets/cat_and_chicken.mp4"},
            {"type": "text", "text": "What happened in the video?"},
        ],
    }
]

# Text
conversation3 = [
    {
        "role": "user",
        "content": "What color is a banana?"
    }
]

conversations = [conversation1, conversation2, conversation3]
# Preparation for batch inference
inputs = processor.apply_chat_template(
    conversations,
    fps=1,
    add_generation_prompt=True,
    tokenize=True,
    padding=True,
    padding_side="left",
    return_dict=True,
    return_tensors="pt"
).to(model.device)

# Batch Inference
output_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, output_ids)]
output_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
print(output_text)
```

#### Flash-Attention 2 を使用して生成を高速化

まず、Flash Attention 2 の最新バージョンをインストールしてください。

```bash
pip install -U flash-attn --no-build-isolation
```

また、Flash-Attention 2 に対応するハードウェアが必要です。詳細については、[flash attention リポジトリ](https://github.com/Dao-AILab/flash-attention)の公式ドキュメントを参照してください。FlashAttention-2 は、モデルが `torch.float16` または `torch.bfloat16` で読み込まれている場合のみ使用できます。

Flash Attention-2 を使用してモデルを読み込み、実行するには、モデルの読み込み時に `attn_implementation="flash_attention_2"` を追加するだけです。

```python
from transformers import VideoLlama3ForConditionalGeneration

model = VideoLlama3ForConditionalGeneration.from_pretrained(
    "lkhl/VideoLLaMA3-2B-Image-HF", , 
    attn_implementation="flash_attention_2",
 device_map="auto")
```

## VideoLlama3Config[[transformers.VideoLlama3Config]]

#### transformers.VideoLlama3Config[[transformers.VideoLlama3Config]]

```python
transformers.VideoLlama3Config(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, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, image_token_id: int = 151655, video_token_id: int = 151656, tie_word_embeddings: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/configuration_video_llama_3.py#L65)

**パラメータ:**

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

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

image_token_id (`int`, *任意*, デフォルトは `151655`) : 入力画像のプレースホルダーとして使用される画像トークンのインデックスです。

video_token_id (`int`、*任意*、デフォルトは`151656`) : 入力動画のプレースホルダーとして使用される動画トークンのインデックスです。

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

これはVideoLlama3Modelの設定を保存するための設定クラスです。指定された引数に基づいてVideo Llama 3モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[lkhl/VideoLLaMA3-2B-Image-HF](https://huggingface.co/lkhl/VideoLLaMA3-2B-Image-HF)と類似した設定が得られます。

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

## VideoLlama3VisionConfig[[transformers.VideoLlama3VisionConfig]]

#### transformers.VideoLlama3VisionConfig[[transformers.VideoLlama3VisionConfig]]

```python
transformers.VideoLlama3VisionConfig(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, intermediate_size: int = 3072, num_hidden_layers: int = 12, num_attention_heads: int = 12, num_channels: int = 3, patch_size: int | list[int] | tuple[int, int] = 16, hidden_act: str = 'gelu_pytorch_tanh', layer_norm_eps: float = 1e-06, attention_dropout: float | int = 0.0, initializer_range: float = 0.02, rope_parameters: dict | None = None)
```

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

**パラメータ:**

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

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

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

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

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

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

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

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

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

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

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

これはVideoLlama3Modelの設定を保存するための設定クラスです。指定された引数に基づいてVideo Llama 3モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[lkhl/VideoLLaMA3-2B-Image-HF](https://huggingface.co/lkhl/VideoLLaMA3-2B-Image-HF)と類似した設定が得られます。

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

例:

```python
>>> from transformers import VideoLlama3VisionConfig, VideoLlama3VisionModel

>>> # Initializing a VideoLlama3VisionConfig with google/video_llama_3-base-patch16-224 style configuration
>>> configuration = VideoLlama3VisionConfig()

>>> # Initializing a VideoLlama3VisionModel (with random weights) from the google/video_llama_3-base-patch16-224 style configuration
>>> model = VideoLlama3VisionModel(configuration)

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

## VideoLlama3ImageProcessor[[transformers.VideoLlama3ImageProcessor]]

#### transformers.VideoLlama3ImageProcessor[[transformers.VideoLlama3ImageProcessor]]

```python
transformers.VideoLlama3ImageProcessor(**kwargs: *<class 'transformers.models.video_llama_3.image_processing_video_llama_3.VideoLlama3ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/image_processing_video_llama_3.py#L86)

**パラメータ:**

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*、デフォルト値は `{'shortest_edge' : 3136, 'longest_edge': 1003520}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*, デフォルトは `False`) : 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*、デフォルトは `3`) : 画像をリサイズする場合に使用するリサンプリングフィルター。`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*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

min_pixels (`int`, *kwargs*, *optional*, デフォルトは `56 * 56`) : 画像をリサイズする際の最小ピクセル数。

max_pixels (`int`, *kwargs*, *optional*, デフォルトは `28 * 28 * 1280`) : 画像をリサイズする際の最大ピクセル数。

patch_size (`int`, *kwargs*, *optional*, デフォルトは 14) : ビジョンエンコーダーの空間パッチサイズです。

temporal_patch_size (`int`, *kwargs*, *optional*, デフォルトは 1) : ビジョンエンコーダーの時間方向のパッチサイズです。

merge_size (`int`, *kwargs*, *optional*, デフォルトは 2) : vision encoder から llm encoder へのマージサイズです。

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

#### preprocess[[transformers.VideoLlama3ImageProcessor.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.video_llama_3.image_processing_video_llama_3.VideoLlama3ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/image_processing_video_llama_3.py#L140)

**パラメータ:**

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

min_pixels (`int`, *kwargs*, *optional*, デフォルトは `56 * 56`) : 画像をリサイズする際の最小ピクセル数。

max_pixels (`int`, *kwargs*, *optional*, デフォルトは `28 * 28 * 1280`) : 画像をリサイズする際の最大ピクセル数。

patch_size (`int`, *kwargs*, *optional*, デフォルトは 14) : ビジョンエンコーダーの空間パッチサイズです。

temporal_patch_size (`int`, *kwargs*, *optional*, デフォルトは 1) : ビジョンエンコーダーの時間方向のパッチサイズです。

merge_size (`int`, *kwargs*, *optional*, デフォルトは 2) : vision encoder から llm encoder へのマージサイズです。

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

- **data** (`dict`, *任意*) -- __call__/pad メソッドによって返されるリスト/配列/テンソルの辞書（'input_values'、'attention_mask' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。
- **skip_tensor_conversion** (`list[str]` または `set[str]`、*任意*) -- `tensor_type` が指定されている場合でも、テンソルに変換すべきでないキーのリストまたはセット。

## VideoLlama3VideoProcessor[[transformers.VideoLlama3VideoProcessor]]

#### transformers.VideoLlama3VideoProcessor[[transformers.VideoLlama3VideoProcessor]]

```python
transformers.VideoLlama3VideoProcessor(**kwargs: *<class 'transformers.models.video_llama_3.video_processing_video_llama_3.VideoLlama3VideoProcessorInitKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/video_processing_video_llama_3.py#L95)

**パラメータ:**

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

VideoLlama3VideoProcessor ビデオプロセッサを構築します。

#### preprocess[[transformers.VideoLlama3VideoProcessor.preprocess]]

```python
preprocess(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]]], **kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

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

**パラメータ:**

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` を設定してください。

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 の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

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_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

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

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

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*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

do_sample_frames (`bool`, *kwargs*, *optional*) : 処理前に動画からフレームをサンプリングするか、動画全体を処理するかを指定します。

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : 動画のメタデータ。総再生時間、fps、総フレーム数などの情報を含みます。動画からのフレームサンプリングやタイムスタンプの計算に使用されます。動画を処理する前に手動でデコードしようとしている場合を除き、メタデータは渡さないでください。

fps (`Annotated[int | float | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、1 秒あたりにサンプリングするターゲットフレーム数。

num_frames (`Annotated[int | None, None]`, *kwargs*) : `do_sample_frames=True` の場合、サンプリングするフレームの最大数。

return_metadata (`bool`, *kwargs*, *任意*) : ビデオメタデータを返すかどうかを指定します。ビデオメタデータは、ビデオの再生時間、fps、デコードバックエンドなどの情報を含むオブジェクトです。

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

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

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

## VideoLlama3ImageProcessorPil[[transformers.VideoLlama3ImageProcessorPil]]

#### transformers.VideoLlama3ImageProcessorPil[[transformers.VideoLlama3ImageProcessorPil]]

```python
transformers.VideoLlama3ImageProcessorPil(**kwargs: *<class 'transformers.models.video_llama_3.image_processing_pil_video_llama_3.VideoLlama3ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/image_processing_pil_video_llama_3.py#L85)

**パラメータ:**

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*、デフォルト値は `{'shortest_edge' : 3136, 'longest_edge': 1003520}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*, デフォルトは `False`) : 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*、デフォルトは `3`) : 画像をリサイズする場合に使用するリサンプリングフィルター。`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*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

min_pixels (`int`, *kwargs*, *optional*, デフォルトは `56 * 56`) : 画像をリサイズする際の最小ピクセル数。

max_pixels (`int`, *kwargs*, *optional*, デフォルトは `28 * 28 * 1280`) : 画像をリサイズする際の最大ピクセル数。

patch_size (`int`, *kwargs*, *optional*, デフォルトは 14) : ビジョンエンコーダーの空間パッチサイズです。

temporal_patch_size (`int`, *kwargs*, *optional*, デフォルトは 1) : ビジョンエンコーダーの時間方向のパッチサイズです。

merge_size (`int`, *kwargs*, *optional*, デフォルトは 2) : vision encoder から llm encoder へのマージサイズです。

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

#### preprocess[[transformers.VideoLlama3ImageProcessorPil.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.video_llama_3.image_processing_pil_video_llama_3.VideoLlama3ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/image_processing_pil_video_llama_3.py#L202)

**パラメータ:**

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

min_pixels (`int`, *kwargs*, *optional*, デフォルトは `56 * 56`) : 画像をリサイズする際の最小ピクセル数。

max_pixels (`int`, *kwargs*, *optional*, デフォルトは `28 * 28 * 1280`) : 画像をリサイズする際の最大ピクセル数。

patch_size (`int`, *kwargs*, *optional*, デフォルトは 14) : ビジョンエンコーダーの空間パッチサイズです。

temporal_patch_size (`int`, *kwargs*, *optional*, デフォルトは 1) : ビジョンエンコーダーの時間方向のパッチサイズです。

merge_size (`int`, *kwargs*, *optional*, デフォルトは 2) : vision encoder から llm encoder へのマージサイズです。

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

- **data** (`dict`, *任意*) -- __call__/pad メソッドによって返されるリスト/配列/テンソルの辞書（'input_values'、'attention_mask' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。
- **skip_tensor_conversion** (`list[str]` または `set[str]`、*任意*) -- `tensor_type` が指定されている場合でも、テンソルに変換すべきでないキーのリストまたはセット。

## VideoLlama3Processor[[transformers.VideoLlama3Processor]]

#### transformers.VideoLlama3Processor[[transformers.VideoLlama3Processor]]

```python
transformers.VideoLlama3Processor(image_processor = None, tokenizer = None, video_processor = None, chat_template = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/processing_video_llama_3.py#L38)

**パラメータ:**

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

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

video_processor (`VideoLlama3VideoProcessor`) : 動画プロセッサは必須の入力です。

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

画像プロセッサ、トークナイザ、および動画プロセッサを単一のプロセッサにまとめるを構築します。

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

#### __call__[[transformers.VideoLlama3Processor.__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 クラスを参照してください。

## VideoLlama3Model[[transformers.VideoLlama3Model]]

#### transformers.VideoLlama3Model[[transformers.VideoLlama3Model]]

```python
transformers.VideoLlama3Model(config: VideoLlama3Config)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/modeling_video_llama_3.py#L536)

**パラメータ:**

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

Video Llama 3のベースモデルは、特定のヘッドを上に載せず、生の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.VideoLlama3Model.forward]]

```python
forward(input_ids: 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, pixel_values: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, image_merge_sizes: typing.Optional[torch.LongTensor] = None, pixel_values_videos: typing.Optional[torch.FloatTensor] = None, video_grid_thw: typing.Optional[torch.LongTensor] = None, video_merge_sizes: typing.Optional[torch.LongTensor] = None, video_compression_mask: typing.Optional[torch.BoolTensor] = None, 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/video_llama_3/modeling_video_llama_3.py#L640)

**パラメータ:**

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`を参照）。

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

image_grid_thw (`torch.LongTensor`、形状 `(num_images, 3)`、*任意*) : LLM における各画像のフィーチャー形状の時間軸、高さ、幅。

image_merge_sizes (`torch.Tensor`、形状 `(num_images,)`) : 各画像特徴の空間的下サンプリング比率。

pixel_values_videos (`torch.FloatTensor`、shape `(batch_size, num_frames, num_channels, frame_size, frame_size)`、*optional*) : 入力動画に対応するテンソルです。動画のピクセル値は、[VideoLlama3VideoProcessor](/docs/transformers/main/ja/model_doc/video_llama_3#transformers.VideoLlama3VideoProcessor) を使用して取得できます。詳細については、[VideoLlama3VideoProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2VideoProcessor.__call__) を参照してください（[VideoLlama3Processor](/docs/transformers/main/ja/model_doc/video_llama_3#transformers.VideoLlama3Processor) は、動画の処理に [VideoLlama3VideoProcessor](/docs/transformers/main/ja/model_doc/video_llama_3#transformers.VideoLlama3VideoProcessor) を使用します）。

video_grid_thw (`torch.LongTensor`、形状 `(num_videos, 3)`、*任意*) : LLM における各動画のフィーチャー形状の時間軸、高さ、幅。

video_merge_sizes (`torch.Tensor`、形状 `(num_videos,)`) : 各動画特徴の空間的下サンプリング比率。

video_compression_mask (`torch.BoolTensor`、shape `(num_video_features,)`、*optional*) : トークン圧縮後に保持される動画特徴量を指定するためのマスク。

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

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

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

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

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

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`、*optional*) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **past_key_values** (`Cache`、*任意*、`use_cache=True` が渡された場合または `config.use_cache=True` の場合に返されます) -- 長さが `config.n_layers` の `tuple(torch.FloatTensor)` のタプルで、各タプルには形状が `(batch_size, num_heads, sequence_length, embed_size_per_head)` のテンソルが2つ含まれます

  逐次デコーディングを高速化するために使用できる（`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`、*任意*) -- サイズが`(num_images_features, hidden_size)`の`torch.FloatTensor`。ビジョンエンコーダーによって生成され、最後の隠れ状態を投影した後のモデルのimage_hidden_statesです。
- **video_hidden_states** (`torch.FloatTensor`、*任意*) -- サイズが`(num_video_features, hidden_size)`の`torch.FloatTensor`。ビジョンエンコーダーによって生成され、最後の隠れ状態を投影した後のモデルのvideo_hidden_statesです。

#### get_video_features[[transformers.VideoLlama3Model.get_video_features]]

```python
get_video_features(pixel_values_videos: FloatTensor, video_grid_thw: LongTensor, video_merge_sizes: LongTensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/modeling_video_llama_3.py#L550)

**パラメータ:**

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

video_grid_thw (`torch.LongTensor`、shape `(num_videos, 3)`) : LLMにおける各動画のフィーチャー形状の時間軸、高さ、幅。

video_merge_sizes (`torch.Tensor`、形状 `(num_videos,)`) : 各動画特徴の空間的下サンプリング比率。

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

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

- **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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

#### get_image_features[[transformers.VideoLlama3Model.get_image_features]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/modeling_video_llama_3.py#L571)

**パラメータ:**

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

image_grid_thw (`torch.LongTensor`、形状 `(num_images, 3)`) : LLM における各画像のフィーチャー形状の時間軸、高さ、幅。

image_merge_sizes (`torch.Tensor`、形状 `(num_images,)`) : 各画像特徴の空間的下サンプリング比率。

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

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

- **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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

## VideoLlama3VisionModel[[transformers.VideoLlama3VisionModel]]

#### transformers.VideoLlama3VisionModel[[transformers.VideoLlama3VisionModel]]

```python
transformers.VideoLlama3VisionModel(config: VideoLlama3VisionConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/modeling_video_llama_3.py#L408)

#### forward[[transformers.VideoLlama3VisionModel.forward]]

```python
forward(pixel_values: Tensor, grid_thw: Tensor, merge_sizes: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/modeling_video_llama_3.py#L452)

**パラメータ:**

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

grid_thw (`torch.LongTensor`、形状 `(num_images_or_videos, 3)`) : 各画像のフィーチャー形状の時間、高さ、幅の次元。各行に [t, h, w] の値が含まれます。

merge_sizes (`torch.Tensor`、形状 `(num_images_or_videos,)`) : 各画像または動画特徴の空間的下サンプリング比率。

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

A [BaseModelOutput](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutput) or a tuple of `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various elements depending on the configuration ([VideoLlama3Config](/docs/transformers/main/ja/model_doc/video_llama_3#transformers.VideoLlama3Config)) and inputs.

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

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

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

## VideoLlama3ForConditionalGeneration[[transformers.VideoLlama3ForConditionalGeneration]]

#### transformers.VideoLlama3ForConditionalGeneration[[transformers.VideoLlama3ForConditionalGeneration]]

```python
transformers.VideoLlama3ForConditionalGeneration(config: VideoLlama3Config)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/modeling_video_llama_3.py#L760)

#### forward[[transformers.VideoLlama3ForConditionalGeneration.forward]]

```python
forward(input_ids: 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, pixel_values: typing.Optional[torch.Tensor] = None, image_grid_thw: typing.Optional[torch.LongTensor] = None, image_merge_sizes: typing.Optional[torch.LongTensor] = None, pixel_values_videos: typing.Optional[torch.FloatTensor] = None, video_grid_thw: typing.Optional[torch.LongTensor] = None, video_merge_sizes: typing.Optional[torch.LongTensor] = None, video_compression_mask: typing.Optional[torch.BoolTensor] = None, 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/video_llama_3/modeling_video_llama_3.py#L798)

**パラメータ:**

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`を参照）。

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

image_grid_thw (`torch.LongTensor`、形状 `(num_images, 3)`、*任意*) : LLM における各画像のフィーチャー形状の時間軸、高さ、幅。

image_merge_sizes (`torch.Tensor`、形状 `(num_images,)`) : 各画像特徴の空間的下サンプリング比率。

pixel_values_videos (`torch.FloatTensor`、shape `(batch_size, num_frames, num_channels, frame_size, frame_size)`、*optional*) : 入力動画に対応するテンソルです。動画のピクセル値は、[VideoLlama3VideoProcessor](/docs/transformers/main/ja/model_doc/video_llama_3#transformers.VideoLlama3VideoProcessor) を使用して取得できます。詳細については、[VideoLlama3VideoProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2VideoProcessor.__call__) を参照してください（[VideoLlama3Processor](/docs/transformers/main/ja/model_doc/video_llama_3#transformers.VideoLlama3Processor) は、動画の処理に [VideoLlama3VideoProcessor](/docs/transformers/main/ja/model_doc/video_llama_3#transformers.VideoLlama3VideoProcessor) を使用します）。

video_grid_thw (`torch.LongTensor`、形状 `(num_videos, 3)`、*任意*) : LLM における各動画のフィーチャー形状の時間軸、高さ、幅。

video_merge_sizes (`torch.Tensor`、形状 `(num_videos,)`) : 各動画特徴の空間的下サンプリング比率。

video_compression_mask (`torch.BoolTensor`、shape `(num_video_features,)`、*optional*) : トークン圧縮後に保持される動画特徴量を指定するためのマスク。

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

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

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

[VideoLlama3ForConditionalGeneration](/docs/transformers/main/ja/model_doc/video_llama_3#transformers.VideoLlama3ForConditionalGeneration) の 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` の場合に返されます) -- 長さが `config.n_layers` の `tuple(torch.FloatTensor)` のタプルで、各タプルには形状が `(batch_size, num_heads, sequence_length, embed_size_per_head)` のテンソルが2つ含まれます

  逐次デコーディングを高速化するために使用できる（`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`、*任意*) -- サイズが`(num_images_features, hidden_size)`の`torch.FloatTensor`。ビジョンエンコーダーによって生成され、最後の隠れ状態を投影した後のモデルのimage_hidden_statesです。
- **video_hidden_states** (`torch.FloatTensor`、*任意*) -- サイズが`(num_video_features, hidden_size)`の`torch.FloatTensor`。ビジョンエンコーダーによって生成され、最後の隠れ状態を投影した後のモデルのvideo_hidden_statesです。

例:

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

>>> model = VideoLlama3ForConditionalGeneration.from_pretrained("lkhl/VideoLLaMA3-2B-Image-HF")
>>> processor = AutoProcessor.from_pretrained("lkhl/VideoLLaMA3-2B-Image-HF")

>>> 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]
```

#### get_video_features[[transformers.VideoLlama3ForConditionalGeneration.get_video_features]]

```python
get_video_features(pixel_values_videos: FloatTensor, video_grid_thw: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/modeling_video_llama_3.py#L772)

**パラメータ:**

pixel_values_videos (`torch.FloatTensor`、shape `(batch_size, num_channels, image_size, image_size)`) : 入力動画に対応するテンソル。

video_grid_thw (`torch.LongTensor`、形状 `(num_videos, 3)`、*任意*) : LLM における各動画のフィーチャー形状の時間軸、高さ、幅。

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

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

- **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, VideoLlama3ForConditionalGeneration

>>> model = VideoLlama3ForConditionalGeneration.from_pretrained("lkhl/VideoLLaMA3-2B-Image-HF")
>>> processor = AutoProcessor.from_pretrained("lkhl/VideoLLaMA3-2B-Image-HF")

>>> 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]
```

#### get_image_features[[transformers.VideoLlama3ForConditionalGeneration.get_image_features]]

```python
get_image_features(pixel_values: FloatTensor, image_grid_thw: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llama_3/modeling_video_llama_3.py#L785)

**パラメータ:**

pixel_values (`torch.FloatTensor`、shape `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソル。

image_grid_thw (`torch.LongTensor`、形状 `(num_images, 3)`、*任意*) : LLM における各画像のフィーチャー形状の時間軸、高さ、幅。

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

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

- **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, VideoLlama3ForConditionalGeneration

>>> model = VideoLlama3ForConditionalGeneration.from_pretrained("lkhl/VideoLLaMA3-2B-Image-HF")
>>> processor = AutoProcessor.from_pretrained("lkhl/VideoLLaMA3-2B-Image-HF")

>>> 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]
```

