Transformers documentation

PE Video

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

このモデルは2025年4月17日にHF papersで公開され、2025年12月16日にHugging Face Transformersに貢献されました。 このモデルは2025年4月17日にリリースされ、2025年12月16日にHugging Face Transformersに追加されました。

PE Video

PE Videoは、MetaのPerception Encoderファミリーの動画向けモデルです。動画クリップとテキストを対照的にアラインし、共有埋め込み空間に配置することで、事前学習済みバックボーン1つからゼロショットの動画分類と動画–テキスト検索を可能にします。

エンコーダーのロータリー埋め込みとパッチエンベッダーは、時間軸を第一級の次元として扱います。そのため、各フレームを独立してタイル化することなく、可変長のクリップをエンコードできます。

公式のPE Audioチェックポイントはすべて、perception-encoder-audio-visualコレクションの下で確認できます。

クイックスタート

import torch
from transformers import AutoProcessor, PeVideoModel
from transformers.video_utils import load_video

processor = AutoProcessor.from_pretrained("facebook/pe-av-large")
model = PeVideoModel.from_pretrained(
    "facebook/pe-av-large",
    device_map="auto",
)

video, _ = load_video("https://huggingface.co/datasets/hf-internal-testing/fixtures_videos/resolve/main/tennis.mp4")
labels = ["a person playing tennis", "a person cooking", "a cat sleeping"]

video_inputs = processor.video_processor(video, num_frames=16, return_tensors="pt").to(model.device)
text_inputs = processor.tokenizer(labels, padding=True, return_tensors="pt").to(model.device)
inputs = {**video_inputs, **text_inputs}

with torch.no_grad():
    outputs = model(**inputs)

probs = outputs.logits_video_text.sigmoid()
print({label: p.item() for label, p in zip(labels, probs[0])})

使用上のヒントと注意点

  • 可変長の動画はpadding_mask_videos(attention_maskではありません)を使用します。動画プロセッサはreturn_tensorsが設定されている場合のみ、パディングを行い、このマスクを返します。設定しないと、クリップごとのテンソルのリストが返され、マスクは得られません。
  • num_frames を video processor に渡すことで、[0, total_frames-1] に対して固定長の均一サンプリングを行います。省略すると、ベースクラスの fps ベースのサンプリングにフォールバックします。チェックポイントは通常、特定のフレーム数で学習されているため、チェックポイントが想定するフレーム数に合わせる必要があります。
  • エンコーダーの入力はpixel_values_videosです。エンコーダーのmain_input_nameは"pixel_values_videos"ですが、フルモデルでは"input_ids"です。main_input_nameを参照してルーティングを行う汎用ユーティリティを使用する際には、この違いが重要になります。

PeVideoConfig

クラス transformers.PeVideoConfig

< >

( 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 = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevideo_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None )

パラメータ

  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig]、省略可) — テキストバックボーンの設定オブジェクトまたは辞書。
  • video_config (dict または PreTrainedConfig、省略可) — ビデオエンコーダーコンポーネントの設定です。

これは PeVideoModel の設定を保存するための設定クラスです。指定された引数に基づいて Pe Video モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、facebook/pe-av-large と同様の設定が得られます。

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

>>> from transformers import PeVideoModel, PeVideoConfig

>>> # Initializing a PeVideoModel style configuration
>>> configuration = PeVideoConfig()

>>> # Initializing a model from the pe-av-large style configuration
>>> model = PeVideoModel(configuration)

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

PeVideoEncoderConfig

class transformers.PeVideoEncoderConfig

< >

( 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 = Nonehidden_size: int = 1792intermediate_size: int = 4800num_hidden_layers: int = 6num_attention_heads: int = 14num_key_value_heads: int | None = Nonehead_dim: int = 128hidden_act: str = 'silu'max_position_embeddings: int = 10000initializer_range: float = 0.02rms_norm_eps: float = 1e-05rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falseattention_dropout: float | int = 0.0 )

パラメータ

  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig]、任意) — ビジョンバックボーンの config オブジェクトまたは辞書です。
  • hidden_size (int、任意、デフォルトは 1792) — 隠れ表現の次元数。
  • intermediate_size (int、任意、デフォルトは 4800) — MLP 表現の次元数。
  • num_hidden_layers (int、任意、デフォルトは 6) — Transformer デコーダーの隠れ層の数。
  • num_attention_heads (int、任意、デフォルトは 14) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。
  • num_key_value_heads (int, 任意) — 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、任意、デフォルトは 10000) — このモデルが使用される可能性のある最大シーケンス長です。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
  • rms_norm_eps (float、任意、デフォルト値は1e-05) — RMS正規化レイヤーで使用するepsilonです。
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 省略可) — RoPE 埋め込みの設定パラメータを含む辞書です。この辞書には rope_theta の値が含まれており、より長い max_position_embeddings で RoPE を使用する場合にスケーリングに使用されるパラメータが任意で含まれます。
  • attention_bias (bool、任意、デフォルトはFalse) — 自己注意機構において、クエリ、キー、バリュー、出力の投影層にバイアスを使用するかどうかを指定します。
  • attention_dropout (Union[float, int]、任意、デフォルトは 0.0) — アテンション確率のドロップアウト率です。

これは PeVideoModel の設定を保存するための設定クラスです。指定された引数に基づいて Pe Video モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、facebook/pe-av-large と同様の設定が得られます。

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

例:

>>> from transformers import PeAudioEncoder, PeAudioEncoderConfig

>>> # Initializing a PeAudioEncoder style configuration
>>> configuration = PeAudioEncoderConfig()

>>> # Initializing a model from the pe-av-large style configuration
>>> model = PeAudioEncoder(configuration)

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

PeVideoVideoProcessor

クラス transformers.PeVideoVideoProcessor

< >

( **kwargs: *<class 'transformers.processing_utils.VideosKwargs'> )

パラメータ

  • 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、任意、デフォルトは True) — size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうかを指定します。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, デフォルトは 2) — 画像のリサイズ時に使用するリサンプリングフィルタです。PILImageResampling の列挙型のいずれかを使用できます。do_resize が True に設定されている場合のみ、効果が現れます。
  • do_rescale (bool、kwargs、optional) — 画像をリスケールするかどうかを指定します。
  • rescale_factor (float、kwargs、任意、デフォルト値は 0.00392156862745098) — 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, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop を適用した後の出力画像のサイズ。
  • 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) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。
  • do_sample_frames (bool、kwargs、任意) — 処理前に動画からフレームをサンプリングするか、動画全体を処理するかどうかを指定します。
  • 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、任意、デフォルトは False) — 動画メタデータを返すかどうかを指定します。動画メタデータは、動画の長さ、fps、デコードバックエンドなどの情報を含むオブジェクトです。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 設定されている場合、特定のフレームワークのテンソルを返します。受け入れられる値は以下の通りです:
    • 'pt': PyTorchのtorch.Tensorオブジェクトを返します。
    • 'np': NumPyのnp.ndarrayオブジェクトを返します。
  • **kwargs (VideosKwargs、optional) — テキスト、画像、動画、音声の各モダリティに対する追加の処理オプション。モデル固有のパラメータは上記にリストされています。サポートされている引数の完全なリストについては、TypedDictクラスを参照してください。

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

PeVideoProcessor

class transformers.PeVideoProcessor

< >

( *args**kwargs )

PeVideoEncoder

class transformers.PeVideoEncoder

< >

( config: PeVideoEncoderConfig )

パラメータ

  • config (PeVideoEncoderConfig) — モデルのすべてのパラメータを含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。

PeVideo Encoder モデル。

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

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

forward

< >

( pixel_values_videos: Tensorpadding_mask_videos: typing.Optional[torch.Tensor] = None**kwargs ) → BaseModelOutputWithPooling or tuple(torch.FloatTensor)

パラメータ

  • pixel_values_videos (torch.Tensor、形状 (batch_size, num_frames, num_channels, frame_size, frame_size)) — 入力動画に対応するテンソルです。動画のピクセル値は、PeVideoVideoProcessor を使用して取得できます。詳細については、PeVideoVideoProcessor.call() を参照してください(PeVideoProcessor は動画の処理に PeVideoVideoProcessor を使用します)。
  • padding_mask_videos (torch.Tensor の形状 (batch_size, num_frames), 、任意) — パディングされた動画フレームに対してアテンションを実行しないためのマスク。マスクの値は [0, 1]:
    • マスクされていないフレームに対して1
    • マスクされたフレームは 0 です。

戻り値

BaseModelOutputWithPooling または tuple(torch.FloatTensor)

torch.FloatTensor のタプル(return_dict=False が渡された場合、または config.return_dict=False の場合)、または BaseModelOutputWithPooling。設定(PeVideoConfig)や入力に応じて、さまざまな要素で構成されます。

PeVideoEncoderのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

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

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

PeVideoModel

class transformers.PeVideoModel

< >

( config: PeVideoConfig )

forward

< >

( input_ids: Tensorpixel_values_videos: Tensorattention_mask: typing.Optional[torch.Tensor] = Nonepadding_mask_videos: typing.Optional[torch.Tensor] = Nonereturn_loss: bool | None = None**kwargs ) → PeVideoOutput or tuple(torch.FloatTensor)

パラメータ

  • input_ids (torch.Tensor の形状 (batch_size, sequence_length)) — 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。

    インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。

    入力IDとは何ですか?

  • pixel_values_videos (torch.Tensor、形状 (batch_size, num_frames, num_channels, frame_size, frame_size)) — 入力動画に対応するテンソルです。動画のピクセル値は、PeVideoVideoProcessor を使用して取得できます。詳細については、PeVideoVideoProcessor.call() を参照してください(PeVideoProcessor は動画の処理に PeVideoVideoProcessor を使用します)。
  • attention_mask (torch.Tensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

    アテンションマスクとは?

  • padding_mask_videos (torch.Tensor の形状 (batch_size, num_frames), 、任意) — パディングされた動画フレームに対してアテンションを実行しないためのマスク。マスクの値は [0, 1]:
    • マスクされていないフレームに対して1
    • マスクされたフレームは 0 です。
  • return_loss (bool, 任意) — 損失を返すかどうかを指定します。

戻り値

PeVideoOutput または tuple(torch.FloatTensor)

PeVideoOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(PeVideoConfig)と入力に応じて、さまざまな要素で構成されます。

PeVideoModelのforwardメソッドは、__call__特殊メソッドをオーバーライドします。

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

  • loss (torch.FloatTensor、shape (1,)、任意) — 動画とテキストの表現間で計算される対比損失。
  • logits_video_text (torch.FloatTensor、shape (batch_size, batch_size)、optional) — 動画とテキストの埋め込み間の類似度 logits。
  • text_video_embeds (torch.FloatTensor、shape (batch_size, hidden_size)、optional) — 動画・テキスト空間に射影されたテキスト埋め込み。
  • video_embeds (torch.FloatTensor、shape (batch_size, hidden_size)、任意) — video-text 空間に射影された動画の埋め込み。
  • text_outputs (BaseModelOutputWithPooling、任意) — テキストエンコーダーのモデル出力。最終隠れ状態とプーリング済み出力を含みます。
  • video_outputs (BaseModelOutputWithPooling、任意) — ビデオエンコーダーのモデル出力。最後の隠れ状態とプーリング済み出力を含みます。
Update on GitHub