Transformers documentation

SAM3

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

SAM3

SDPA FlashAttention

概要

SAM3 (Segment Anything Model 3) は、SAM 3: Segment Anything with Concepts で紹介されました。

SAM3は画像に対してPromptable Concept Segmentation (PCS)を実行します。PCSはテキストおよび/または画像のサンプルを入力として受け取り(例: “yellow school bus”)、その概念に一致するすべてのオブジェクトのインスタンスマスクとセマンティックマスクを予測します。

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

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

このモデルは、yonigozlan 氏と ronghanghu 氏によって提供されました。

🤗 Transformers を使用した使用例

テキストのみのプロンプト

import requests
import torch
from PIL import Image

from transformers import Sam3Model, Sam3Processor


model = Sam3Model.from_pretrained("facebook/sam3", device_map="auto")
processor = Sam3Processor.from_pretrained("facebook/sam3")

# Load image
image_url = "http://images.cocodataset.org/val2017/000000077595.jpg"
image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")

# Segment using text prompt
inputs = processor(images=image, text="ear", return_tensors="pt").to(model.device)

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

# Post-process results
results = processor.post_process_instance_segmentation(
    outputs,
    threshold=0.5,
    mask_threshold=0.5,
    target_sizes=inputs.get("original_sizes").tolist()
)[0]

print(f"Found {len(results['masks'])} objects")
# Results contain:
# - masks: Binary masks resized to original image size
# - boxes: Bounding boxes in absolute pixel coordinates (xyxy format)
# - scores: Confidence scores

単一のバウンディングボックスプロンプト

視覚的な概念に対してバウンディングボックスを指定してオブジェクトをセグメントします:

# Box in xyxy format: [x1, y1, x2, y2] in pixel coordinates
# Example: laptop region
box_xyxy = [100, 150, 500, 450]
input_boxes = [[box_xyxy]]  # [batch, num_boxes, 4]
input_boxes_labels = [[1]]  # 1 = positive box

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

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

# Post-process results
results = processor.post_process_instance_segmentation(
    outputs,
    threshold=0.5,
    mask_threshold=0.5,
    target_sizes=inputs.get("original_sizes").tolist()
)[0]

複数のボックスプロンプト(正と負)

正ラベルと負ラベルを付けた複数のボックスを使用して、概念を洗練させます:

# Load kitchen image
kitchen_url = "http://images.cocodataset.org/val2017/000000136466.jpg"
kitchen_image = Image.open(requests.get(kitchen_url, stream=True).raw).convert("RGB")

# Define two positive boxes (e.g., dial and button on oven)
# Boxes are in xyxy format [x1, y1, x2, y2] in pixel coordinates
box1_xyxy = [59, 144, 76, 163]  # Dial box
box2_xyxy = [87, 148, 104, 159]  # Button box
input_boxes = [[box1_xyxy, box2_xyxy]]
input_boxes_labels = [[1, 1]]  # Both positive

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

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

# Post-process results
results = processor.post_process_instance_segmentation(
    outputs,
    threshold=0.5,
    mask_threshold=0.5,
    target_sizes=inputs.get("original_sizes").tolist()
)[0]

組み合わせプロンプト(テキスト + ネガティブボックス)

ネガティブなビジュアルプロンプトをテキストプロンプトと組み合わせて、コンセプトを洗練させます:

# Segment "handle" but exclude the oven handle using a negative box
text = "handle"
# Negative box covering oven handle area (xyxy): [40, 183, 318, 204]
oven_handle_box = [40, 183, 318, 204]
input_boxes = [[oven_handle_box]]

inputs = processor(
    images=kitchen_image,
    text=text,
    input_boxes=input_boxes,
    input_boxes_labels=[[0]],  # 0 = negative (exclude this region)
    return_tensors="pt"
).to(model.device)

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

# Post-process results
results = processor.post_process_instance_segmentation(
    outputs,
    threshold=0.5,
    mask_threshold=0.5,
    target_sizes=inputs.get("original_sizes").tolist()
)[0]
# This will segment pot handles but exclude the oven handle

テキストプロンプトによるバッチ推論

異なるテキストプロンプトを持つ複数の画像を効率的に処理します:

cat_url = "http://images.cocodataset.org/val2017/000000077595.jpg"
kitchen_url = "http://images.cocodataset.org/val2017/000000136466.jpg"
images = [
    Image.open(requests.get(cat_url, stream=True).raw).convert("RGB"),
    Image.open(requests.get(kitchen_url, stream=True).raw).convert("RGB")
]

# Different text prompt for each image
text_prompts = ["ear", "dial"]

inputs = processor(images=images, text=text_prompts, return_tensors="pt").to(model.device)

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

# Post-process results for both images
results = processor.post_process_instance_segmentation(
    outputs,
    threshold=0.5,
    mask_threshold=0.5,
    target_sizes=inputs.get("original_sizes").tolist()
)

print(f"Image 1: {len(results[0]['masks'])} objects found")
print(f"Image 2: {len(results[1]['masks'])} objects found")

バッチ化された混合プロンプト

同じバッチ内の異なる画像に異なるプロンプトタイプを使用するには:

# Image 1: text prompt "laptop"
# Image 2: visual prompt (dial box)
box2_xyxy = [59, 144, 76, 163]

inputs = processor(
    images=images,
    text=["laptop", None],  # Only first image has text
    input_boxes=[None, [box2_xyxy]],  # Only second image has box
    input_boxes_labels=[None, [1]],  # Positive box for second image
    return_tensors="pt"
).to(model.device)

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

# Post-process results for both images
results = processor.post_process_instance_segmentation(
    outputs,
    threshold=0.5,
    mask_threshold=0.5,
    target_sizes=inputs.get("original_sizes").tolist()
)
# Both images processed in single forward pass

セマンティックセグメンテーションの出力

SAM3 は、インスタンスマスクに加えてセマンティックセグメンテーションも提供します:

inputs = processor(images=image, text="ear", return_tensors="pt").to(model.device)

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

# Instance segmentation masks
instance_masks = torch.sigmoid(outputs.pred_masks)  # [batch, num_queries, H, W]

# Semantic segmentation (single channel)
semantic_seg = outputs.semantic_seg  # [batch, 1, H, W]

print(f"Instance masks: {instance_masks.shape}")
print(f"Semantic segmentation: {semantic_seg.shape}")

単一画像での効率的なマルチプロンプト推論

同じ画像に対して複数のテキストプロンプトを実行する場合は、冗長な計算を避けるために、ビジョン埋め込みを事前計算してください。

from transformers import Sam3Processor, Sam3Model
import torch
from PIL import Image
import requests


model = Sam3Model.from_pretrained("facebook/sam3", device_map="auto")
processor = Sam3Processor.from_pretrained("facebook/sam3")

# Load image
image_url = "http://images.cocodataset.org/val2017/000000077595.jpg"
image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")

# Pre-process image and compute vision embeddings once
img_inputs = processor(images=image, return_tensors="pt").to(model.device)
with torch.no_grad():
    vision_embeds = model.get_vision_features(pixel_values=img_inputs.pixel_values)

# Run multiple text prompts efficiently
text_prompts = ["ear", "eye", "nose"]
all_results = []

for prompt in text_prompts:
    text_inputs = processor(text=prompt, return_tensors="pt").to(model.device)
    with torch.no_grad():
        outputs = model(vision_embeds=vision_embeds, **text_inputs)
...
    results = processor.post_process_instance_segmentation(
        outputs,
        threshold=0.5,
        mask_threshold=0.5,
        target_sizes=img_inputs.get("original_sizes").tolist()
    )[0]
    all_results.append({"prompt": prompt, "results": results})

for item in all_results:
    print(f"Prompt '{item['prompt']}': {len(item['results']['masks'])} objects found")

複数の画像に対する効率的なシングルプロンプト推論

複数の画像に対して同じテキストプロンプトを実行する場合は、冗長な計算を避けるために、テキスト埋め込みを事前計算してください。

from transformers import Sam3Processor, Sam3Model
import torch
from PIL import Image
import requests


model = Sam3Model.from_pretrained("facebook/sam3", device_map="auto")
processor = Sam3Processor.from_pretrained("facebook/sam3")

# Pre-compute text embeddings once
text_prompt = "ear"
text_inputs = processor(text=text_prompt, return_tensors="pt").to(model.device)
with torch.no_grad():
    text_embeds = model.get_text_features(**text_inputs)

# Load multiple images
image_urls = [
    "http://images.cocodataset.org/val2017/000000077595.jpg",
    "http://images.cocodataset.org/val2017/000000039769.jpg",
]
images = [Image.open(requests.get(url, stream=True).raw).convert("RGB") for url in image_urls]

# Run inference on each image reusing text embeddings
# Note: attention_mask must be passed along with text_embeds for proper masking
all_results = []

for image in images:
    img_inputs = processor(images=image, return_tensors="pt").to(model.device)
    with torch.no_grad():
        outputs = model(
            pixel_values=img_inputs.pixel_values,
            text_embeds=text_embeds,
            attention_mask=text_inputs.attention_mask,
        )
...
    results = processor.post_process_instance_segmentation(
        outputs,
        threshold=0.5,
        mask_threshold=0.5,
        target_sizes=img_inputs.get("original_sizes").tolist()
    )[0]
    all_results.append(results)

for i, results in enumerate(all_results):
    print(f"Image {i+1}: {len(results['masks'])} '{text_prompt}' objects found")

カスタム解像度推論

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

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

config = Sam3Config.from_pretrained("facebook/sam3")
config.image_size = 560
model = Sam3Model.from_pretrained("facebook/sam3", config=config, device_map="auto")
processor = Sam3Processor.from_pretrained("facebook/sam3", size={"height": 560, "width": 560})

プロンプトのラベル規約

SAM3では、以下のラベル規約を使用します。

点とボックスについて:

  • 1: ポジティブプロンプト(この領域/オブジェクトを含める)
  • 0: 否定プロンプト(この領域/オブジェクトを除外)
  • -10: バッチ入力用のパディング値

座標形式:

  • 入力ボックス: ピクセル座標の [x1, y1, x2, y2] (xyxy 形式)
  • 出力ボックス(生データ): [x1, y1, x2, y2](xyxy形式)、[0, 1]に正規化済み
  • 出力ボックス(後処理済み): [x1, y1, x2, y2](xyxy形式)の絶対ピクセル座標

Sam3Config

class transformers.Sam3Config

< >

( 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 = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonegeometry_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonedetr_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonedetr_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonemask_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneinitializer_range: float = 0.02 )

パラメータ

  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig]、任意) — ビジョンバックボーンの config オブジェクトまたは辞書です。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig]、省略可) — テキストバックボーンの設定オブジェクトまたは辞書。
  • geometry_encoder_config (dict または Sam3GeometryEncoderConfig、省略可) — ジオメトリエンコーダーの設定です。
  • detr_encoder_config (dict または Sam3DETREncoderConfig、任意) — DETR エンコーダーの設定です。
  • detr_decoder_config (dict または Sam3DETRDecoderConfig、省略可) — DETR デコーダーの設定です。
  • mask_decoder_config (dict または Sam3MaskDecoderConfig、省略可) — マスクデコーダーの設定です。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。

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

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

例:

>>> from transformers import Sam3Config, Sam3Model

>>> # Initializing a SAM3 configuration
>>> configuration = Sam3Config()

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

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

Sam3ViTConfig

クラス transformers.Sam3ViTConfig

< >

( 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 = 1024intermediate_size: int = 4736num_hidden_layers: int = 32num_attention_heads: int = 16num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 1008patch_size: int | list[int] | tuple[int, int] = 14hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06attention_dropout: float | int = 0.0window_size: int = 24global_attn_indexes: list[int] | None = Nonelayer_scale_init_value: float | None = Nonepretrain_image_size: int | list[int] | tuple[int, int] = 336hidden_dropout: float | int = 0.0initializer_range: float = 0.02rope_parameters: dict | None = None )

パラメータ

  • hidden_size (int、任意、デフォルトは 1024) — 隠れ表現の次元数。
  • intermediate_size (int、任意、デフォルトは 4736) — MLP 表現の次元数。
  • num_hidden_layers (int、任意、デフォルトは 32) — Transformer デコーダーの隠れ層の数。
  • num_attention_heads (int、任意、デフォルトは 16) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。
  • num_channels (int、任意、デフォルトは3) — 入力チャネル数。
  • image_size (Union[int, list[int], tuple[int, int]]、任意、デフォルトは 1008) — 各画像のサイズ(解像度)。
  • patch_size (Union[int, list[int], tuple[int, int]]、任意、デフォルトは14) — 各パッチのサイズ(解像度)です。
  • hidden_act (str、任意、デフォルトは gelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、 "relu"、"silu" など。
  • layer_norm_eps (float、任意、デフォルトは 1e-06) — レイヤーノーマル層で使用する epsilon です。
  • attention_dropout (Union[float, int]、任意、デフォルトは 0.0) — アテンション確率のドロップアウト率です。
  • window_size (int, 任意、デフォルトは 24) — ウィンドウ付きアテンションのウィンドウサイズ。
  • global_attn_indexes (list[int]、任意、デフォルトは [7, 15, 23, 31]) — グローバルアテンションを持つレイヤーのインデックス。
  • layer_scale_init_value (float, 任意) — 自己アテンション層で使用するスケール値です。base モデルでは 0.1、large モデルでは 1e-6 を使用します。0 に設定すると、layer scale を無効にします。
  • pretrain_image_size (int、任意、デフォルトは 336)— 位置埋め込みの初期化に使用する事前学習モデルの画像サイズ。
  • hidden_dropout (float、任意、デフォルト値は 0.0)— 隠れ状態の Dropout 確率です。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
  • rope_parameters (dict, 任意) — RoPE 埋め込みの設定パラメータを含む辞書です。辞書には rope_theta の値が含まれており、より長い max_position_embeddings で RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。

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

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

Sam3VisionConfig

class transformers.Sam3VisionConfig

< >

( 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 = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonefpn_hidden_size: int = 256backbone_feature_sizes: list | None = Nonescale_factors: list[float] | None = Nonehidden_act: str = 'gelu'layer_norm_eps: float = 1e-06initializer_range: float = 0.02 )

パラメータ

  • backbone_config (Union[dict, ~configuration_utils.PreTrainedConfig], 任意) — バックボーンモデルの設定です。
  • fpn_hidden_size (int, 任意、デフォルトは 256) — FPN の隠れ層の次元数です。
  • backbone_feature_sizes (List[List[int]]、任意、デフォルトは [[288, 288], [144, 144], [72, 72]]) — バックボーンから異なるスケールで出力される特徴マップの空間サイズ(高さ、幅)です。
  • scale_factors (list[float]、任意、デフォルトは [4.0, 2.0, 1.0, 0.5]) — FPN のマルチスケール特徴量用のスケール係数です。各 FPN レベルに対するスケーリング係数のリストです。
  • hidden_act (str、任意、デフォルトは gelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、 "relu"、"silu" など。
  • layer_norm_eps (float、任意、デフォルトは 1e-06) — レイヤーノーマル層で使用する epsilon です。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。

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

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

Sam3GeometryEncoderConfig

class transformers.Sam3GeometryEncoderConfig

< >

( 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 = 256num_layers: int = 3num_attention_heads: int = 8intermediate_size: int = 2048dropout: float | int = 0.1hidden_act: str = 'relu'hidden_dropout: float | int = 0.0layer_norm_eps: float = 1e-06roi_size: int = 7initializer_range: float = 0.02 )

パラメータ

  • hidden_size (int、任意、デフォルトは 256) — 隠れ表現の次元数。
  • num_layers (int、任意、デフォルトは 3) — Transformer デコーダーの隠れ層の数。
  • num_attention_heads (int、任意、デフォルトは 8) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。
  • intermediate_size (int、任意、デフォルトは2048) — MLP 表現の次元数。
  • dropout (Union[float, int]、任意、デフォルト値は0.1) — すべての dropout レイヤーの比率です。
  • hidden_act (str、任意、デフォルトは relu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、 "relu"、"silu" など。
  • hidden_dropout (Union[float, int]、任意、デフォルト値は 0.0) — embeddings、encoder、pooler 内のすべての全結合層における dropout 確率です。
  • layer_norm_eps (float、任意、デフォルトは 1e-06) — レイヤーノーマル層で使用する epsilon です。
  • roi_size (int、任意、デフォルトは 7) — ボックスプーリング操作の ROI サイズ。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。

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

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

Sam3DETREncoderConfig

クラス transformers.Sam3DETREncoderConfig

< >

( 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 = 256num_layers: int = 6num_attention_heads: int = 8intermediate_size: int = 2048dropout: float | int = 0.1hidden_act: str = 'relu'hidden_dropout: float | int = 0.0layer_norm_eps: float = 1e-06initializer_range: float = 0.02 )

パラメータ

  • hidden_size (int、任意、デフォルトは 256) — 隠れ表現の次元数。
  • num_layers (int、任意、デフォルトは6) — Transformerデコーダーの隠れ層の数。
  • num_attention_heads (int、任意、デフォルトは 8) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。
  • intermediate_size (int、任意、デフォルトは2048) — MLP 表現の次元数。
  • dropout (Union[float, int]、任意、デフォルト値は0.1) — すべての dropout レイヤーの比率です。
  • hidden_act (str、任意、デフォルトは relu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、 "relu"、"silu" など。
  • hidden_dropout (float、任意、デフォルト値は 0.0)— 隠れ状態の Dropout 確率です。
  • layer_norm_eps (float、任意、デフォルトは 1e-06) — レイヤーノーマル層で使用する epsilon です。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。

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

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

Sam3DETRDecoderConfig

クラス transformers.Sam3DETRDecoderConfig

< >

( 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 = 256num_layers: int = 6num_queries: int = 200num_attention_heads: int = 8intermediate_size: int = 2048dropout: float | int = 0.1hidden_act: str = 'relu'hidden_dropout: float | int = 0.0layer_norm_eps: float = 1e-06initializer_range: float = 0.02 )

パラメータ

  • hidden_size (int、任意、デフォルトは 256) — 隠れ表現の次元数。
  • num_layers (int、任意、デフォルトは6) — Transformerデコーダーの隠れ層の数。
  • num_queries (int、任意、デフォルトは 200) — オブジェクトクエリの数。
  • num_attention_heads (int、任意、デフォルトは 8) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。
  • intermediate_size (int、任意、デフォルトは2048) — MLP 表現の次元数。
  • dropout (Union[float, int]、任意、デフォルト値は0.1) — すべての dropout レイヤーの比率です。
  • hidden_act (str、任意、デフォルトは relu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、 "relu"、"silu" など。
  • hidden_dropout (Union[float, int]、任意、デフォルト値は 0.0) — embeddings、encoder、pooler 内のすべての全結合層における dropout 確率です。
  • layer_norm_eps (float、任意、デフォルトは 1e-06) — レイヤーノーマル層で使用する epsilon です。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。

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

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

Sam3MaskDecoderConfig

クラス transformers.Sam3MaskDecoderConfig

< >

( 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 = 256num_upsampling_stages: int = 3layer_norm_eps: float = 1e-06dropout: float | int = 0.0num_attention_heads: int = 8initializer_range: float = 0.02 )

パラメータ

  • hidden_size (int、任意、デフォルトは 256) — 隠れ表現の次元数。
  • num_upsampling_stages (int、任意、デフォルトは 3)— ピクセルデコーダー(FPN)におけるアップサンプリングのステージ数。
  • layer_norm_eps (float、任意、デフォルトは 1e-06) — レイヤーノーマル層で使用する epsilon です。
  • dropout (Union[float, int]、省略可、デフォルト値は0.0) — すべての dropout レイヤーの比率です。
  • num_attention_heads (int、任意、デフォルトは 8) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。

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

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

Sam3Processor

クラス transformers.Sam3Processor

< >

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

パラメータ

  • image_processor (Sam3ImageProcessor) — 画像プロセッサは必須の入力です。
  • tokenizer (CLIPTokenizer) — トークナイザーは必須の入力です。
  • target_size (int, 任意) — 画像をリサイズする対象サイズ (target_size, target_size)。
  • point_pad_value (int、省略可能、デフォルトは -10) — 入力ボックスのパディングに使用される値です。

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

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

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = 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_boxes: typing.Union[list[list[list[float]]], torch.Tensor, NoneType] = Noneinput_boxes_labels: typing.Union[list[list[list[int]]], 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 (ImageInput、任意) — 処理対象の画像です。
  • text (str、list[str]、list[list[str]]、任意) — 処理対象のテキストです。
  • segmentation_maps (ImageInput、任意) — 処理対象のセグメンテーションマップです。
  • input_boxes (list[list[list[float]]]、torch.Tensor、省略可) — 処理するバウンディングボックスです。
  • input_boxes_labels (list[list[int]]、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_boxes_labels (torch.Tensor): 処理済みのバウンディングボックスのラベル。
  • input_boxes (torch.Tensor): 処理済みのバウンディングボックス。

Sam3ImageProcessor

class transformers.Sam3ImageProcessor

< >

( **kwargs: *<class 'transformers.models.sam3.image_processing_sam3.Sam3ImageProcessorKwargs'> )

パラメータ

  • 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' -- 1008, 'width': 1008}): モデルへの最大入力サイズを指定します。
  • default_to_square (bool、kwargs、任意、デフォルトは True) — 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, デフォルトは 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、任意、デフォルトは [0.5, 0.5, 0.5]) — 正規化に使用する画像の平均値。do_normalize が True に設定されている場合のみ有効です。
  • image_std (Union[float, list[float], tuple[float, ...]]、kwargs、optional、デフォルト値は [0.5, 0.5, 0.5]) — 正規化に使用する画像の標準偏差。do_normalize が True に設定されている場合のみ有効です。
  • do_pad (bool、kwargs、optional、デフォルトは None) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせて行われるか、画像ごとに固定の正方形サイズに合わせて行われます。具体的なパディング戦略はモデルによって異なります。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, デフォルトは None) — 画像をパディングするサイズを {"height": int, "width" int} で指定します。前処理用に提供されたすべての画像サイズより大きい必要があります。pad_size が指定されない場合、バッチ内の最大の幅と高さにパディングされます。do_pad=True. の場合のみ適用されます。
  • do_center_crop (bool, kwargs, optional) — 画像を中央クロップするかどうかを指定します。
  • 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) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt' に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。
  • disable_grouping (bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。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}。

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

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.sam3.image_processing_sam3.Sam3ImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature

パラメータ

  • 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、任意) — 画像を RGB に変換するかどうかを指定します。
  • do_resize (bool、kwargs、optional) — 画像をリサイズするかどうか。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — モデルへの最大入力次元を記述します。
  • default_to_square (bool、kwargs、任意) — サイズが整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。
  • 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、optional) — 画像をリスケールするかどうかを指定します。
  • rescale_factor (float、kwargs、任意) — do_rescale が True に設定されている場合、画像をリスケールするための係数。
  • do_normalize (bool, kwargs, optional) — 画像を正規化するかどうかを指定します。
  • image_mean (Union[float, list[float], tuple[float, ...]]、kwargs、optional) — 正規化に使用する画像の平均値。do_normalize が True に設定されている場合のみ有効です。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, optional) — 正規化に使用する画像の標準偏差。do_normalize が True に設定されている場合のみ有効です。
  • do_pad (bool, kwargs, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。
  • 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、任意) — サポートされているのは 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) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt' に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。
  • disable_grouping (bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。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 を指定できます。

Sam3ViTModel

class transformers.Sam3ViTModel

< >

( config: Sam3ViTConfig )

パラメータ

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

Sam3の生モデルで、特定のヘッドを上に載せず、生のhidden-statesを出力します。

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

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

forward

< >

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

パラメータ

戻り値

BaseModelOutput または tuple(torch.FloatTensor)

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

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

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

  • last_hidden_state (torch.FloatTensor、shape (batch_size, sequence_length, hidden_size)) — モデルの最終層の出力における隠れ状態のシーケンス。

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

Sam3VisionModel

class transformers.Sam3VisionModel

< >

( config: Sam3VisionConfig )

パラメータ

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

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

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

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

forward

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )

Sam3Model

class transformers.Sam3Model

< >

( config: Sam3Config )

forward

< >

( pixel_values: typing.Optional[torch.FloatTensor] = Nonevision_embeds: transformers.models.sam3.modeling_sam3.Sam3VisionEncoderOutput | None = Noneinput_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonetext_embeds: typing.Optional[torch.FloatTensor] = Noneinput_boxes: typing.Optional[torch.FloatTensor] = Noneinput_boxes_labels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Sam3ImageSegmentationOutput or tuple(torch.FloatTensor)

パラメータ

  • pixel_values (torch.FloatTensor、形状 (batch_size, num_channels, image_size, image_size)、任意) — 入力画像に対応するテンソルです。ピクセル値は Sam3ImageProcessor を使用して取得できます。詳細については Sam3ImageProcessor.call() を参照してください(Sam3Processor は画像の処理に Sam3ImageProcessor を使用します)。
  • vision_embeds (Sam3VisionEncoderOutput、任意) — 事前計算済みのビジョン埋め込みです。ビジョン埋め込みを簡単に再利用できます。指定した場合、pixel_values は渡さないでください。pixel_values とは排他的です。
  • input_ids (torch.LongTensor の形状 (batch_size, sequence_length), 、省略可) — 語彙における入力シーケンスのトークンインデックスです。デフォルトではパディングは無視されます。

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

    入力IDとは何ですか?

  • attention_mask (torch.Tensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

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

  • text_embeds (torch.FloatTensor、形状 (batch_size, sequence_length, hidden_size)、任意) — 事前計算されたテキスト埋め込み。テキスト埋め込みを簡単に再利用するために使用できます。指定した場合、input_ids は渡すべきではありません。input_ids とは排他的です。
  • input_boxes (torch.FloatTensor、shape (batch_size, num_boxes, 4)、任意) — [0, 1] の範囲で正規化されたボックス座標。(cx, cy, w, h) の形式です。
  • input_boxes_labels (torch.LongTensor、形状 (batch_size, num_boxes)、任意) — ボックスのラベル: 1 (正)、0 (負)。

戻り値

Sam3ImageSegmentationOutput または tuple(torch.FloatTensor)

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

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

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

  • pred_masks (torch.FloatTensor、shape (batch_size, num_queries, height, width)) — 各クエリに対する予測セグメンテーションマスク。
  • pred_boxes (torch.FloatTensor、shape (batch_size, num_queries, 4)) — (x1, y1, x2, y2) 形式で予測されたバウンディングボックス。
  • pred_logits (torch.FloatTensor、shape (batch_size, num_queries)、optional) — 各クエリに対する分類の信頼度スコア。デコーダのクエリ特徴量とテキスト特徴量の間の内積によって計算されます。
  • presence_logits (torch.FloatTensor、shape (batch_size, 1)、任意) — DETR デコーダーの presence トークンからの presence logits(最終層のみ)。シーン内にオブジェクトが存在するかどうかを示します。pred_logits と乗算することで最終スコアを計算できます: final_scores = pred_logits.sigmoid() * presence_logits.sigmoid()。
  • semantic_seg (torch.FloatTensor、shape (batch_size, 1, height, width)、任意) — セマンティックセグメンテーションの出力。
  • decoder_hidden_states (tuple[torch.FloatTensor]、optional) — DETR のデコーダー各層からの隠れ状態のタプル。各テンソルの形状は (batch_size, num_queries, hidden_size) です。
  • decoder_reference_boxes (torch.FloatTensor、shape (num_layers, batch_size, num_queries, 4)、optional) — DETR のすべての decoder レイヤーからの参照ボックス。
  • encoder_hidden_states (tuple[torch.FloatTensor]、optional) — DETRエンコーダーの全レイヤーからの隠れ状態のタプル。
  • vision_hidden_states (tuple[torch.FloatTensor]、optional) — 全ビジョンエンコーダー(ViT)層からの隠れ状態のタプル。
  • vision_attentions (tuple[torch.FloatTensor]、optional) — ビジョンエンコーダー(ViT)レイヤーからのアテンション重み。
  • detr_encoder_attentions (tuple[torch.FloatTensor]、任意) — DETRエンコーダ層からのアテンション重み。
  • detr_decoder_attentions (tuple[torch.FloatTensor]、任意) — DETR デコーダー層からのアテンション重み(自己アテンションとクロスアテンション)。
  • mask_decoder_attentions (tuple[torch.FloatTensor]、任意) — マスクデコーダー層からのアテンション重み。

例:

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

>>> model = AutoModel.from_pretrained("facebook/sam3")
>>> processor = AutoProcessor.from_pretrained("facebook/sam3")

>>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam-car.png"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read())).convert("RGB")
>>> text = "car"
>>> inputs = processor(images=image, text=text, return_tensors="pt")

>>> # Get segmentation output
>>> outputs = model(**inputs)
>>> pred_masks = outputs.pred_masks
>>> pred_boxes = outputs.pred_boxes

get_text_features

< >

( input_ids: LongTensorattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.FloatTensor)

パラメータ

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

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

    入力IDとは何ですか?

  • attention_mask (torch.Tensor の形状 (batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。 [0, 1]:
    • マスクされていないトークンに対して1
    • マスクされたトークンに対しては 0 です。

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

戻り値

BaseModelOutputWithPooling または tuple(torch.FloatTensor)

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

  • last_hidden_state (torch.FloatTensor、shape (batch_size, sequence_length, hidden_size)) — モデルの最終層の出力における隠れ状態のシーケンス。

  • pooler_output (torch.FloatTensor、shape (batch_size, hidden_size)) — 補助事前学習タスクに使用される層をさらに通して処理された後、シーケンスの最初のトークン(分類トークン)の最終層の隠れ状態。例えば、BERT 系のモデルでは、線形層と tanh 活性化関数を経て処理された後の分類トークンを返します。この線形層の重みは、事前学習中の次文予測(分類)目的から学習されます。

  • hidden_states (tuple(torch.FloatTensor)、optional、output_hidden_states=True が渡された場合または config.output_hidden_states=True の場合に返されます)— torch.FloatTensor のタプル(埋め込み層を持つモデルの場合、埋め込みの出力が 1 つ、各層の出力がそれぞれ 1 つずつ)で、形状は (batch_size, sequence_length, hidden_size) です。

    各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。

  • attentions (tuple(torch.FloatTensor)、optional、output_attentions=True が渡された場合または config.output_attentions=True の場合に返されます)— torch.FloatTensor のタプル(各レイヤーごとに1つ)、形状は (batch_size, num_heads, sequence_length, sequence_length)。

    アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。

例:

>>> from transformers import Sam3Model, Sam3Processor
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> model = Sam3Model.from_pretrained("facebook/sam3")
>>> processor = Sam3Processor.from_pretrained("facebook/sam3")

>>> # Pre-compute text embeddings
>>> text_inputs = processor(text="cat", return_tensors="pt")
>>> text_embeds = model.get_text_features(**text_inputs).pooler_output

>>> # Reuse text embeddings for multiple images
>>> url = "http://images.cocodataset.org/val2017/000000077595.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> img_inputs = processor(images=image, return_tensors="pt")
>>> outputs = model(pixel_values=img_inputs.pixel_values, text_embeds=text_embeds)
Update on GitHub