# SAM2

    
        
        
    

## 概要

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](https://ai.meta.com/research/publications/sam-2-segment-anything-in-images-and-videos/) で提案されました。

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

![example image](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam2_header.gif)

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

*画像および動画におけるプロンプト可能な視覚セグメンテーションの解決に向けた基盤モデルである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](https://github.com/SangbumChoi) と [yonigozlan](https://huggingface.co/yonigozlan) によって提供されました。元のコードは[こちら](https://github.com/facebookresearch/sam2/tree/main)で確認できます。

## 使用例

### Pipelineによる自動マスク生成

SAM2は、`mask-generation`パイプラインを使用して画像内のすべてのオブジェクトをセグメントするための自動マスク生成に使用できます。

```python
from transformers import pipeline

generator = pipeline("mask-generation", model="facebook/sam2.1-hiera-large", device=0)
image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg"
outputs = generator(image_url, points_per_batch=64)

len(outputs["masks"])  # Number of masks generated
39
```

### 基本的な画像セグメンテーション

#### 単一ポイントクリック

オブジェクトをセグメントするには、セグメントしたいオブジェクトに1回クリックするだけで分割できます:

```python
from transformers import Sam2Processor, Sam2Model
import torch
from PIL import Image
import requests

model = Sam2Model.from_pretrained("facebook/sam2.1-hiera-large", device_map="auto")
processor = Sam2Processor.from_pretrained("facebook/sam2.1-hiera-large")

image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg"
raw_image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")

input_points = [[[[500, 375]]]]  # Single point click, 4 dimensions (image_dim, object_dim, point_per_object_dim, coordinates)
input_labels = [[[1]]]  # 1 for positive click, 0 for negative click, 3 dimensions (image_dim, object_dim, point_label)

inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)

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

masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]

# The model outputs multiple mask predictions ranked by quality score
print(f"Generated {masks.shape[1]} masks with shape {masks.shape}")
Generated 3 masks with shape torch.Size(1, 3, 1500, 2250)
```

#### 改善のための複数のポイント

セグメンテーションを微調整するために、複数の点を指定できます。

```python
# Add both positive and negative points to refine the mask
input_points = [[[[500, 375], [1125, 625]]]]  # Multiple points for refinement
input_labels = [[[1, 1]]]  # Both positive clicks

inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)

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

masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
```

#### バウンディングボックス入力

SAM2は、セグメンテーションのためのバウンディングボックス入力もサポートしています:

```python
# Define bounding box as [x_min, y_min, x_max, y_max]
input_boxes = [[[75, 275, 1725, 850]]]

inputs = processor(images=raw_image, input_boxes=input_boxes, return_tensors="pt").to(model.device)

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

masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
```

#### 複数オブジェクトのセグメンテーション

複数のオブジェクトを同時にセグメンテーションできます:

```python
# Define points for two different objects
input_points = [[[[500, 375]], [[650, 750]]]]  # Points for two objects in same image
input_labels = [[[1], [1]]]  # Positive clicks for both objects

inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)

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

# Each object gets its own mask
masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
print(f"Generated masks for {masks.shape[0]} objects")
Generated masks for 2 objects
```

### バッチ推論

#### バッチ化された画像

効率を向上させるために、複数の画像を同時に処理します:

```python
from transformers import Sam2Processor, Sam2Model
import torch
from PIL import Image
import requests

model = Sam2Model.from_pretrained("facebook/sam2.1-hiera-large", device_map="auto")
processor = Sam2Processor.from_pretrained("facebook/sam2.1-hiera-large")

# Load multiple images
image_urls = [
    "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg",
    "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/dog_sam.png"
]
raw_images = [Image.open(requests.get(url, stream=True).raw).convert("RGB") for url in image_urls]

# Single point per image
input_points = [[[[500, 375]]], [[[770, 200]]]]  # One point for each image
input_labels = [[[1]], [[1]]]  # Positive clicks for both images

inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)

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

# Post-process masks for each image
all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
print(f"Processed {len(all_masks)} images, each with {all_masks[0].shape[0]} objects")
Processed 2 images, each with 1 objects
```

#### 画像ごとのバッチ化されたオブジェクト

バッチ推論を使用して、各画像内の複数のオブジェクトをセグメントします:

```python
# Multiple objects per image - different numbers of objects per image
input_points = [
    [[[500, 375]], [[650, 750]]],  # Truck image: 2 objects
    [[[770, 200]]]  # Dog image: 1 object
]
input_labels = [
    [[1], [1]],  # Truck image: positive clicks for both objects
    [[1]]  # Dog image: positive click for the object
]

inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)

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

all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
```

#### バッチ化された画像とバッチ化されたオブジェクト、および複数のポイント

1つのオブジェクトに複数の点を含む複雑なバッチシナリオを処理します:

```python
# Add groceries image for more complex example
groceries_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/groceries.jpg"
groceries_image = Image.open(requests.get(groceries_url, stream=True).raw).convert("RGB")
raw_images = [raw_images[0], groceries_image]  # Use truck and groceries images

# Complex batching: multiple images, multiple objects, multiple points per object
input_points = [
    [[[500, 375]], [[650, 750]]],  # Truck image: 2 objects with 1 point each
    [[[400, 300]], [[630, 300], [550, 300]]]  # Groceries image: obj1 has 1 point, obj2 has 2 points
]
input_labels = [
    [[1], [1]],  # Truck image: positive clicks
    [[1], [1, 1]]  # Groceries image: positive clicks for refinement
]

inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)

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

all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
```

#### バッチ化されたバウンディングボックス

バウンディングボックス入力で複数の画像を処理します:

```python
# Multiple bounding boxes per image (using truck and groceries images)
input_boxes = [
    [[75, 275, 1725, 850], [425, 600, 700, 875], [1375, 550, 1650, 800], [1240, 675, 1400, 750]],  # Truck image: 4 boxes
    [[450, 170, 520, 350], [350, 190, 450, 350], [500, 170, 580, 350], [580, 170, 640, 350]]  # Groceries image: 4 boxes
]

# Update images for this example
raw_images = [raw_images[0], groceries_image]  # truck and groceries

inputs = processor(images=raw_images, input_boxes=input_boxes, return_tensors="pt").to(model.device)

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

all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
print(f"Processed {len(input_boxes)} images with {len(input_boxes[0])} and {len(input_boxes[1])} boxes respectively")
Processed 2 images with 4 and 4 boxes respectively
```

### 以前のマスクを入力として使用

SAM2は、以前の予測から得られたマスクを入力として使用して、セグメンテーションを改善できます:

```python
# Get initial segmentation
input_points = [[[[500, 375]]]]
input_labels = [[[1]]]
inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)

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

# Use the best mask as input for refinement
mask_input = outputs.pred_masks[:, :, torch.argmax(outputs.iou_scores.squeeze())]

# Add additional points with the mask input
new_input_points = [[[[500, 375], [450, 300]]]]
new_input_labels = [[[1, 1]]]
inputs = processor(
    input_points=new_input_points,
    input_labels=new_input_labels,
    original_sizes=inputs["original_sizes"],
    return_tensors="pt",
).to(model.device)

with torch.no_grad():
    refined_outputs = model(
        **inputs,
        input_masks=mask_input,
        image_embeddings=outputs.image_embeddings,
        multimask_output=False,
    )
```

## Sam2Config[[transformers.Sam2Config]]

#### transformers.Sam2Config[[transformers.Sam2Config]]

```python
transformers.Sam2Config(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, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, prompt_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, mask_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, initializer_range: float = 0.02)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/configuration_sam2.py#L220)

**パラメータ:**

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

prompt_encoder_config (Union[`dict`, `Sam2PromptEncoderConfig`], *optional*) : [Sam2PromptEncoderConfig](/docs/transformers/main/ja/model_doc/sam2#transformers.Sam2PromptEncoderConfig)を初期化するために使用される設定オプションの辞書。

mask_decoder_config (Union[`dict`, `Sam2MaskDecoderConfig`], *optional*) : [Sam2MaskDecoderConfig](/docs/transformers/main/ja/model_doc/sam2#transformers.Sam2MaskDecoderConfig)を初期化するために使用される設定オプションの辞書。

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

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

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

例:

```python
>>> 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)
```

## Sam2HieraDetConfig[[transformers.Sam2HieraDetConfig]]

#### transformers.Sam2HieraDetConfig[[transformers.Sam2HieraDetConfig]]

```python
transformers.Sam2HieraDetConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 96, num_attention_heads: int = 1, num_channels: int = 3, image_size: int | list[int] | None = None, patch_kernel_size: int | list[int] | None = None, patch_stride: int | list[int] | None = None, patch_padding: int | list[int] | None = None, query_stride: int | list[int] | None = None, window_positional_embedding_background_size: list[int] | None = None, num_query_pool_stages: int = 3, blocks_per_stage: list[int] | None = None, embed_dim_per_stage: list[int] | None = None, num_attention_heads_per_stage: list[int] | None = None, window_size_per_stage: list[int] | None = None, global_attention_blocks: list[int] | None = None, mlp_ratio: float = 4.0, hidden_act: str = 'gelu', layer_norm_eps: float = 1e-06, initializer_range: float = 0.02)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/configuration_sam2.py#L25)

**パラメータ:**

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

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

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

image_size (`Union[int, list[int]]`、*任意*) : 各画像のサイズ（解像度）。

patch_kernel_size (`list[int]`、*optional*、デフォルトは`[7, 7]`) : パッチのカーネルサイズ。

patch_stride (`list[int]`、*optional*、デフォルトは`[4, 4]`) : パッチのストライドです。

patch_padding (`list[int]`、*optional*、デフォルトは`[3, 3]`) : パッチのpaddingです。

query_stride (`list[int]`、*optional*、デフォルトは`[2, 2]`) : 各ステージ間のダウンサンプルのストライド。

window_positional_embedding_background_size (`list[int]`、*optional*、デフォルトは`[7, 7]`) : グローバルアテンションを使用しない場合の、各ステージのウィンドウサイズ。

num_query_pool_stages (`int`、*任意*、デフォルトは 3) : クエリプールのステージ数。

blocks_per_stage (`list[int]`、*optional*、デフォルトは`[1, 2, 7, 2]`) : ステージごとのブロック数です。

embed_dim_per_stage (`list[int]`、*optional*、デフォルトは`[96, 192, 384, 768]`) : 各ステージの埋め込み次元数。

num_attention_heads_per_stage (`list[int]`、*optional*、デフォルトは`[1, 2, 4, 8]`) : 各ステージあたりのアテンションヘッド数です。

window_size_per_stage (`list[int]`、*optional*、デフォルトは`[8, 4, 14, 7]`) : 各ステージのウィンドウサイズです。

global_attention_blocks (`list[int]`、*optional*、デフォルトは`[5, 7, 9]`) : グローバルアテンションが使用されるブロック。

mlp_ratio (`float`、*任意*、デフォルトは `4.0`) : MLP の隠れ層次元と埋め込み次元の比率。

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

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

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

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

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

## Sam2VisionConfig[[transformers.Sam2VisionConfig]]

#### transformers.Sam2VisionConfig[[transformers.Sam2VisionConfig]]

```python
transformers.Sam2VisionConfig(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, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, backbone_channel_list: list[int] | None = None, backbone_feature_sizes: list | None = None, fpn_hidden_size: int = 256, fpn_kernel_size: int = 1, fpn_stride: int = 1, fpn_padding: int = 0, fpn_top_down_levels: list[int] | None = None, num_feature_levels: int = 3, hidden_act: str = 'gelu', layer_norm_eps: float = 1e-06, initializer_range: float = 0.02)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/configuration_sam2.py#L103)

**パラメータ:**

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`、*optional*) : バックボーンモデルの設定です。

backbone_channel_list (`List[int]`、*任意*、デフォルトは`[768, 384, 192, 96]`) : バックボーンのチャネル次元のリストです。

backbone_feature_sizes (`List[List[int]]`、*任意*、デフォルトは `[[256, 256], [128, 128], [64, 64]]`) : バックボーンからの特徴マップの空間サイズです。

fpn_hidden_size (`int`、*optional*、デフォルトは 256) : FPN の隠れ層の次元数。

fpn_kernel_size (`int`、*optional*、デフォルトは 1) : neck 内の畳み込みのカーネルサイズです。

fpn_stride (`int`、*optional*、デフォルトは 1) : neck における畳み込みのストライドです。

fpn_padding (`int`、*任意*、デフォルトは 0) : neck 内の畳み込みの padding です。

fpn_top_down_levels (`List[int]`、*optional*、デフォルトは`[2, 3]`) : トップダウン FPN 接続のレベル。

num_feature_levels (`int`、*任意*、デフォルトは 3) : FPN から使用する特徴量レベルの数。

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

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

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

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

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

## Sam2MaskDecoderConfig[[transformers.Sam2MaskDecoderConfig]]

#### transformers.Sam2MaskDecoderConfig[[transformers.Sam2MaskDecoderConfig]]

```python
transformers.Sam2MaskDecoderConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 256, hidden_act: str = 'gelu', mlp_dim: int = 2048, num_hidden_layers: int = 2, num_attention_heads: int = 8, attention_downsample_rate: int = 2, num_multimask_outputs: int = 3, iou_head_depth: int = 3, iou_head_hidden_dim: int = 256, dynamic_multimask_via_stability: bool = True, dynamic_multimask_stability_delta: float = 0.05, dynamic_multimask_stability_thresh: float = 0.98)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/configuration_sam2.py#L181)

**パラメータ:**

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

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

mlp_dim (`int`、*optional*、デフォルトは 2048) : 2-way transformer における MLP の次元数。

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

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

attention_downsample_rate (`int`、*optional*、デフォルトは 2) : アテンション層のダウンサンプル率です。

num_multimask_outputs (`int`、*任意*、デフォルトは 3) : マルチマスク出力の数。

iou_head_depth (`int`、*optional*、デフォルトは 3) : IoU ヘッドの深さ。

iou_head_hidden_dim (`int`、*optional*、デフォルトは 256) : IoU ヘッドの隠れ次元です。

dynamic_multimask_via_stability (`bool`、*任意*、デフォルトは `True`) : stability を用いた動的マルチマスクを使用するかどうか。

dynamic_multimask_stability_delta (`float`、*任意*、デフォルトは 0.05) : 動的マルチマスクの安定性デルタです。

dynamic_multimask_stability_thresh (`float`、*任意*、デフォルト値は 0.98) : 動的マルチマスクの安定性しきい値です。

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

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

## Sam2PromptEncoderConfig[[transformers.Sam2PromptEncoderConfig]]

#### transformers.Sam2PromptEncoderConfig[[transformers.Sam2PromptEncoderConfig]]

```python
transformers.Sam2PromptEncoderConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 256, image_size: int | list[int] | tuple[int, int] = 1024, patch_size: int | list[int] | tuple[int, int] = 16, mask_input_channels: int = 16, num_point_embeddings: int = 4, hidden_act: str = 'gelu', layer_norm_eps: float = 1e-06, scale: int = 1)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/configuration_sam2.py#L156)

**パラメータ:**

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) : 使用するポイント埋め込みの数。

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

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

scale (`float`、*任意*、デフォルトは 1) : プロンプトエンコーダーのスケール係数です。

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

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

## Sam2Processor[[transformers.Sam2Processor]]

#### transformers.Sam2Processor[[transformers.Sam2Processor]]

```python
transformers.Sam2Processor(image_processor, target_size: int | None = None, point_pad_value: int = -10, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/processing_sam2.py#L37)

**パラメータ:**

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

target_size (`int`, *optional*) : 入力ポイントとバウンディングボックスを正規化するためのターゲットサイズ（ピクセル単位）です。指定されない場合、画像プロセッサのサイズ設定がデフォルトとして使用されます。すべての入力座標（ポイントとボックス）は、モデルに渡される前にこのサイズに正規化されます。これにより、元の画像の寸法に関係なく、座標の表現が常に一貫したものになります。

point_pad_value (`int`, *optional*, デフォルト値は -10) : 長さが異なるシーケンスをバッチ処理する際に、入力ポイントのパディングに使用される値。この値はパディングされた位置をマークするために使用され、座標正規化の間も保持されます。

Sam2Processor を構築し、画像プロセッサーを単一のプロセッサーにラップします。

[Sam2Processor](/docs/transformers/main/ja/model_doc/sam2#transformers.Sam2Processor) は [Sam2ImageProcessor](/docs/transformers/main/ja/model_doc/sam2#transformers.Sam2ImageProcessor) のすべての機能を提供します。詳細については、[~Sam2ImageProcessor](/docs/transformers/main/ja/model_doc/sam2#transformers.Sam2ImageProcessor) を参照してください。

#### __call__[[transformers.Sam2Processor.__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, input_points: typing.Union[list[list[list[list[float]]]], torch.Tensor, NoneType] = None, input_labels: typing.Union[list[list[list[int]]], torch.Tensor, NoneType] = None, input_boxes: typing.Union[list[list[list[float]]], 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/sam2/processing_sam2.py#L53)

**パラメータ:**

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](/docs/transformers/main/ja/main_classes/tokenizer#transformers.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[[transformers.Sam2Processor.post_process_masks]]

```python
post_process_masks(masks, original_sizes, mask_threshold = 0.0, binarize = True, max_hole_area = 0.0, max_sprinkle_area = 0.0, apply_non_overlapping_constraints = False, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/processing_sam2.py#L459)

**パラメータ:**

masks (`Union[List[torch.Tensor], List[np.ndarray]]`) : (batch_size, num_channels, height, width) 形式の、mask_decoder からのバッチ化されたマスク。

original_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`) : モデルが期待する入力形状にリサイズされる前の、各画像の元のサイズ。(height, width)形式です。

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によって指定されます。

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

## Sam2ImageProcessor[[transformers.Sam2ImageProcessor]]

#### transformers.Sam2ImageProcessor[[transformers.Sam2ImageProcessor]]

```python
transformers.Sam2ImageProcessor(**kwargs: *<class 'transformers.models.sam2.image_processing_sam2.Sam2ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/image_processing_sam2.py#L369)

**パラメータ:**

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

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

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.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_pad (`bool`, *kwargs*, *optional*, デフォルトは`None`) : 画像にパディングを行うかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, defaults to `None`) : The size in `{"height": int, "width" int}` to pad the images to. Must be larger than any image size provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest height and width in the batch. Applied only when `do_pad=True.`

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

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

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

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

mask_size (`dict[str, *kwargs*, int]`, *任意*) : セグメンテーションマップをリサイズするサイズ `{"height": int, "width": int}`。

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

#### preprocess[[transformers.Sam2ImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], 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, **kwargs: *<class 'transformers.models.sam2.image_processing_sam2.Sam2ImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/image_processing_sam2.py#L389)

**パラメータ:**

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`, *任意*) : 前処理対象のセグメンテーションマップ。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

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

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

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

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

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

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

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

mask_size (`dict[str, *kwargs*, int]`, *任意*) : セグメンテーションマップをリサイズするサイズ `{"height": int, "width": int}`。

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

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

## Sam2HieraDetModel[[transformers.Sam2HieraDetModel]]

#### transformers.Sam2HieraDetModel[[transformers.Sam2HieraDetModel]]

```python
transformers.Sam2HieraDetModel(config: Sam2HieraDetConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/modeling_sam2.py#L603)

#### forward[[transformers.Sam2HieraDetModel.forward]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/modeling_sam2.py#L646)

## Sam2VisionModel[[transformers.Sam2VisionModel]]

#### transformers.Sam2VisionModel[[transformers.Sam2VisionModel]]

```python
transformers.Sam2VisionModel(config: Sam2VisionConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/modeling_sam2.py#L677)

**パラメータ:**

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

ヘッドや投影が上に乗せられていないSamのビジョンモデル。

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

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/modeling_sam2.py#L699)

## Sam2Model[[transformers.Sam2Model]]

#### transformers.Sam2Model[[transformers.Sam2Model]]

```python
transformers.Sam2Model(config: Sam2Config)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/modeling_sam2.py#L1314)

**パラメータ:**

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

入力画像と、入力ポイントとラベル、ボックス、またはマスクを指定してセグメンテーションマスクを生成するためのSegment Anything Model 2 (SAM 2)。

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

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, input_points: typing.Optional[torch.Tensor] = None, input_labels: typing.Optional[torch.LongTensor] = None, input_boxes: typing.Optional[torch.Tensor] = None, input_masks: typing.Optional[torch.LongTensor] = None, image_embeddings: typing.Optional[torch.Tensor] = None, multimask_output: bool = True, attention_similarity: typing.Optional[torch.Tensor] = None, target_embedding: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/modeling_sam2.py#L1413)

**パラメータ:**

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

input_points (`torch.Tensor`、shape は `(batch_size, num_points, 2)`) : 入力となる 2 次元空間上の点です。プロンプトエンコーダーがこの点を使用してプロンプトをエンコードします。一般的に、これによりはるかに良い結果が得られます。点は、リストのリストのリストをプロセッサーに渡すことで取得でき、プロセッサーは次元 4 の対応する `torch` テンソルを作成します。最初の次元は画像のバッチサイズ、2 番目の次元は点のバッチサイズ（つまり、1 つの入力点あたりモデルに何つのセグメンテーションマスクを予測させたいか）、3 番目の次元は 1 つのセグメンテーションマスクあたりの点の数（1 つのマスクに対して複数の点を渡すことも可能です）、最後の次元は点の x（縦）および y（横）座標です。画像ごと、またはマスクごとに異なる数の点が渡された場合、プロセッサーは (0, 0) 座標に対応する「PAD」点を作成し、これらの点についてはラベルを使用して埋め込みの計算をスキップします。

input_labels (`torch.LongTensor`、shape は `(batch_size, point_batch_size, num_points)`) : ポイントの入力ラベルです。プロンプトエンコーダーがプロンプトをエンコードするために使用されます。公式実装によると、ラベルには 3 種類あります - `1`: 対象オブジェクトを含むポイント - `0`: 対象オブジェクトを含まないポイント - `-1`: 背景に対応するポイント 追加したラベル: - `-10`: パディングポイントであり、プロンプトエンコーダーによって無視されるべきです パディングラベルは、プロセッサーによって自動的に設定される必要があります。

input_boxes (`torch.Tensor`、shape `(batch_size, num_boxes, 4)`) : ポイント用の入力ボックスです。プロンプトエンコーダーによってプロンプトをエンコードするために使用されます。一般的に、はるかに優れた生成マスクが得られます。ボックスは、リストのリストのリストをプロセッサーに渡すことで取得でき、`torch`テンソルが生成されます。各次元は、それぞれ画像のバッチサイズ、画像ごとのボックス数、ボックスの左上と右下の点の座標に対応します。順序は (`x1`, `y1`, `x2`, `y2`) です:  - `x1`: 入力ボックスの左上の点のx座標 - `y1`: 入力ボックスの左上の点のy座標 - `x2`: 入力ボックスの右下の点のx座標 - `y2`: 入力ボックスの右下の点のy座標

input_masks (`torch.Tensor`、shape `(batch_size, image_size, image_size)`) : SAM モデルはセグメンテーションマスクも入力として受け付けます。マスクはプロンプトエンコーダーによって埋め込まれ、対応する埋め込みが生成されます。この埋め込みは後でマスクデコーダーに渡されます。これらのマスクはユーザーが手動で渡す必要があり、shape は (`batch_size`, `image_size`, `image_size`) である必要があります。

image_embeddings (`torch.Tensor`、shape は `(batch_size, output_channels, window_size, window_size)`) : 画像埋め込みです。マスクデコーダーがマスクと iou スコアを生成するために使用されます。メモリ効率の高い計算を行うには、まず `get_image_embeddings` メソッドで画像埋め込みを取得し、`pixel_values` を渡す代わりに、それを `forward` メソッドに渡すことができます。

multimask_output (`bool`, *任意*) : 元の実装および論文では、モデルは常に1画像につき3つのマスクを出力します（関連する場合は、1ポイントごとまたは1バウンディングボックスごと）。ただし、`multimask_output=False`を指定することで、「最良」のマスクに相当する単一のマスクのみを出力することも可能です。

attention_similarity (`torch.Tensor`, *任意*) : 注意度類似度テンソル。モデルが[PerSAM](https://huggingface.co/papers/2305.03048)で導入されたパーソナライゼーションに使用される場合、ターゲット誘導注意のためにマスクデコーダーに提供されます。

target_embedding (`torch.Tensor`, *任意*) : ターゲット概念の埋め込み。モデルが[PerSAM](https://huggingface.co/papers/2305.03048)で導入されたパーソナライゼーションに使用される場合、ターゲットセマンティックプロンプティングのためにマスクデコーダーに提供されます。

**戻り値:** `Sam2ImageSegmentationOutput` または `tuple(torch.Tensor)`

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

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

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

- **iou_scores** (`torch.Tensor`、形状 `(batch_size, point_batch_size, num_masks)`) -- 予測されたマスクの交差率 (IoU) スコア。
- **pred_masks** (`torch.Tensor`、形状 `(batch_size, point_batch_size, num_masks, height, width)`) -- 予測された低解像度マスクです。これは `low_res_masks` の別名です。これらのマスクは、プロセッサによって後処理を行い、元の画像サイズに合わせる必要があります。
- **object_score_logits** (`torch.Tensor`、形状 `(batch_size, point_batch_size, 1)`) -- オブジェクトが存在するかどうかを示すオブジェクトスコアのロジット。
- **image_embeddings** (`tuple(torch.Tensor)`) -- FPN からの特徴量で、マスクデコーダーで使用されます。これは `torch.Tensor` のタプルであり、各テンソルの形状は `(batch_size, channels, height, width)` です。
- **vision_hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` の場合に返されます) -- 各ステージの出力に対応する `torch.Tensor` のタプルで、形状は `(batch_size, height, width, hidden_size)` です。ビジョンモデルの各ステージの出力における隠れ状態です。
- **vision_attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` の場合のみ返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。ビジョンモデルのアテンション重みです。
- **mask_decoder_attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` の場合のみ返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）。形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。マスクデコーダーのアテンション重みです。

例:

```python
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoModel, AutoProcessor

>>> model = AutoModel.from_pretrained("danelcsb/sam2.1_hiera_tiny")
>>> processor = AutoProcessor.from_pretrained("danelcsb/sam2.1_hiera_tiny")

>>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam-car.png"
>>> with httpx.stream("GET", url) as response:
...     raw_image = Image.open(BytesIO(response.read())).convert("RGB")
>>> input_points = [[[400, 650]]]  # 2D location of a window on the car
>>> inputs = processor(images=raw_image, input_points=input_points, return_tensors="pt")

>>> # Get segmentation mask
>>> outputs = model(**inputs)

>>> # Postprocess masks
>>> masks = processor.post_process_masks(
...     outputs.pred_masks, inputs["original_sizes"]
... )
```

#### get_image_features[[transformers.Sam2Model.get_image_features]]

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

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/sam2/modeling_sam2.py#L1589)

**パラメータ:**

pixel_values (`torch.Tensor`) : 形状が`(batch_size, num_channels, height, width)`の入力のピクセル値。

**戻り値:** `Sam2VisionEncoderOutput` または `tuple(torch.Tensor)`

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

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, height, width, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **pooler_output** (`torch.Tensor`、形状 `(batch_size, hidden_size)`) -- 補助的な事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン（分類トークン）の最終層の隠れ状態です。例えば、BERT系のモデルでは、線形層とtanh活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次の文予測（分類）目的から学習されます。
- **hidden_states** (`tuple(torch.Tensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（モデルに埋め込み層がある場合はその出力用 1 つ、各層の出力用 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.Tensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.Tensor` のタプル（各レイヤーごとに1つ）、形状は `(batch_size, num_heads, sequence_length, sequence_length)`。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **fpn_hidden_states** (`tuple(torch.Tensor)`) -- 各特徴レベル（高解像度から低解像度へ）に対応する `torch.Tensor` のタプルで、形状は `(batch_size, hidden_size, height, width)` です。Feature Pyramid Network のネック部分から得られる特徴マップです。
- **fpn_position_encoding** (`tuple(torch.Tensor)`) -- `torch.Tensor` のタプル（解像度が高い順に、各フィーチャーレベルに対応する1つずつ）。形状は `(batch_size, hidden_size, height, width)`。`fpn_hidden_states` に対応する位置エンコーディング。

例:

```python
```

