Transformers documentation

SAM2 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年8月14日にHugging Face Transformersに貢献されました。

SAM2 Video

SDPA FlashAttention

概要

SAM2 (Segment Anything Model 2) は、Nikhila Ravi、Valentin Gabeur、Yuan-Ting Hu、Ronghang Hu、Chaitanya Ryali、Tengyu Ma、Haitham Khedr、Roman Rädle、Chloe Rolland、Laura Gustafson、Eric Mintun、Junting Pan、Kalyan Vasudev Alwala、Nicolas Carion、Chao-Yuan Wu、Ross Girshick、Piotr Dollár、Christoph Feichtenhofer によって、Segment Anything in Images and Videos で提案されました。

モデルは、入力画像または動画、および入力されたポイントまたはバウンディングボックスを指定することで、対象とする任意のオブジェクトのセグメンテーションマスクを予測するために使用できます。

example image

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

画像および動画におけるプロンプト可能な視覚セグメンテーションの解決に向けた基盤モデルであるSegment Anything Model 2 (SAM 2) を紹介します。ユーザーとのインタラクションを通じてモデルとデータを改善するデータエンジンを構築し、これまでに収集された最大規模の動画セグメンテーションデータセットを収集しました。当社のモデルは、リアルタイムの動画処理に対応するストリーミングメモリを備えたシンプルなtransformerアーキテクチャです。当社のデータで訓練されたSAM 2は、幅広いタスクで優れたパフォーマンスを発揮します。動画セグメンテーションでは、従来の手法よりも3分の1のインタラクション数で、より高い精度を実現しています。画像セグメンテーションでは、Segment Anything Model (SAM) よりも精度が高く、6倍速く動作します。当社のデータ、モデル、および知見は、動画セグメンテーションおよび関連する知覚タスクにとって重要なマイルストーンとなるものと確信しています。モデルのバージョン、データセット、およびインタラクティブなデモを公開します。

ヒント:

  • Batch & Video Support: SAM2 はバッチ処理とシームレスな動画セグメンテーションをネイティブでサポートする一方、オリジナルの SAM は静的な画像と、1枚ずつ処理するシンプルなワークフロー向けに設計されています。
  • Accuracy & Generalization: SAM2は、元のSAMと比較して、特に混合プロンプトを使用した場合に、セグメンテーションの品質、ロバストネス、および新しいドメインへのゼロショット汎化性能が向上しています。

このモデルは、sangbumchoi と yonigozlan によって提供されました。 元のコードはこちらで確認できます。

使用例

Video Segmentation and Tracking

SAM2の最大の強みは、動画フレーム間でオブジェクトを追跡できる点です。動画セグメンテーションにSAM2を使用する方法は以下の通りです。

基本的なビデオトラッキング

from transformers import Sam2VideoModel, Sam2VideoProcessor
import torch

model = Sam2VideoModel.from_pretrained("facebook/sam2.1-hiera-tiny", device_map="auto")
processor = Sam2VideoProcessor.from_pretrained("facebook/sam2.1-hiera-tiny")

# Load video frames (example assumes you have a list of PIL Images)
# video_frames = [Image.open(f"frame_{i:05d}.jpg") for i in range(num_frames)]

# For this example, we'll use the video loading utility
from transformers.video_utils import load_video
video_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/bedroom.mp4"
video_frames, _ = load_video(video_url)

# Initialize video inference session
inference_session = processor.init_video_session(
    video=video_frames,
    inference_device=device,
)

# Add click on first frame to select object
ann_frame_idx = 0
ann_obj_id = 1
points = [[[[210, 350]]]]
labels = [[[1]]]

processor.add_inputs_to_inference_session(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
    obj_ids=ann_obj_id,
    input_points=points,
    input_labels=labels,
)

# Segment the object on the first frame
outputs = model(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
)
video_res_masks = processor.post_process_masks(
    [outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
)[0]
print(f"Segmentation shape: {video_res_masks.shape}")
Segmentation shape: torch.Size([1, 1, 480, 854])

# Propagate through the entire video
video_segments = {}
for sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_video_output.frame_idx] = video_res_masks

print(f"Tracked object through {len(video_segments)} frames")
Tracked object through 180 frames

マルチオブジェクト・ビデオトラッキング

動画フレーム間で複数のオブジェクトを同時にトラッキングします:

# Reset for new tracking session
inference_session.reset_inference_session()

# Add multiple objects on the first frame
ann_frame_idx = 0
obj_ids = [2, 3]
input_points = [[[[200, 300]], [[400, 150]]]]  # Points for two objects (batched)
input_labels = [[[1], [1]]]

processor.add_inputs_to_inference_session(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
    obj_ids=obj_ids,
    input_points=input_points,
    input_labels=input_labels,
)

# Get masks for both objects on first frame
outputs = model(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
)

# Propagate both objects through video
video_segments = {}
for sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_video_output.frame_idx] = {
        obj_id: video_res_masks[i]
        for i, obj_id in enumerate(inference_session.obj_ids)
    }

print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")
Tracked 2 objects through 180 frames

動画セグメンテーションの洗練

任意のフレームに追加のクリックを追加して、トラッキングを微調整できます:

# Add refinement click on a later frame
refine_frame_idx = 50
ann_obj_id = 2  # Refining first object
points = [[[[220, 280]]]]  # Additional point
labels = [[[1]]]  # Positive click

processor.add_inputs_to_inference_session(
    inference_session=inference_session,
    frame_idx=refine_frame_idx,
    obj_ids=ann_obj_id,
    input_points=points,
    input_labels=labels,
)

# Re-propagate with the additional information
video_segments = {}
for sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_video_output.frame_idx] = video_res_masks

ストリーミング動画推論

リアルタイムアプリケーション向けに、SAM2はフレームが到着するたびに動画フレームを処理することをサポートしています:

# Initialize session for streaming
inference_session = processor.init_video_session(
    inference_device=device,
)

# Process frames one by one
for frame_idx, frame in enumerate(video_frames[:10]):  # Process first 10 frames
    inputs = processor(images=frame, device=device, return_tensors="pt").to(model.device)
...
    if frame_idx == 0:
        # Add point input on first frame
        processor.add_inputs_to_inference_session(
            inference_session=inference_session,
            frame_idx=0,
            obj_ids=1,
            input_points=[[[[210, 350], [250, 220]]]],
            input_labels=[[[1, 1]]],
            original_size=inputs.original_sizes[0], # need to be provided when using streaming video inference
        )
...
    # Process current frame
    sam2_video_output = model(inference_session=inference_session, frame=inputs.pixel_values[0])
...
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=inputs.original_sizes, binarize=False
    )[0]
    print(f"Frame {frame_idx}: mask shape {video_res_masks.shape}")

複数のオブジェクト向けのビデオバッチ処理

をすべて一度に追加して、動画内の複数のオブジェクトを同時にトラッキングします:

# Initialize video session
inference_session = processor.init_video_session(
    video=video_frames,
    inference_device=device,
)

# Add multiple objects on the first frame using batch processing
ann_frame_idx = 0
obj_ids = [2, 3]  # Track two different objects
input_points = [
    [[[200, 300], [230, 250], [275, 175]], [[400, 150]]]
]  # Object 2: 3 points (2 positive, 1 negative); Object 3: 1 point
input_labels = [
    [[1, 1, 0], [1]]
]  # Object 2: positive, positive, negative; Object 3: positive

processor.add_inputs_to_inference_session(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
    obj_ids=obj_ids,
    input_points=input_points,
    input_labels=input_labels,
)

# Get masks for all objects on the first frame
outputs = model(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
)
video_res_masks = processor.post_process_masks(
    [outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
)[0]
print(f"Generated masks for {video_res_masks.shape[0]} objects")
Generated masks for 2 objects

# Propagate all objects through the video
video_segments = {}
for sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_video_output.frame_idx] = {
        obj_id: video_res_masks[i]
        for i, obj_id in enumerate(inference_session.obj_ids)
    }

print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")
Tracked 2 objects through 180 frames

リソース

SAMの入門を支援するための、Hugging Face公式およびコミュニティ(🌎で示す)のリソースのリストです。

Sam2VideoConfig

class transformers.Sam2VideoConfig

< >

( 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 = Noneprompt_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonemask_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneinitializer_range: float = 0.02num_maskmem: int = 7image_size: int | list[int] | tuple[int, int] = 1024sigmoid_scale_for_mem_enc: float = 20.0sigmoid_bias_for_mem_enc: float = -10.0enable_occlusion_spatial_embedding: bool = Truemultimask_output_in_sam: bool = Truemultimask_min_pt_num: int = 0multimask_max_pt_num: int = 1multimask_output_for_tracking: bool = Truemax_object_pointers_in_encoder: int = 16max_cond_frame_num: int = -1enable_temporal_pos_encoding_for_object_pointers: bool = Truememory_attention_hidden_size: int = 256memory_attention_num_layers: int = 4memory_attention_num_attention_heads: int = 1memory_attention_downsample_rate: int = 1memory_attention_feed_forward_hidden_size: int = 2048memory_attention_feed_forward_hidden_act: str = 'relu'memory_attention_dropout: float | int = 0.1memory_attention_rope_feat_sizes: list[int] | None = Nonememory_attention_rope_dropout: float | int = 0.1memory_encoder_hidden_size: int = 256memory_encoder_output_channels: int = 64rope_parameters: dict | None = Nonemask_downsampler_embed_dim: int = 256mask_downsampler_kernel_size: int = 3mask_downsampler_stride: int = 2mask_downsampler_padding: int = 1mask_downsampler_total_stride: int = 16mask_downsampler_hidden_act: str = 'gelu'memory_fuser_num_layers: int = 2memory_fuser_embed_dim: int = 256memory_fuser_intermediate_dim: int = 1024memory_fuser_kernel_size: int = 7memory_fuser_padding: int = 3memory_fuser_layer_scale_init_value: float = 1e-06memory_fuser_hidden_act: str = 'gelu' )

パラメータ

  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig]、任意) — ビジョンバックボーンの config オブジェクトまたは辞書です。
  • prompt_encoder_config (Union[dict, Sam2PromptEncoderConfig], 省略可) — Sam2PromptEncoderConfigを初期化するために使用される設定オプションの辞書。
  • mask_decoder_config (Union[dict, Sam2MaskDecoderConfig], 省略可) — Sam2MaskDecoderConfigを初期化するために使用される設定オプションの辞書です。
  • initializer_range (float、任意、デフォルト値は 0.02) — パラメータ初期化の標準偏差。
  • num_maskmem (int、任意、デフォルト値は 7)— マスクメモリ用のメモリスロットの数。
  • image_size (Union[int, list[int], tuple[int, int]]、任意、デフォルトは 1024) — 各画像のサイズ(解像度)です。
  • sigmoid_scale_for_mem_enc (float、任意、デフォルト値は 20.0) — メモリエンコーダーにおけるシグモイド関数のスケール係数です。
  • sigmoid_bias_for_mem_enc (float、任意、デフォルト値は -10.0) — メモリエンコーダーにおけるシグモイド関数のバイアスです。
  • enable_occlusion_spatial_embedding (bool、任意、デフォルトは True) — オクルージョンに対して空間埋め込みを有効にするかどうか。
  • multimask_output_in_sam (bool、任意、デフォルトは True) — SAM ヘッドから複数のマスクを出力するかどうかを指定します。
  • multimask_min_pt_num (int、任意、デフォルト値は 0)— マルチマスク出力をトリガーするための最小ポイント数です。
  • multimask_max_pt_num (int、任意、デフォルト値は 1)— マルチマスク出力をトリガーする最大ポイント数です。
  • multimask_output_for_tracking (bool、任意、デフォルトは True) — トラッキングにマルチマスク出力を使用するかどうか。
  • max_object_pointers_in_encoder (int、任意、デフォルト値は 16)— エンコーダー内のオブジェクトポインタの最大数。
  • max_cond_frame_num (int、任意、デフォルトは -1) — メモリアテンションで使用する条件付けフレームの最大数です。すべての条件付けフレームを使用するには -1 を設定してください。
  • enable_temporal_pos_encoding_for_object_pointers (bool、任意、デフォルトは True) — オブジェクトポインタに対して時間的位置エンコーディングを有効にするかどうか。
  • memory_attention_hidden_size (int、任意、デフォルトは 256) — メモリアテンションの隠れ状態の次元数です。
  • memory_attention_num_layers (int、任意、デフォルトは 4) — メモリアテンションモジュールの層数です。
  • memory_attention_num_attention_heads (int、任意、デフォルトは 1) — メモリアテンションにおける各アテンションレイヤーのアテンションヘッド数。
  • memory_attention_downsample_rate (int、任意、デフォルトは 1) — アテンション層のダウンサンプル率です。
  • memory_attention_feed_forward_hidden_size (int、任意、デフォルト値は 2048) — メモリアテンションモジュールにおけるフィードフォワードネットワークの次元数です。
  • memory_attention_feed_forward_hidden_act (str、任意、デフォルトは "relu") — メモリアテンションモジュール内のフィードフォワードネットワークで使用する非線形活性化関数です。
  • memory_attention_dropout (float、任意、デフォルトは 0.1) — メモリアテンションモジュールのドロップアウト率です。
  • memory_attention_rope_feat_sizes (list[int]、任意、デフォルトは [64, 64]) — Rope 位置エンコーディングのフィーチャサイズです。
  • memory_attention_rope_dropout (float、任意、デフォルト値は 0.1) — Rope 位置エンコーディングの dropout 率です。
  • memory_encoder_hidden_size (int、任意、デフォルトは 256) — メモリエンコーダーの隠れ状態の次元数。
  • memory_encoder_output_channels (int, 任意、デフォルトは 64) — メモリエンコーダーの出力チャネル数です。
  • rope_parameters (dict, 任意) — RoPE 埋め込みの設定パラメータを含む辞書です。辞書には rope_theta の値が含まれており、より長い max_position_embeddings で RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。
  • mask_downsampler_embed_dim (int、任意、デフォルトは 256) — マスクダウンスAMPLERの埋め込みの次元数。
  • mask_downsampler_kernel_size (int、任意、デフォルトは 3) — マスクダウンスAMPLERのカーネルサイズです。
  • mask_downsampler_stride (int、任意、デフォルトは 2) — マスクダウンサンプラーのストライドです。
  • mask_downsampler_padding (int、任意、デフォルト値は 1) — マスクダウンサンプラーのパディングです。
  • mask_downsampler_total_stride (int、任意、デフォルト値は 16)— マスクダウンスAMPLERの総ストライドです。
  • mask_downsampler_hidden_act (str、任意、デフォルトは"gelu") — マスクダウンスAMPLERにおける非線形活性化関数です。
  • memory_fuser_num_layers (int、任意、デフォルトは 2)— memory fuser のレイヤー数です。
  • memory_fuser_embed_dim (int、任意、デフォルト値は 256) — memory fuser の埋め込み層の次元数です。
  • memory_fuser_intermediate_dim (int、任意、デフォルトは 1024) — memory fuser の中間層の次元数です。
  • memory_fuser_kernel_size (int、任意、デフォルトは 7) — memory fuser のカーネルサイズです。
  • memory_fuser_padding (int、任意、デフォルトは 3) — memory fuser のパディングです。
  • memory_fuser_layer_scale_init_value (float、任意、デフォルトは 1e-06) — memory fuser のレイヤースケールの初期値です。
  • memory_fuser_hidden_act (str、任意、デフォルトは"gelu") — memory fuserで使用する非線形活性化関数です。

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

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

例:

>>> from transformers import (
...     Sam2VisionConfig,
...     Sam2PromptEncoderConfig,
...     Sam2MaskDecoderConfig,
...     Sam2Model,
... )

>>> # Initializing a Sam2Config with `"facebook/sam2.1_hiera_tiny"` style configuration
>>> configuration = Sam2Config()

>>> # Initializing a Sam2Model (with random weights) from the `"facebook/sam2.1_hiera_tiny"` style configuration
>>> model = Sam2Model(configuration)

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

>>> # We can also initialize a Sam2Config from a Sam2VisionConfig, Sam2PromptEncoderConfig, and Sam2MaskDecoderConfig

>>> # Initializing SAM2 vision encoder, memory attention, and memory encoder configurations
>>> vision_config = Sam2VisionConfig()
>>> prompt_encoder_config = Sam2PromptEncoderConfig()
>>> mask_decoder_config = Sam2MaskDecoderConfig()

>>> config = Sam2Config(vision_config, prompt_encoder_config, mask_decoder_config)

Sam2VideoMaskDecoderConfig

クラス transformers.Sam2VideoMaskDecoderConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 256hidden_act: str = 'gelu'mlp_dim: int = 2048num_hidden_layers: int = 2num_attention_heads: int = 8attention_downsample_rate: int = 2num_multimask_outputs: int = 3iou_head_depth: int = 3iou_head_hidden_dim: int = 256dynamic_multimask_via_stability: bool = Truedynamic_multimask_stability_delta: float = 0.05dynamic_multimask_stability_thresh: float = 0.98 )

パラメータ

  • hidden_size (int、任意、デフォルトは 256) — 隠れ表現の次元数。
  • hidden_act (str、任意、デフォルトは gelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、 "relu"、"silu" など。
  • mlp_dim (int、任意、デフォルトは 2048) — 2 方向 Transformer における MLP の次元数です。
  • num_hidden_layers (int、任意、デフォルトは2) — Transformerデコーダーの隠れ層の数。
  • num_attention_heads (int、任意、デフォルトは 8) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。
  • attention_downsample_rate (int、任意、デフォルトは 2) — アテンション層のダウンサンプル率です。
  • num_multimask_outputs (int、任意、デフォルトは 3) — マルチマスク出力の数です。
  • iou_head_depth (int、任意、デフォルト値は 3) — IoU ヘッドの深さです。
  • iou_head_hidden_dim (int、任意、デフォルトは 256) — IoU ヘッドの隠れ層の次元数です。
  • dynamic_multimask_via_stability (bool、省略可、デフォルトは True) — stability を用いた動的マルチマスクを使用するかどうかを指定します。
  • dynamic_multimask_stability_delta (float、任意、デフォルト値は 0.05) — 動的マルチマスクの安定性デルタです。
  • dynamic_multimask_stability_thresh (float、任意、デフォルト値は 0.98) — 動的マルチマスクの安定性しきい値です。

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

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

Sam2VideoPromptEncoderConfig

class transformers.Sam2VideoPromptEncoderConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 256image_size: int | list[int] | tuple[int, int] = 1024patch_size: int | list[int] | tuple[int, int] = 16mask_input_channels: int = 16num_point_embeddings: int = 4hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06scale: int = 1 )

パラメータ

  • hidden_size (int、任意、デフォルトは 256) — 隠れ表現の次元数。
  • image_size (Union[int, list[int], tuple[int, int]]、任意、デフォルトは 1024) — 各画像のサイズ(解像度)です。
  • patch_size (Union[int, list[int], tuple[int, int]]、任意、デフォルトは16) — 各パッチのサイズ(解像度)です。
  • mask_input_channels (int、任意、デフォルトは 16)— MaskDecoder モジュールに渡すチャネル数です。
  • num_point_embeddings (int、任意、デフォルトは 4) — 使用する point embeddings の数です。
  • hidden_act (str、任意、デフォルトは gelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、 "relu"、"silu" など。
  • layer_norm_eps (float、任意、デフォルトは 1e-06) — レイヤーノーマル層で使用する epsilon です。
  • scale (float、任意、デフォルトは 1) — プロンプトエンコーダーのスケール係数です。

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

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

Sam2VideoProcessor

class transformers.Sam2VideoProcessor

< >

( image_processorvideo_processortarget_size: int | None = Nonepoint_pad_value: int = -10**kwargs )

パラメータ

  • image_processor (Sam2ImageProcessor) — 画像プロセッサは必須の入力です。
  • video_processor (Sam2VideoVideoProcessor) — 動画プロセッサは必須の入力です。
  • target_size (int, 任意) — 入力ポイントとバウンディングボックスを正規化するためのターゲットサイズ(ピクセル単位)です。指定されない場合、デフォルトでは画像プロセッサのサイズ設定が使用されます。すべての入力座標(ポイントとボックス)は、モデルに渡される前にこのサイズに正規化されます。これにより、元の画像の寸法に関係なく、座標の表現が常に一貫したものになります。
  • point_pad_value (int、任意、デフォルトは -10) — 長さの異なるシーケンスをバッチ処理する際に、入力ポイントのパディングに使用される値です。この値はパディングされた位置をマークするために使用され、座標正規化の間も保持されます。

画像プロセッサと動画プロセッサを単一のプロセッサにラップするSam2VideoProcessorを構築します。

Sam2VideoProcessor は、Sam2ImageProcessor と Sam2VideoVideoProcessor のすべての機能を提供します。詳細については、~Sam2ImageProcessor および ~Sam2VideoVideoProcessor を参照してください。

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonesegmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Noneinput_points: typing.Union[list[list[list[list[float]]]], torch.Tensor, NoneType] = Noneinput_labels: typing.Union[list[list[list[int]]], torch.Tensor, NoneType] = Noneinput_boxes: typing.Union[list[list[list[float]]], torch.Tensor, NoneType] = Noneoriginal_sizes: typing.Union[list[list[float]], torch.Tensor, NoneType] = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = None**kwargs ) → A BatchEncoding with the following fields

パラメータ

  • 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 を設定してください。
  • segmentation_maps (ImageInput、任意) — 処理対象のセグメンテーションマップです。
  • input_points (list[list[list[list[float]]]]、torch.Tensor、省略可) — フレームに追加する点です。
  • input_labels (list[list[list[int]]]、torch.Tensor、省略可) — ポイントのラベルです。
  • input_boxes (list[list[list[float]]]、torch.Tensor、省略可) — フレームに追加するバウンディングボックスです。
  • original_sizes (list[list[float]]、torch.Tensor、省略可) — 画像の元のサイズです。
  • return_tensors (Union[str, ~utils.generic.TensorType], 省略可能) — 設定すると、特定のフレームワークのテンソルを返します。受け入れられる値は以下の通りです:
    • 'pt': PyTorchのtorch.Tensorオブジェクトを返します。
    • 'np': NumPyのnp.ndarrayオブジェクトを返します。

戻り値

以下のフィールドを持つBatchEncoding

  • pixel_values (torch.Tensor): 処理された画像。
  • original_sizes (list[list[float]]): 画像の元のサイズ。
  • labels (torch.Tensor): 処理済みのセグメンテーションマップ(指定されている場合)。
  • input_points (torch.Tensor): 処理済みのポイント。
  • input_labels (torch.Tensor): 処理済みのラベル。
  • input_boxes (torch.Tensor): 処理済みのバウンディングボックス。

post_process_masks

< >

( masksoriginal_sizesmask_threshold = 0.0binarize = Truemax_hole_area = 0.0max_sprinkle_area = 0.0apply_non_overlapping_constraints = False**kwargs ) → (torch.Tensor)

パラメータ

  • masks (Union[List[torch.Tensor], List[np.ndarray]]) — mask_decoder からのバッチ化されたマスク。形式は (batch_size, num_channels, height, width) です。
  • original_sizes (Union[torch.Tensor, List[Tuple[int,int]]]) — モデルが期待する入力形状にリサイズされる前の、各画像の元のサイズです。形式は (高さ, 幅) です。
  • mask_threshold (float、任意、デフォルト値は 0.0) — 二値化および後処理操作の閾値。
  • binarize (bool、省略可能、デフォルトは True) — マスクをバイナリ化するかどうかを指定します。
  • max_hole_area (float、任意、デフォルト値は 0.0)— 埋める穴の最大面積です。
  • max_sprinkle_area (float、任意、デフォルト値は 0.0) — 塗りつぶす sprinkle の最大面積です。
  • apply_non_overlapping_constraints (bool、省略可能、デフォルトはFalse) — マスクに非重複制約を適用するかどうか。

戻り値

(torch.Tensor)

batch_size, num_channels, height, width形式のバッチ化されたマスク。ここで、(height, width)はoriginal_sizeによって指定されます。

パディングを除去し、マスクを元の画像サイズにアップスケールします。

init_video_session

< >

( video: 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] = Noneinference_device: typing.Union[str, ForwardRef('torch.device')] = 'cpu'inference_state_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Noneprocessing_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Nonevideo_storage_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Nonemax_vision_features_cache_size: int = 1dtype: dtype = torch.float32 )

パラメータ

  • video (VideoInput、任意) — 処理対象の動画です。ストリーミングの場合は指定する必要はありません。
  • inference_device (str または torch.device、任意、デフォルトは “cpu”) — 推論に使用するデバイス。
  • inference_state_device (str または torch.device、省略可) — 推論状態を保存するデバイス。
  • processing_device (str または torch.device、省略可) — 動画処理に使用するデバイス。
  • video_storage_device (str または torch.device、省略可) — 処理済みの動画フレームを保存するデバイス。
  • max_vision_features_cache_size (int、任意、デフォルト値は 1)— キャッシュするビジョン特徴の最大数です。
  • dtype (torch.dtype、任意、デフォルトは torch.float32) — セッション全体で使用する torch の dtype。

推論用のビデオセッションを初期化します。 ビデオが提供されている場合(非同期推論)、そのビデオは処理され、video_storage_deviceに保存されます。

add_inputs_to_inference_session

< >

( inference_session: Sam2VideoInferenceSessionframe_idx: intobj_ids: list[int] | intinput_points: typing.Union[list[list[list[list[float]]]], torch.Tensor, NoneType] = Noneinput_labels: typing.Union[list[list[list[int]]], torch.Tensor, NoneType] = Noneinput_boxes: typing.Union[list[list[list[float]]], torch.Tensor, NoneType] = Noneinput_masks: typing.Union[numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneoriginal_size: tuple[int, int] | None = Noneclear_old_inputs: bool = True )

パラメータ

  • inference_session (Sam2VideoInferenceSession) — 動画用の推論セッションです。
  • frame_idx (int) — 処理するフレームのインデックスです。
  • obj_ids (list[int] または int) — 点またはボックスに関連付けるオブジェクト ID です。 任意の整数を指定でき、後でオブジェクトを特定するために再利用できます。
  • input_points (list[list[list[list[float]]]]、torch.Tensor、省略可) — フレームに追加する点です。
  • input_labels (list[list[list[int]]]、torch.Tensor、省略可) — ポイントのラベルです。
  • input_boxes (list[list[list[float]]]、torch.Tensor、省略可) — フレームに追加するバウンディングボックスです。
  • input_masks (np.ndarray、torch.Tensor、list[np.ndarray]、または list[torch.Tensor]、任意) — フレームに追加するマスクです。
  • original_size (tuple[int, int]、省略可) — 動画の元のサイズです。ストリーミングを行う場合は指定してください。
  • clear_old_inputs (bool、省略可能、デフォルトはTrue) — オブジェクトの古い入力をクリアするかどうかを指定します。

動画フレームの新しい点、ボックス、またはマスクを処理し、推論セッションに追加します。

Sam2VideoVideoProcessor

class transformers.Sam2VideoVideoProcessor

< >

( **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、デフォルトは {'height' -- 1024, 'width': 1024}): モデルへの最大入力サイズを指定します。
  • 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、任意、デフォルトはTrue) — 画像をリスケールするかどうかを指定します。
  • rescale_factor (float、kwargs、任意、デフォルト値は 0.00392156862745098) — do_rescale が True に設定されている場合、画像をリスケールするための係数です。
  • do_normalize (bool、kwargs、optional、デフォルトはTrue) — 画像を正規化するかどうかを指定します。
  • image_mean (Union[float, list[float], tuple[float, ...]]、kwargs、optional、デフォルト値は [0.485, 0.456, 0.406]) — 正規化に使用する画像の平均値。do_normalize が True に設定されている場合のみ有効です。
  • image_std (Union[float, list[float], tuple[float, ...]]、kwargs、optional、デフォルト値は [0.229, 0.224, 0.225]) — 正規化に使用する画像の標準偏差。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クラスを参照してください。

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

post_process_masks

< >

( masksoriginal_sizesreshaped_input_sizesmask_threshold = 0.0binarize = Truepad_size = None ) → (torch.Tensor)

パラメータ

  • masks (Union[List[torch.Tensor], List[np.ndarray]]) — mask_decoder からのバッチ化されたマスク。形式は (batch_size, num_channels, height, width) です。
  • original_sizes (Union[torch.Tensor, List[Tuple[int,int]]]) — モデルが期待する入力形状にリサイズされる前の、各画像の元のサイズです。形式は (高さ, 幅) です。
  • reshaped_input_sizes (Union[torch.Tensor, List[Tuple[int,int]]]) — モデルに投入される各画像のサイズです。形式は (height, width) です。パディングの除去に使用されます。
  • mask_threshold (float、省略可、デフォルトは 0.0) — マスクを二値化するために使用する閾値。
  • binarize (bool、省略可能、デフォルトは True) — マスクをバイナリ化するかどうかを指定します。
  • pad_size (int、任意、デフォルトは self.pad_size) — モデルに渡される前に画像がパディングされた後のターゲットサイズです。None の場合、ターゲットサイズはプロセッサの pad_size であると仮定されます。

戻り値

(torch.Tensor)

batch_size, num_channels, height, width形式のバッチ化されたマスク。ここで、(height, width)はoriginal_sizeによって指定されます。

パディングを除去し、マスクを元の画像サイズにアップスケールします。

Sam2VideoInferenceSession

class transformers.Sam2VideoInferenceSession

< >

( video: typing.Optional[torch.FloatTensor] = Nonevideo_height: int | None = Nonevideo_width: int | None = Noneinference_device: typing.Union[torch.device, str] = 'cpu'inference_state_device: typing.Union[torch.device, str] = 'cpu'video_storage_device: typing.Union[torch.device, str] = 'cpu'dtype: typing.Union[torch.dtype, str] = 'float32'max_vision_features_cache_size: int = 1 )

パラメータ

  • video (torch.FloatTensor、任意) — 処理対象の動画です。ストリーミング時には指定する必要はありません。
  • video_height (int、任意) — 動画の高さ。
  • video_width (int、任意) — 動画の幅です。
  • inference_device (torch.device、任意、デフォルトは "cpu") — 推論に使用するデバイス。
  • inference_state_device (torch.device、任意、デフォルトは "cpu") — 推論状態を保存するデバイスです。
  • video_storage_device (torch.device、任意、デフォルトは "cpu") — 動画を保存するデバイスです。
  • dtype (torch.dtype、任意、デフォルトは "float32") — 動画に使用する dtype です。
  • max_vision_features_cache_size (int、任意、デフォルト値は 1)— キャッシュするビジョン特徴の最大数です。

動画推論セッションのパラメータ、状態、およびキャッシュを管理します。

add_mask_inputs

< >

( obj_idx: intframe_idx: intinputs: Tensor )

自動的なデバイス配置を備えたマスク入力を追加します。

add_new_frame

< >

( pixel_values: Tensorframe_idx: int | None = None )

自動的なデバイス配置で新しいフレームを追加します。

add_point_inputs

< >

( obj_idx: intframe_idx: intinputs: dict )

自動的なデバイス配置を備えたポイント入力を追加します。

get_frame

< >

( frame_idx: int )

動画からフレームを取得します。

get_obj_num

< >

( )

このセッションでこれまでに受信した一意のオブジェクトIDの総数を取得します。

get_output

< >

( obj_idx: intframe_idx: intoutput_key: stris_conditioning_frame: bool = True )

パラメータ

  • obj_idx (int) — オブジェクトのインデックス。
  • frame_idx (int) — フレームのインデックス。
  • output_key (str) — 出力のキー。
  • is_conditioning_frame (bool) — 出力が条件付けフレーム用であるかどうかを示します。

スマートなデバイス管理で出力を取得します。

obj_id_to_idx

< >

( obj_id: int )

必要に応じて新しいエントリを作成し、オブジェクトIDをインデックスにマッピングします。

obj_idx_to_id

< >

( obj_idx: int )

モデル側のオブジェクトインデックスをクライアント側のオブジェクトIDにマッピングします。

remove_mask_inputs

< >

( obj_idx: intframe_idx: int )

マスク入力を削除します。

remove_point_inputs

< >

( obj_idx: intframe_idx: int )

ポイント入力を削除します。

reset_inference_session

< >

( )

トラッキングデータとキャッシュをリセットします。

reset_tracking_data

< >

( )

トラッキングデータをリセットしますが、キャッシュは保持します。

store_output

< >

( obj_idx: intframe_idx: intoutput_key: str | None = Noneoutput_value: typing.Union[torch.Tensor, dict, NoneType] = Noneis_conditioning_frame: bool = True )

パラメータ

  • obj_idx (int) — オブジェクトのインデックス。
  • frame_idx (int) — フレームのインデックス。
  • output_key (Optional[str]) — 出力のキーです。None の場合、出力は辞書として保存されます。
  • output_value (Optional[Union[torch.Tensor, dict]]) — 出力の値。
  • is_conditioning_frame (bool) — 出力が条件付けフレーム用であるかどうかを示します。

スマートなデバイス管理により出力を保存します。 がNoneの場合、出力は辞書として保存されます。

Sam2VideoModel

class transformers.Sam2VideoModel

< >

( config: Sam2VideoConfig )

パラメータ

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

特定のヘッドを上に載せずに、生のhidden-statesを出力する、素のSam2 Video Model。

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

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

forward

< >

( inference_session: Sam2VideoInferenceSessionframe_idx: int | None = Noneframe: typing.Optional[torch.Tensor] = Nonereverse: bool = Falserun_mem_encoder: bool = True**kwargs ) → Sam2VideoSegmentationOutput or tuple(torch.FloatTensor)

パラメータ

  • inference_session (~models.sam2_video.modeling_sam2_video.Sam2VideoInferenceSession) — 動画推論セッションオブジェクトです。
  • frame_idx (int, 任意) — 推論を実行するフレームのインデックスです。新しいストリームフレームに対して推論を行う場合は、指定する必要はありません。
  • frame (torch.Tensor, 任意) — 処理するフレーム。ストリーミング処理を行う場合に指定します。
  • reverse (bool、省略可能、デフォルトは False) — 逆方向に伝播するかどうか。
  • run_mem_encoder (bool、省略可、デフォルトは True) — 予測されたマスクに対してメモリエンコーダーを実行するかどうか。メモリエンコーダーは効率化のため、すべてのオブジェクトに対してバッチ処理されます。

戻り値

Sam2VideoSegmentationOutput または tuple(torch.FloatTensor)

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

ストリーミングされた動画フレームを通じてオブジェクトを伝播させます。

  • object_ids (list[int]、任意) — 現在のフレームで追跡されているオブジェクトの ID のリスト。
  • pred_masks (torch.FloatTensor、shape (batch_size, num_masks, height, width)) — モデルの解像度で保存された予測マスクです。
  • object_score_logits (torch.FloatTensor、shape (batch_size,)、任意) — オブジェクトが存在するかどうかを示す、オブジェクトスコアの logits。
  • frame_idx (int, 任意) — 動画のフレームインデックス。

propagate_in_video_iterator

< >

( inference_session: Sam2VideoInferenceSessionstart_frame_idx: int | None = Nonemax_frame_num_to_track: int | None = Nonereverse: bool = Falseshow_progress_bar: bool = False ) → Sam2VideoSegmentationOutput or tuple(torch.FloatTensor)

パラメータ

  • inference_session (~models.sam2_video.modeling_sam2_video.Sam2VideoInferenceSession) — 動画推論セッションオブジェクトです。
  • start_frame_idx (int, 任意) — 伝播の開始フレームインデックスです。 forward が新しい入力に対してまだ呼び出されていない場合は、指定する必要があります。 指定しない場合、開始フレームインデックスは入力ポイントを持つ最も早いフレームになります。
  • max_frame_num_to_track (int, 省略可) — 追跡するフレームの最大数。
  • reverse (bool、省略可能、デフォルトは False) — 逆方向に伝播するかどうか。
  • show_progress_bar (bool、省略可能、デフォルトは False) — 伝播中にプログレスバーを表示するかどうか。

戻り値

Sam2VideoSegmentationOutput または tuple(torch.FloatTensor)

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

…を動画フレーム全体に伝播します。動画全体で推論セッションを初期化する際に使用します。 各フレームに対してSam2VideoSegmentationOutputを生成します。

  • object_ids (list[int]、任意) — 現在のフレームで追跡されているオブジェクトの ID のリスト。
  • pred_masks (torch.FloatTensor、shape (batch_size, num_masks, height, width)) — モデルの解像度で保存された予測マスクです。
  • object_score_logits (torch.FloatTensor、shape (batch_size,)、任意) — オブジェクトが存在するかどうかを示す、オブジェクトスコアの logits。
  • frame_idx (int, 任意) — 動画のフレームインデックス。

get_image_features

< >

( pixel_values: FloatTensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Sam2VideoVisionEncoderOutput or tuple(torch.FloatTensor)

パラメータ

  • pixel_values (torch.FloatTensor) — (batch_size, num_channels, height, width) の形状を持つ入力のピクセル値。

戻り値

Sam2VideoVisionEncoderOutput または tuple(torch.FloatTensor)

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

  • last_hidden_state (torch.FloatTensor、shape (batch_size, height, width, 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後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

  • fpn_hidden_states (tuple(torch.FloatTensor)) — 各特徴レベル(高解像度から低解像度へ)に対応する torch.FloatTensor のタプルで、形状は (batch_size, hidden_size, height, width) です。Feature Pyramid Network のネック部からの特徴マップです。

  • fpn_position_encoding (tuple(torch.FloatTensor)) — torch.FloatTensor のタプル(解像度が高い順に各フィーチャーレベル分)。形状は (batch_size, hidden_size, height, width)。fpn_hidden_states に対応する位置エンコーディングです。

Update on GitHub