Transformers documentation
Video Vision Transformer (ViViT)
このモデルは2021年3月29日にHF papersで公開され、2023年7月11日にHugging Face Transformersに貢献されました。
Video Vision Transformer (ViViT)
概要
Vivit モデルは、Anurag Arnab、Mostafa Dehghani、Georg Heigold、Chen Sun、Mario Lučić、Cordelia Schmid による ViViT: A Video Vision Transformer で提案されました。 この論文では、動画理解のための純粋な Transformer ベースのモデル群の初期の成功例の一つが提案されています。
論文の抄録は以下の通りです。
画像分類における最近の成功を踏まえ、動画分類のための純粋なTransformerベースのモデルを提案します。本モデルは入力動画から時空間トークンを抽出し、一連のTransformer層によってエンコードします。動画で遭遇する長いトークンシーケンスを処理するために、入力の空間次元と時間次元を因数分解する、いくつかの効率的なモデルバリアントを提案します。Transformerベースのモデルは、大規模な学習データセットが利用可能な場合のみ有効であることが知られていますが、学習時にモデルを効果的に正則化し、事前学習済みの画像モデルを活用することで、比較的小規模なデータセットでの学習が可能であることを示します。徹底的なアブレーション研究を行い、Kinetics 400および600、Epic Kitchens、Something-Something v2、Moments in Timeを含む複数の動画分類ベンチマークで最先端の結果を達成し、従来の深い3D畳み込みネットワークベースの手法を上回りました。
このモデルはjegormeisterによって提供されました。元のコード(JAXで記述)はこちらで確認できます。
Scaled Dot Product Attention (SDPA) の使用
PyTorchには、torch.nn.functionalの一部として、ネイティブのスケーリングドットプロダクトアテンション(SDPA)オペレーターが含まれています。この関数は、入力や使用しているハードウェアに応じて適用できる複数の実装を備えています。詳細については、公式ドキュメントまたはGPU推論ページを参照してください。
torch>=2.1.1 の場合、実装が利用可能な場合はデフォルトで SDPA が使用されますが、from_pretrained() で attn_implementation="sdpa" を設定することで、SDPA の使用を明示的に指定することもできます。
from transformers import VivitModel
model = VivitModel.from_pretrained("google/vivit-b-16x2-kinetics400", attn_implementation="sdpa", device_map="auto")
...最大限の高速化を実現するには、モデルを半精度(例: torch.float16 または torch.bfloat16)で読み込むことをお勧めします。
ローカル環境でのベンチマーク(A100-40GB、PyTorch 2.3.0、OS Ubuntu 22.04)において、float32 と google/vivit-b-16x2-kinetics400 モデルを使用した場合、推論時に以下の速度向上を確認しました。
トレーニング
| num_training_steps | batch_size | is cuda | 高速化率 (%) | Eager ピークメモリ (MB) | sdpa ピークメモリ (MB) | メモリ削減率(%) |
|---|---|---|---|---|---|---|
| 100 | 1 | True | 7.122 | 2575.28 | 5932.54 | 130.364 |
推論
| num_batches | batch_size | is cuda | は半分の | 高速化率 (%) | Mem eager (MB) | メモリ BT (MB) | メモリ削減率 (%) |
|---|---|---|---|---|---|---|---|
| 20 | 1 | True | False | 15.422 | 715.807 | 317.079 | 125.75 |
| 20 | 2 | True | False | 17.146 | 1234.75 | 447.175 | 176.122 |
| 20 | 4 | True | False | 18.093 | 2275.82 | 709.864 | 220.6 |
| 20 | 8 | True | False | 19.284 | 4358.19 | 1233.24 | 253.393 |
VivitConfig
class transformers.VivitConfig
< 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 = Noneimage_size: int | list[int] | tuple[int, int] = 224num_frames: int = 32tubelet_size: list[int] | tuple[int, ...] = (2, 16, 16)num_channels: int = 3hidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12intermediate_size: int = 3072hidden_act: str = 'gelu_fast'hidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-06qkv_bias: bool = Truepooler_output_size: int | None = Nonepooler_act: str = 'tanh' )
パラメータ
- image_size (
Union[int, list[int], tuple[int, int]]、任意、デフォルトは224) — 各画像のサイズ(解像度)。 - num_frames (
int, 任意、デフォルトは 32) — 各動画のフレーム数です。 - tubelet_size (
list[int]、任意、デフォルトは[2, 16, 16]) — 各チューブレットのサイズ(解像度)です。 - num_channels (
int、任意、デフォルトは3) — 入力チャネル数。 - hidden_size (
int、任意、デフォルトは768) — 隠れ表現の次元数。 - num_hidden_layers (
int、任意、デフォルトは12) — Transformer デコーダーの隠れ層の数。 - num_attention_heads (
int、任意、デフォルトは12) — Transformerデコーダーの各アテンション層におけるアテンションヘッドの数。 - intermediate_size (
int、任意、デフォルトは3072) — MLP 表現の次元数。 - hidden_act (
str、任意、デフォルトはgelu_fast) — デコーダーで使用する非線形活性化関数(関数または文字列)です。例えば、"gelu"、"relu"、"silu"などです。 - hidden_dropout_prob (
Union[float, int]、任意、デフォルト値は0.0) — embeddings、encoder、pooler 内のすべての全結合層における dropout 確率です。 - attention_probs_dropout_prob (
Union[float, int]、任意、デフォルトは0.0) — アテンション確率のドロップアウト率です。 - initializer_range (
float、任意、デフォルトは0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。 - layer_norm_eps (
float、任意、デフォルトは1e-06) — レイヤーノーマル層で使用する epsilon です。 - qkv_bias (
bool、省略可、デフォルトはTrue) — クエリ、キー、バリューにバイアスを追加するかどうか。 - pooler_output_size (
int, 任意) — プーラー層の次元数。None の場合、デフォルトでhidden_sizeになります。 - pooler_act (
str、任意、デフォルトは"tanh") — プーラーで使用する活性化関数です。
これはVivitModelの設定を保存するための設定クラスです。指定された引数に基づいてVivitモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、google/vivit-b-16x2-kinetics400と類似した設定が得られます。
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
例:
>>> from transformers import VivitConfig, VivitModel
>>> # Initializing a ViViT google/vivit-b-16x2-kinetics400 style configuration
>>> configuration = VivitConfig()
>>> # Initializing a model (with random weights) from the google/vivit-b-16x2-kinetics400 style configuration
>>> model = VivitModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configVivitImageProcessor
class transformers.VivitImageProcessor
< source >( do_resize: bool = Truesize: dict[str, int] | None = Noneresample: Resampling = <Resampling.BILINEAR: 2>do_center_crop: bool = Truecrop_size: dict[str, int] | None = Nonedo_rescale: bool = Truerescale_factor: int | float = 0.00784313725490196offset: bool = Truedo_normalize: bool = Trueimage_mean: float | list[float] | None = Noneimage_std: float | list[float] | None = None**kwargs )
パラメータ
- do_resize (
bool、省略可能、デフォルトはTrue) — 画像の (height, width) 次元を指定されたsizeにリサイズするかどうか。preprocessメソッドのdo_resizeパラメータによって上書きできます。 - size (
dict[str, int]省略可能、デフォルトは{"shortest_edge" -- 256}): リサイズ後の出力画像のサイズです。元の画像のアスペクト比を維持したまま、画像の短い辺をsize["shortest_edge"]にリサイズします。preprocessメソッド内のsizeによって上書きできます。 - resample (
PILImageResampling、任意、デフォルトはResampling.BILINEAR) — 画像のリサイズ時に使用するリサンプリングフィルタ。preprocessメソッドのresampleパラメータによって上書きできます。 - do_center_crop (
bool、任意、デフォルトはTrue) — 画像を指定されたcrop_sizeに中央クロップするかどうか。preprocessメソッドのdo_center_cropパラメータによって上書きできます。 - crop_size (
dict[str, int]、任意、デフォルトは{"height" -- 224, "width": 224}): 中央クロップを適用した後の画像サイズ。preprocessメソッドのcrop_sizeパラメータによって上書きできます。 - do_rescale (
bool、省略可能、デフォルトはTrue) — 指定されたスケーリング係数rescale_factorによって画像をリスケールするかどうか。preprocessメソッドのdo_rescaleパラメータによって上書きできます。 - rescale_factor (
intまたはfloat、任意、デフォルトは1/127.5) — 画像をリスケールする場合に使用するスケール係数を定義します。preprocessメソッドのrescale_factorパラメータによって上書きできます。 - offset (
bool、省略可能、デフォルトはTrue) — 画像を負方向と正方向の両方にスケーリングするかどうか。preprocessメソッド内のoffsetによって上書きできます。 - do_normalize (
bool、省略可能、デフォルトはTrue) — 画像を正規化するかどうかを指定します。preprocessメソッドのdo_normalizeパラメータによって上書きできます。 - image_mean (
floatまたはlist[float]、省略可、デフォルトはIMAGENET_STANDARD_MEAN) — 画像を正規化する場合に使用する平均値です。これは、画像のチャネル数と同じ長さの float または float のリストです。preprocessメソッドのimage_meanパラメータによって上書きできます。 - image_std (
floatまたはlist[float]、任意、デフォルトはIMAGENET_STANDARD_STD) — 画像を正規化する場合に使用する標準偏差です。これは、画像のチャネル数と同じ長さの float または float のリストです。preprocessメソッドのimage_stdパラメータによって上書きできます。
Vivit の画像プロセッサを構築します。
preprocess
< source >( videos: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]do_resize: bool | None = Nonesize: dict[str, int] | None = Noneresample: PIL.Image.Resampling | None = Nonedo_center_crop: bool | None = Nonecrop_size: dict[str, int] | None = Nonedo_rescale: bool | None = Nonerescale_factor: float | None = Noneoffset: bool | None = Nonedo_normalize: bool | None = Noneimage_mean: float | list[float] | None = Noneimage_std: float | list[float] | None = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = Nonedata_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'>input_data_format: str | transformers.image_utils.ChannelDimension | None = None )
パラメータ
- videos (
ImageInput) — 前処理対象の動画フレーム。ピクセル値が 0 から 255 の範囲にある、単一の動画フレームまたはバッチの動画フレームを想定しています。ピクセル値が 0 から 1 の範囲にあるフレームを渡す場合は、do_rescale=Falseを設定してください。 - do_resize (
bool、省略可能、デフォルトはself.do_resize) — 画像をリサイズするかどうかを指定します。 - size (
dict[str, int]、任意、デフォルトはself.size) — リサイズを適用した後の画像のサイズ。 - resample (
PILImageResampling、optional、デフォルトはself.resample) — 画像のリサイズ時に使用するリサンプリングフィルタです。PILImageResamplingの列挙型のいずれかになります。do_resizeがTrueに設定されている場合のみ有効です。 - do_center_crop (
bool、任意、デフォルトはself.do_centre_crop) — 画像を中央クロップするかどうかを指定します。 - crop_size (
dict[str, int]、任意、デフォルトはself.crop_size) — 中央クロップを適用した後の画像サイズ。 - do_rescale (
bool、任意、デフォルトはself.do_rescale) —offsetがTrueの場合、画像の値を[-1 - 1]に、それ以外の場合は[0, 1]にリスケールするかどうか。 - rescale_factor (
float、任意、デフォルトはself.rescale_factor) —do_rescaleがTrueに設定されている場合、画像をリスケールするための係数。 - offset (
bool、任意、デフォルトはself.offset) — 画像を負方向と正方向の両方にスケーリングするかどうか。 - do_normalize (
bool、省略可、デフォルトはself.do_normalize) — 画像を正規化するかどうかを指定します。 - image_mean (
floatまたはlist[float]、任意、デフォルトはself.image_mean) — 画像の平均値。 - image_std (
floatまたはlist[float]、任意、デフォルトはself.image_std) — 画像の標準偏差です。 - return_tensors (
strまたはTensorType, 省略可) — 返すテンソルの型。次のいずれかになります:- Unset:
np.ndarrayのリストを返します。 TensorType.PYTORCHまたは'pt':torch.Tensor型のバッチを返します。TensorType.NUMPYまたは'np':np.ndarray型のバッチを返します。
- Unset:
- data_format (
ChannelDimensionまたはstr, 省略可能, デフォルトはChannelDimension.FIRST) — 出力画像のチャネル次元の形式です。次のいずれかになります:ChannelDimension.FIRST: (num_channels, height, width) 形式の画像。ChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。- Unset: 入力画像の推定されたチャネル次元の形式を使用します。
- input_data_format (
ChannelDimensionまたはstr, 省略可) — 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推測されます。次のいずれかになります:"channels_first"またはChannelDimension.FIRST: (num_channels, height, width) 形式の画像。"channels_last"またはChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。"none"またはChannelDimension.NONE: (height, width) 形式の画像。
画像または画像のバッチを前処理します。
VivitVideoProcessor
class transformers.VivitVideoProcessor
< source >( **kwargs: *<class 'transformers.processing_utils.VideosKwargs'> )
パラメータ
- 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' -- 256}): モデルへの最大入力サイズを指定します。 - default_to_square (
bool、kwargs、任意、デフォルトはFalse) — size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, デフォルトは2) — 画像のリサイズ時に使用するリサンプリングフィルタです。PILImageResamplingの列挙型のいずれかを使用できます。do_resizeがTrueに設定されている場合のみ、効果が現れます。 - do_rescale (
bool、kwargs、任意、デフォルトはTrue) — 画像をリスケールするかどうかを指定します。 - rescale_factor (
float、kwargs、任意、デフォルト値は0.00784313725490196) —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_center_crop (
bool、kwargs、optional、デフォルトはTrue) — 画像を中央クロップするかどうか。 - do_pad (
bool, kwargs, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs、デフォルトは{'height' -- 224, 'width': 224}):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、任意、デフォルトはFalse) — 処理前に動画からフレームをサンプリングするか、動画全体を処理するかを指定します。 - 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クラスを参照してください。
VivitVideoProcessorのビデオプロセッサを構築します。
preprocess
< source >( 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'> ) → ~image_processing_base.BatchFeature
パラメータ
- 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、任意) — 画像を RGB に変換するかどうかを指定します。 - do_resize (
bool、kwargs、optional) — 画像をリサイズするかどうか。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — モデルへの最大入力次元を記述します。 - default_to_square (
bool、kwargs、任意) — サイズが整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。 - 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_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、optional) — 動画メタデータを返すかどうかを指定します。動画メタデータは、動画の長さ、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 を指定できます。
VivitModel
class transformers.VivitModel
< source >( config: VivitConfigadd_pooling_layer: bool = True )
パラメータ
- config (VivitConfig) — モデルのパラメータをすべて含むモデル設定クラス。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
- add_pooling_layer (
bool、省略可、デフォルトはTrue) — プーリング層を追加するかどうか
特定のヘッドを付加せず、生の隠れ状態を出力する素のVivitモデル。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( pixel_values: typing.Optional[torch.FloatTensor] = Noneinterpolate_pos_encoding: bool = Falseattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.FloatTensor)
パラメータ
- pixel_values (
torch.FloatTensor、形状(batch_size, num_channels, image_size, image_size)、任意) — 入力画像に対応するテンソルです。ピクセル値は VivitImageProcessor を使用して取得できます。詳細については VivitImageProcessor.call() を参照してください(processor_classは画像の処理に VivitImageProcessor を使用します)。 - interpolate_pos_encoding (
bool、省略可、デフォルトはFalse) — 事前学習済みの位置エンコーディングを補間するかどうかを指定します。 - attention_mask (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。[0, 1]:- マスクされていないトークンに対して1
- マスクされたトークンに対しては 0 です。
戻り値
BaseModelOutputWithPooling または tuple(torch.FloatTensor)
torch.FloatTensor のタプル(return_dict=False が渡された場合、または config.return_dict=False の場合)、または BaseModelOutputWithPooling。設定(VivitConfig)や入力に応じて、さまざまな要素で構成されます。
VivitModelの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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
例:
>>> import av
>>> import numpy as np
>>> from transformers import VivitImageProcessor, VivitModel
>>> from huggingface_hub import hf_hub_download
>>> np.random.seed(0)
>>> def read_video_pyav(container, indices):
... '''
... Decode the video with PyAV decoder.
... Args:
... container (`av.container.input.InputContainer`): PyAV container.
... indices (`list[int]`): List of frame indices to decode.
... Returns:
... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
... '''
... frames = []
... container.seek(0)
... start_index = indices[0]
... end_index = indices[-1]
... for i, frame in enumerate(container.decode(video=0)):
... if i > end_index:
... break
... if i >= start_index and i in indices:
... frames.append(frame)
... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
>>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
... '''
... Sample a given number of frame indices from the video.
... Args:
... clip_len (`int`): Total number of frames to sample.
... frame_sample_rate (`int`): Sample every n-th frame.
... seg_len (`int`): Maximum allowed index of sample's last frame.
... Returns:
... indices (`list[int]`): List of sampled frame indices
... '''
... converted_len = int(clip_len * frame_sample_rate)
... end_idx = np.random.randint(converted_len, seg_len)
... start_idx = end_idx - converted_len
... indices = np.linspace(start_idx, end_idx, num=clip_len)
... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
... return indices
>>> # video clip consists of 300 frames (10 seconds at 30 FPS)
>>> file_path = hf_hub_download(
... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)
>>> # sample 32 frames
>>> indices = sample_frame_indices(clip_len=32, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container=container, indices=indices)
>>> image_processor = VivitImageProcessor.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> model = VivitModel.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> # prepare video for the model
>>> inputs = image_processor(list(video), return_tensors="pt")
>>> # forward pass
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 3137, 768]VivitForVideoClassification
クラス transformers.VivitForVideoClassification
< source >( config: VivitConfig )
パラメータ
- config (VivitConfig) — モデルのパラメータをすべて含むモデル設定クラス。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
ViViT Transformerモデルの上部に動画分類ヘッド([CLS]トークンの最終隠れ状態の上に線形層を配置したもの)を備えた構成。例えばKinetics-400向け。
モデルの forward で
interpolate_pos_encodingをTrueに設定することで、ViT を学習時に使用した解像度よりも高い解像度の画像でファインチューニングすることが可能です。これにより、事前学習済みの位置埋め込みがより高い解像度に補間されます。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( pixel_values: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ImageClassifierOutput or tuple(torch.FloatTensor)
パラメータ
- pixel_values (
torch.FloatTensor、形状(batch_size, num_channels, image_size, image_size)、任意) — 入力画像に対応するテンソルです。ピクセル値は VivitImageProcessor を使用して取得できます。詳細については VivitImageProcessor.call() を参照してください(processor_classは画像の処理に VivitImageProcessor を使用します)。 - labels (
torch.LongTensor、shape(batch_size,)、任意) — 画像分類/回帰の損失を計算するためのラベル。インデックスは[0, ..., config.num_labels - 1]の範囲である必要があります。config.num_labels == 1の場合は回帰損失(平均二乗誤差)が計算され、config.num_labels > 1の場合は分類損失(クロスエントロピー)が計算されます。 - interpolate_pos_encoding (
bool、省略可、デフォルトはFalse) — 事前学習済みの位置エンコーディングを補間するかどうかを指定します。
戻り値
ImageClassifierOutput または tuple(torch.FloatTensor)
torch.FloatTensor のタプル、または ImageClassifierOutput(return_dict=False が渡された場合、または config.return_dict=False の場合)。設定(VivitConfig)や入力に応じて、さまざまな要素で構成されます。
VivitForVideoClassificationのforwardメソッドは、__call__特殊メソッドをオーバーライドします。
この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく
Moduleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。
loss (
torch.FloatTensor、shape(1,)、optional、labelsが指定された場合に返されます) — 分類損失(config.num_labels==1 の場合は回帰損失)。logits (
torch.FloatTensor、shape(batch_size, config.num_labels)) — SoftMax 適用前の分類スコア(config.num_labels==1 の場合は回帰スコア)。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)です。各ステージの出力におけるモデルの隠れ状態(特徴マップとも呼ばれます)。attentions (
tuple(torch.FloatTensor)、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます)—torch.FloatTensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, patch_size, sequence_length)。アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
例:
>>> import av
>>> import numpy as np
>>> import torch
>>> from transformers import VivitImageProcessor, VivitForVideoClassification
>>> from huggingface_hub import hf_hub_download
>>> np.random.seed(0)
>>> def read_video_pyav(container, indices):
... '''
... Decode the video with PyAV decoder.
... Args:
... container (`av.container.input.InputContainer`): PyAV container.
... indices (`list[int]`): List of frame indices to decode.
... Returns:
... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
... '''
... frames = []
... container.seek(0)
... start_index = indices[0]
... end_index = indices[-1]
... for i, frame in enumerate(container.decode(video=0)):
... if i > end_index:
... break
... if i >= start_index and i in indices:
... frames.append(frame)
... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
>>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
... '''
... Sample a given number of frame indices from the video.
... Args:
... clip_len (`int`): Total number of frames to sample.
... frame_sample_rate (`int`): Sample every n-th frame.
... seg_len (`int`): Maximum allowed index of sample's last frame.
... Returns:
... indices (`list[int]`): List of sampled frame indices
... '''
... converted_len = int(clip_len * frame_sample_rate)
... end_idx = np.random.randint(converted_len, seg_len)
... start_idx = end_idx - converted_len
... indices = np.linspace(start_idx, end_idx, num=clip_len)
... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
... return indices
>>> # video clip consists of 300 frames (10 seconds at 30 FPS)
>>> file_path = hf_hub_download(
... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)
>>> # sample 32 frames
>>> indices = sample_frame_indices(clip_len=32, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container=container, indices=indices)
>>> image_processor = VivitImageProcessor.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> model = VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> inputs = image_processor(list(video), return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
... logits = outputs.logits
>>> # model predicts one of the 400 Kinetics-400 classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
LABEL_116