# SAM3 Video

    
        
        
    

## 概要

SAM3 (Segment Anything Model 3) は [SAM 3: Segment Anything with Concepts](https://ai.meta.com/research/publications/sam-3-segment-anything-with-concepts/) で紹介されました。

SAM3 Video は、動画に対して**Promptable Concept Segmentation (PCS)**を実行します。PCS はテキストを入力として受け取り（例: "yellow school bus"）、その概念に一致する**すべてのオブジェクト**のインスタンスマスクとセマンティックマスクを予測し、動画フレーム間でオブジェクトのアイデンティティを保持します。

このモデルは、検出モジュール（SAM3）とトラッキングモジュール（SAM2スタイルのトラッカー）を組み合わせることで、テキストプロンプトを用いた動画フレーム間の堅牢なオブジェクトトラッキングを可能にします。

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

*本稿では、Segment Anything Model (SAM) 3 を提示します。SAM 3 は、概念プロンプトに基づいて画像および動画内のオブジェクトを検出、セグメンテーション、トラッキングを行う統合モデルです。ここで、概念プロンプトとは、短い名詞句（例: "yellow school bus"）、画像のサンプル、またはそれらの組み合わせのいずれかを指します。Promptable Concept Segmentation (PCS) は、こうしたプロンプトを受け取り、一致するすべてのオブジェクトインスタンスに対してセグメンテーションマスクと一意のIDを返します。PCS の発展を促すため、画像と動画にわたって困難なネガティブ例を含む 400 万のユニークな概念ラベルを持つ高品質なデータセットを生成するスケーラブルなデータエンジンを構築しました。当モデルは、単一のバックボーンを共有する画像レベルの検出器と、メモリベースの動画トラッカーで構成されています。認識と位置特定は、検出精度を向上させるプレゼンスヘッドによって分離されています。SAM 3 は、画像および動画の PCS において既存システムの精度を 2 倍に向上させ、視覚的セグメンテーションタスクにおける従来の SAM の機能も改善しています。プロンプタブル概念セグメンテーションのための新しいベンチマーク Segment Anything with Concepts (SA-Co) とともに、SAM 3 をオープンソースとして公開します。*

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

## 使用例

### Video Segmentation and Tracking

#### プリロードされたビデオ推論

テキストプロンプトを使用して、すべてのフレームがすでに利用可能な動画を処理します:

```python
from transformers import Sam3VideoModel, Sam3VideoProcessor
import torch

model = Sam3VideoModel.from_pretrained("facebook/sam3", device_map="auto")
processor = Sam3VideoProcessor.from_pretrained("facebook/sam3")

# Load video frames
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,
    processing_device="cpu",
    video_storage_device="cpu",
)

# Add text prompt to detect and track objects
text = "person"
inference_session = processor.add_text_prompt(
    inference_session=inference_session,
    text=text,
)

# Process all frames in the video
outputs_per_frame = {}
# Pass show_progress_bar=True to display a tqdm progress bar.
for model_outputs in model.propagate_in_video_iterator(
    inference_session=inference_session, max_frame_num_to_track=50
):
    processed_outputs = processor.postprocess_outputs(inference_session, model_outputs)
    outputs_per_frame[model_outputs.frame_idx] = processed_outputs

print(f"Processed {len(outputs_per_frame)} frames")
Processed 51 frames

# Access results for a specific frame
frame_0_outputs = outputs_per_frame[0]
print(f"Detected {len(frame_0_outputs['object_ids'])} objects")
print(f"Object IDs: {frame_0_outputs['object_ids'].tolist()}")
print(f"Scores: {frame_0_outputs['scores'].tolist()}")
print(f"Boxes shape (XYXY format, absolute coordinates): {frame_0_outputs['boxes'].shape}")
print(f"Masks shape: {frame_0_outputs['masks'].shape}")
```

複数のプロンプトを指定することで、複数のオブジェクトカテゴリを同時にトラッキングすることもできます。モデルは、すべてのプロンプト間でビジョン特徴を効率的に再利用します:

```python
# Add multiple text prompts (or use a list in add_text_prompt)
multi_prompt_session = processor.init_video_session(
    video=video_frames,
    inference_device=device,
    processing_device="cpu",
    video_storage_device="cpu",
)
>>>
prompts = ["person", "bed", "lamp"]
processor.add_text_prompt(multi_prompt_session, prompts)
>>>
# Process video - detects objects from ALL prompts in a single pass
multi_outputs_per_frame = {}
# Pass show_progress_bar=True to display a tqdm progress bar.
for model_outputs in model.propagate_in_video_iterator(
    inference_session=multi_prompt_session, max_frame_num_to_track=50
):
    processed_outputs = processor.postprocess_outputs(multi_prompt_session, model_outputs)
    multi_outputs_per_frame[model_outputs.frame_idx] = processed_outputs
>>>
# Check which objects were detected by each prompt
frame_0_outputs = multi_outputs_per_frame[0]
prompt_to_obj_ids = frame_0_outputs["prompt_to_obj_ids"]
for prompt, obj_ids in prompt_to_obj_ids.items():
    print(f"{prompt}: {len(obj_ids)} objects")
person: 2 objects
bed: 1 objects
lamp: 1 objects
```

#### ストリーミング動画推論

⚠️ **ストリーミング推論の品質に関する注意**: ストリーミング推論では、未一致オブジェクトや重複オブジェクトを除去するホットスタートのヒューリスティックが無効になります。これらは、適切な判断を行うために将来のフレームへのアクセスを必要とするためです。そのため、事前読み込み済み動画の推論と比較して、誤検出や重複したオブジェクトトラッキングが増える可能性があります。すべてのフレームが利用可能な場合は、最適な結果を得るために事前読み込み済み動画の推論を使用してください。

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

```python
# Initialize session for streaming
streaming_inference_session = processor.init_video_session(
    inference_device=device,
    processing_device="cpu",
    video_storage_device="cpu",
)

# Add text prompt
text = "person"
streaming_inference_session = processor.add_text_prompt(
    inference_session=streaming_inference_session,
    text=text,
)

# Process frames one by one (streaming mode)
streaming_outputs_per_frame = {}
for frame_idx, frame in enumerate(video_frames[:50]):  # Process first 50 frames
    # First, process the frame using the processor
    inputs = processor(images=frame, device=device, return_tensors="pt").to(model.device)
...
    # Process frame using streaming inference - pass the processed pixel_values
    model_outputs = model(
        inference_session=streaming_inference_session,
        frame=inputs.pixel_values[0],  # Provide processed frame - this enables streaming mode
        reverse=False,
    )
...
    # Post-process outputs with original_sizes for proper resolution handling
    processed_outputs = processor.postprocess_outputs(
        streaming_inference_session,
        model_outputs,
        original_sizes=inputs.original_sizes,  # Required for streaming inference
    )
    streaming_outputs_per_frame[frame_idx] = processed_outputs
...
    if (frame_idx + 1) % 10 == 0:
        print(f"Processed {frame_idx + 1} frames...")

print(f"✓ Streaming inference complete! Processed {len(streaming_outputs_per_frame)} frames")
✓ Streaming inference complete! Processed 50 frames

# Access results
frame_0_outputs = streaming_outputs_per_frame[0]
print(f"Detected {len(frame_0_outputs['object_ids'])} objects in first frame")
print(f"Boxes are in XYXY format (absolute pixel coordinates): {frame_0_outputs['boxes'].shape}")
print(f"Masks are at original video resolution: {frame_0_outputs['masks'].shape}")
```

#### カスタム解像度推論

⚠️ **パフォーマンスに関する注意**: カスタム解像度を使用すると、精度が低下する可能性があります。このモデルは1008pxの解像度で使用することを前提としています。

より高速な推論や、メモリ使用量の削減のために:

```python
config = Sam3VideoConfig.from_pretrained("facebook/sam3")
config.image_size = 560
model = Sam3VideoModel.from_pretrained("facebook/sam3", config=config, device_map="auto")
processor = Sam3VideoProcessor.from_pretrained("facebook/sam3", size={"height": 560, "width": 560})
```

## Sam3VideoConfig[[transformers.Sam3VideoConfig]]

#### transformers.Sam3VideoConfig[[transformers.Sam3VideoConfig]]

```python
transformers.Sam3VideoConfig(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, detector_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, tracker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, initializer_range: float = 0.02, low_res_mask_size: int = 288, score_threshold_detection: float = 0.5, det_nms_thresh: float = 0.1, assoc_iou_thresh: float = 0.1, trk_assoc_iou_thresh: float = 0.5, new_det_thresh: float = 0.7, recondition_on_trk_masks: bool = True, hotstart_delay: int = 15, hotstart_unmatch_thresh: int = 8, hotstart_dup_thresh: int = 8, suppress_unmatched_only_within_hotstart: bool = True, init_trk_keep_alive: int = 30, max_trk_keep_alive: int = 30, min_trk_keep_alive: int = -1, suppress_overlapping_based_on_recent_occlusion_threshold: float = 0.7, decrease_trk_keep_alive_for_empty_masklets: bool = False, fill_hole_area: int = 16, max_num_objects: int = 10000, recondition_every_nth_frame: int = 16, high_conf_thresh: float = 0.8, high_iou_thresh: float = 0.8)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/configuration_sam3_video.py#L28)

**パラメータ:**

detector_config (`dict` または `Sam3Config`、*任意*) : Sam3 検出器モデルの設定です。指定しない場合、デフォルトの Sam3Config が使用されます。

tracker_config (`dict` または `Sam2VideoConfig`、*任意*) : Sam2Videoトラッカーモデルの設定です。指定しない場合、デフォルトのSam2VideoConfigが使用されます。

initializer_range (`float`、*optional*、デフォルト値は 0.02) : 重み行列の初期化に使用される truncated_normal_initializer の標準偏差です。

low_res_mask_size (`int`, *optional*, デフォルトは 288) : トラッカーから出力される低解像度マスクのサイズ（高さおよび幅）。動画解像度へのアップサンプリング前の値です。

score_threshold_detection (`float`、*optional*、デフォルトは 0.5) : 検出出力の確率閾値 - この閾値を超える検出のみを保持します。

det_nms_thresh (`float`、*optional*、デフォルト値は 0.1) : 検出 NMS (Non-Maximum Suppression) の IoU 閾値。

assoc_iou_thresh (`float`、*optional*、デフォルト値は 0.1) : 検出とトラッキングのマッチングにおける IoU 閾値。検出がトラクレットとこの閾値以上で重複する場合、その検出はトラクレットに「マッチした」とみなされます。通常、0.1 のような緩やかな閾値が使用されます。

trk_assoc_iou_thresh (`float`、*optional*、デフォルト値は 0.5) : 検出からトラッキングへのマッチングにおける IoU 閾値。マスクレットがどの検出にも「未マッチ」であるかを判定するために使用されます。0.5 のようなより厳格な閾値が一般的です。

new_det_thresh (`float`、*任意*、デフォルト値は 0.7) : 検出結果を新しいオブジェクトとして追加するための確率の閾値。

recondition_on_trk_masks (`bool`、*任意*、デフォルトは`True`) : リコンディショニングにトラッキングマスク（True）を使用するか、検出マスク（False）を使用するかを指定します。トラッキングマスクの方が品質が高く、検出器を検証シグナルとして活用してメモリを強化し、ドリフトを防ぐ場合は True を使用してください。

hotstart_delay (`int`、*optional*、デフォルトは 15) : ホットスタート中に出力をバッファリングするフレーム数。出力を`hotstart_delay`フレーム分保持し、ホットスタートのヒューリスティックに基づいてトラックレットを削除します。

hotstart_unmatch_thresh (`int`、*optional*、デフォルトは 8) : ホットスタート期間中にトラックレットを削除するために必要な、一致しないフレームの数。

hotstart_dup_thresh (`int`、*optional*、デフォルトは 8) : ホットスタート期間中に重複トラックレットを除去するために必要な重複フレーム数。

suppress_unmatched_only_within_hotstart (`bool`、*任意*、デフォルトは`True`) : マスクの抑制をホットスタート期間内に限定するかどうか。False の場合、ホットスタート期間より前に開始されたマスクも抑制できます。

init_trk_keep_alive (`int`、*任意*、デフォルトは 30) : 新しいトラックの初期 keep-alive カウンター。

max_trk_keep_alive (`int`、*optional*、デフォルトは 30) : 最大 keep-alive カウンター値。マッチした検出を追跡している場合、そのカウンターはこの値まで増加します。

min_trk_keep_alive (`int`, *optional*, デフォルトは -1) : 最小の keep-alive カウンター値。未一致の検出を追跡している場合、そのカウンターはこの値まで減少します。

suppress_overlapping_based_on_recent_occlusion_threshold (`float`, *optional*, デフォルト値は 0.7) : 最近の遮蔽に基づいて重複するオブジェクトを抑制するための閾値。この閾値を超える IoU を持つ重複マスクは、最も最近遮蔽されたものに基づいて抑制されます。

decrease_trk_keep_alive_for_empty_masklets (`bool`, *任意*, デフォルトは `False`) : SAM2の予測において、面積がゼロのマスクレットのキープアライブカウンタを減少させるかどうか。

fill_hole_area (`int`、*optional*、デフォルトは 16) : マスク内の穴を埋め、小さなノイズを除去するための最小面積（ピクセル単位）。

max_num_objects (`int`、*optional*、デフォルトは 10000) : 追跡するオブジェクトの最大数。デフォルトの 10000 は、実質的にこの制限を無効にします。

recondition_every_nth_frame (`int`、*optional*、デフォルトは 16) : マスクの再条件付けの頻度（フレーム単位）。再条件付けを無効にするには 0 を設定します。

high_conf_thresh (`float`、*任意*、デフォルトは 0.8) : リコンディショニングのための高信頼度閾値。この閾値を超える検出のみが、トラックレットのリコンディショニングに使用できます。

high_iou_thresh (`float`、*任意*、デフォルト値は 0.8) : リコンディショニング用の高IoU閾値。この閾値を超えるIoUを持つ検出のみが、トラックレットのリコンディショニングに使用できます。

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

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

例:
```python
>>> from transformers import Sam3VideoConfig, Sam3VideoModel

>>> # Initializing a SAM3 Video configuration with default detector and tracker
>>> configuration = Sam3VideoConfig()

>>> # Changing image size for custom resolution inference (automatically propagates to all nested configs)
>>> configuration.image_size = 560

>>> # Initializing a model from the configuration
>>> model = Sam3VideoModel(configuration)

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

## Sam3VideoProcessor[[transformers.Sam3VideoProcessor]]

#### transformers.Sam3VideoProcessor[[transformers.Sam3VideoProcessor]]

```python
transformers.Sam3VideoProcessor(image_processor, video_processor, tokenizer, target_size: int | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/processing_sam3_video.py#L39)

**パラメータ:**

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

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

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

target_size (`int`, *optional*) : 画像をリサイズする対象サイズ (target_size, target_size)。

画像プロセッサ、動画プロセッサ、トークナイザーを単一のプロセッサにラップするSam3VideoProcessorを構築します。

[Sam3VideoProcessor](/docs/transformers/main/ja/model_doc/sam3_video#transformers.Sam3VideoProcessor) は、[Sam3ImageProcessor](/docs/transformers/main/ja/model_doc/sam3#transformers.Sam3ImageProcessor)、`video_processor_class`、および [CLIPTokenizer](/docs/transformers/main/ja/model_doc/clip#transformers.CLIPTokenizer) のすべての機能を提供します。詳細については、[~Sam3ImageProcessor](/docs/transformers/main/ja/model_doc/sam3#transformers.Sam3ImageProcessor)、`~video_processor_class`、および [~CLIPTokenizer](/docs/transformers/main/ja/model_doc/clip#transformers.CLIPTokenizer) を参照してください。

#### __call__[[transformers.Sam3VideoProcessor.__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, segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, original_sizes: typing.Union[list[list[float]], torch.Tensor, NoneType] = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/processing_sam3_video.py#L55)

**パラメータ:**

images (`ImageInput`, *任意*) : 処理する画像。

segmentation_maps (`ImageInput`, *任意*) : 処理するセグメンテーションマップ（画像プロセッサ用、任意）。

original_sizes (`list[list[float]]`、`torch.Tensor`、*任意*) : 画像の元のサイズ。imagesが提供されていない場合にのみ使用されます。

return_tensors (`Union[str, ~utils.generic.TensorType]`、*任意*) : 設定すると、特定のフレームワークのテンソルを返します。指定可能な値は以下の通りです。 - `'pt'`: PyTorch の `torch.Tensor` オブジェクトを返します。 - `'np'`: NumPy の `np.ndarray` オブジェクトを返します。

**戻り値:** 以下のフィールドを持つ [BatchEncoding](/docs/transformers/main/ja/main_classes/tokenizer#transformers.BatchEncoding)

- `pixel_values` (`torch.Tensor`): 処理された画像。
- `original_sizes` (`list[list[float]]`): 画像の元のサイズ。
- `labels` (`torch.Tensor`、*任意*): 提供された場合の、処理済みセグメンテーションマップ。

#### postprocess_outputs[[transformers.Sam3VideoProcessor.postprocess_outputs]]

```python
postprocess_outputs(inference_session, model_outputs, original_sizes: typing.Union[list[list[float]], torch.Tensor, NoneType] = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/processing_sam3_video.py#L247)

**パラメータ:**

inference_session (`Sam3VideoInferenceSession`) : 推論セッションオブジェクト。

model_outputs (`Sam3VideoSegmentationOutput`) : `Sam3VideoModel.forward()`からの生のモデル出力です。

original_sizes (`list[list[float]]` または `torch.Tensor`、*任意*) : 元のフレームサイズ [高さ, 幅]（オプション）。video_height/video_width がセッション内で設定されていない場合、ストリーミング推論には必須です。

**戻り値:** `dict`

以下のキーを含む辞書:
- **object_ids** (`torch.Tensor`、shape `(num_objects,)`): 検出された各オブジェクトのオブジェクト ID。
- **scores** (`torch.Tensor`、形状 `(num_objects,)`): 各オブジェクトの検出スコア。
- **boxes** (`torch.Tensor`、形状 `(num_objects, 4)`): XYXY形式（top_left_x, top_left_y, bottom_right_x, bottom_right_y）のバウンディングボックス。
- **masks**（形状が`(num_objects, height, width)`の`torch.Tensor`）: 元の動画解像度における、各オブジェクトのバイナリセグメンテーションマスク。
- **prompt_to_obj_ids** (`dict[str, list[int]]`): プロンプトのテキストから、そのプロンプトによって検出されたオブジェクト ID のリストへのマッピング。

モデルの出力を後処理して、最終的なマスク、ボックス、スコアを取得します。

#### init_video_session[[transformers.Sam3VideoProcessor.init_video_session]]

```python
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] = None, inference_device: typing.Union[str, ForwardRef('torch.device')] = 'cpu', inference_state_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = None, processing_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = None, video_storage_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = None, max_vision_features_cache_size: int = 1, dtype: dtype = torch.float32)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/processing_sam3_video.py#L133)

**パラメータ:**

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`、*optional*、デフォルトは 1) : キャッシュするビジョン特徴の最大数。

dtype (`torch.dtype`、*任意*、デフォルトは`torch.float32`) : セッション全体で使用するtorchのdtype。

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

#### add_text_prompt[[transformers.Sam3VideoProcessor.add_text_prompt]]

```python
add_text_prompt(inference_session: Sam3VideoInferenceSession, text: str | list[str])
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/processing_sam3_video.py#L101)

**パラメータ:**

inference_session (`Sam3VideoInferenceSession`) : 推論セッション。

text (`str` または `list[str]`) : 追加するテキストプロンプト。

**戻り値:** `Sam3VideoInferenceSession`

追加されたテキストプロンプトを含む推論セッション。

推論セッションにテキストプロンプトを追加します。

## Sam3VideoInferenceSession[[transformers.Sam3VideoInferenceSession]]

#### transformers.Sam3VideoInferenceSession[[transformers.Sam3VideoInferenceSession]]

```python
transformers.Sam3VideoInferenceSession(video: typing.Optional[torch.FloatTensor] = None, video_height: int | None = None, video_width: int | None = None, inference_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)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L119)

**パラメータ:**

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`、*optional*、デフォルトは 1) : キャッシュするビジョン特徴の最大数。

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

#### add_mask_inputs[[transformers.Sam3VideoInferenceSession.add_mask_inputs]]

```python
add_mask_inputs(obj_idx: int, frame_idx: int, inputs: Tensor)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L255)

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

#### add_new_frame[[transformers.Sam3VideoInferenceSession.add_new_frame]]

```python
add_new_frame(pixel_values: Tensor, frame_idx: int | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L384)

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

#### add_prompt[[transformers.Sam3VideoInferenceSession.add_prompt]]

```python
add_prompt(prompt_text: str)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L215)

セッションにテキストプロンプトを追加し、その一意のIDを返します。プロンプトが既に存在する場合は、既存のIDを返します。

#### get_frame[[transformers.Sam3VideoInferenceSession.get_frame]]

```python
get_frame(frame_idx: int)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L400)

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

#### get_obj_num[[transformers.Sam3VideoInferenceSession.get_obj_num]]

```python
get_obj_num()
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L251)

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

#### get_output[[transformers.Sam3VideoInferenceSession.get_output]]

```python
get_output(obj_idx: int, frame_idx: int, output_key: str, is_conditioning_frame: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L357)

**パラメータ:**

obj_idx (int) : オブジェクトのインデックス。

frame_idx (int) : フレームのインデックス。

output_key (str) : 出力のキー。

is_conditioning_frame (bool) : 出力が条件付けフレーム用かどうかを示します。

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

#### obj_id_to_idx[[transformers.Sam3VideoInferenceSession.obj_id_to_idx]]

```python
obj_id_to_idx(obj_id: int)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L229)

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

#### obj_idx_to_id[[transformers.Sam3VideoInferenceSession.obj_idx_to_id]]

```python
obj_idx_to_id(obj_idx: int)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L247)

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

#### remove_mask_inputs[[transformers.Sam3VideoInferenceSession.remove_mask_inputs]]

```python
remove_mask_inputs(obj_idx: int, frame_idx: int)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L261)

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

#### remove_object[[transformers.Sam3VideoInferenceSession.remove_object]]

```python
remove_object(obj_id: int, strict: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L265)

**パラメータ:**

obj_id (`int`) : 削除するオブジェクトのID。

strict (`bool`、*任意*、デフォルトは`False`) : オブジェクトが存在しない場合にエラーを発生させるかどうか。

推論セッションからオブジェクトを削除します。これにより、動画のすべてのフレームからそのオブジェクトが削除されます。

#### reset_inference_session[[transformers.Sam3VideoInferenceSession.reset_inference_session]]

```python
reset_inference_session()
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L416)

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

#### reset_state[[transformers.Sam3VideoInferenceSession.reset_state]]

```python
reset_state()
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L428)

推論セッションの状態をリセットします。

#### reset_tracking_data[[transformers.Sam3VideoInferenceSession.reset_tracking_data]]

```python
reset_tracking_data()
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L404)

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

#### store_output[[transformers.Sam3VideoInferenceSession.store_output]]

```python
store_output(obj_idx: int, frame_idx: int, output_key: str | None = None, output_value: typing.Union[torch.Tensor, dict, NoneType] = None, is_conditioning_frame: bool = True)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L320)

**パラメータ:**

obj_idx (int) : オブジェクトのインデックス。

frame_idx (int) : フレームのインデックス。

output_key (Optional[str]) : 出力のキー。None の場合、出力は辞書として保存されます。

output_value (Optional[Union[torch.Tensor, dict]]) : 出力の値。

is_conditioning_frame (bool) : 出力が条件付けフレーム用かどうかを示します。

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

## Sam3VideoSegmentationOutput[[transformers.Sam3VideoSegmentationOutput]]

#### transformers.Sam3VideoSegmentationOutput[[transformers.Sam3VideoSegmentationOutput]]

```python
transformers.Sam3VideoSegmentationOutput(object_ids: list[int] | None = None, obj_id_to_mask: dict[int, torch.FloatTensor] | None = None, obj_id_to_score: dict[int, float] | None = None, obj_id_to_tracker_score: dict[int, float] | None = None, removed_obj_ids: set[int] | None = None, suppressed_obj_ids: set[int] | None = None, frame_idx: int | None = None)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L462)

**パラメータ:**

object_ids (`list[int]`, *任意*) : 現在のフレームで追跡されているオブジェクトのIDのリスト。

obj_id_to_mask (`dict[int, torch.FloatTensor]`, *任意*) : オブジェクト ID を予測された低解像度マスクにマッピングする辞書です。各マスクの形状は `(1, H_low, W_low)` です。

obj_id_to_score (`dict[int, float]`, *任意*) : オブジェクトIDを検出スコアにマッピングする辞書。

obj_id_to_tracker_score (`dict[int, float]`, *任意*) : 現在のフレームにおいて、オブジェクトIDをトラッカーのスコアにマッピングする辞書。

removed_obj_ids (`set[int]`, *任意*) : 削除されたオブジェクト ID のセット（例：ホットスタートのヒューリスティックによる削除）。

suppressed_obj_ids (`set[int]`, *任意*) : 現在のフレームで抑制されているオブジェクト ID のセット。

frame_idx (`int`, *optional*) : 動画のフレームインデックス。

Sam3Videoモデルの出力の基底クラス。

## Sam3VideoModel[[transformers.Sam3VideoModel]]

#### transformers.Sam3VideoModel[[transformers.Sam3VideoModel]]

```python
transformers.Sam3VideoModel(config: Sam3VideoConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L507)

**パラメータ:**

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

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

このモデルは [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.Sam3VideoModel.forward]]

```python
forward(inference_session: Sam3VideoInferenceSession, frame_idx: int | None = None, frame: typing.Optional[torch.Tensor] = None, reverse: bool = False, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L1693)

**パラメータ:**

inference_session (`~models.sam3_video.modeling_sam3_video.Sam3VideoInferenceSession`) : 動画推論セッションオブジェクト。

frame_idx (`int`, *optional*) : 推論を実行するフレームのインデックスです。新しいストリームされたフレームに対して推論を行う場合は、指定する必要はありません。

frame (`torch.Tensor`, *任意*) : 処理するフレーム。ストリーミングの場合に指定します。

reverse (`bool`、*任意*、デフォルトは`False`) : 逆方向に伝播するかどうか。

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

#### propagate_in_video_iterator[[transformers.Sam3VideoModel.propagate_in_video_iterator]]

```python
propagate_in_video_iterator(inference_session: Sam3VideoInferenceSession, start_frame_idx: int = 0, max_frame_num_to_track: int | None = None, reverse: bool = False, show_progress_bar: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam3_video/modeling_sam3_video.py#L1784)

**パラメータ:**

inference_session (`~models.sam3_video.modeling_sam3_video.Sam3VideoInferenceSession`) : 動画推論セッションオブジェクト。

start_frame_idx (`int`, *optional*, デフォルトは `0`) : 伝播の開始フレームインデックス。

max_frame_num_to_track (`int`, *optional*) : 追跡するフレームの最大数。指定しない場合、動画内のすべてのフレームが追跡されます。

reverse (`bool`、*任意*、デフォルトは`False`) : 逆方向に伝播するかどうか。

show_progress_bar (`bool`, *任意*, デフォルトは `False`) : 伝播中にプログレスバーを表示するかどうか。

**戻り値:** [Sam3VideoSegmentationOutput](/docs/transformers/main/ja/model_doc/sam3_video#transformers.Sam3VideoSegmentationOutput) または `tuple(torch.FloatTensor)`

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

プロンプトを伝播させ、動画全体についてグラウンディング結果を取得します。動画全体で推論セッションを初期化する際に使用します。各フレームに対してSam3VideoSegmentationOutputを生成します。

- **object_ids** (`list[int]`、*任意*) -- 現在のフレームで追跡されているオブジェクトのIDのリスト。
- **obj_id_to_mask** (`dict[int, torch.FloatTensor]`, *オプション*) -- オブジェクト ID を予測された低解像度マスクにマッピングする辞書です。各マスクの形状は `(1, H_low, W_low)` です。
- **obj_id_to_score** (`dict[int, float]`、*任意*) -- オブジェクト ID をその検出スコアにマッピングする辞書。
- **obj_id_to_tracker_score** (`dict[int, float]`, *optional*) -- Dictionary mapping object IDs to their tracker scores for the current frame.
- **removed_obj_ids** (`set[int]`, *任意*) -- 削除されたオブジェクト ID のセット（例：ホットスタートのヒューリスティックによる削除）。
- **suppressed_obj_ids** (`set[int]`、*任意*) -- 現在のフレームで抑制されているオブジェクト ID のセット。
- **frame_idx** (`int`, *任意*) -- 動画のフレームインデックス。

