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 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만 개의 고유한 개념 라벨(어려운 음수 포함)을 포함하는 고품질 데이터셋을 생성하는 확장 가능한 데이터 엔진을 구축했습니다. 우리의 모델은 단일 백본을 공유하는 이미지 수준의 감지기와 메모리 기반 비디오 트래커로 구성됩니다. 존재 헤드(presence head)를 통해 인식과 위치 파악을 분리하여 감지 정확도를 높였습니다. SAM 3은 이미지와 비디오 PCS 모두에서 기존 시스템의 정확도를 2배로 높였으며, 시각 분할 작업에서 이전 SAM의 기능을 향상시켰습니다. 우리는 프롬프트 기반 개념 분할을 위한 새로운 Segment Anything with Concepts(SA-Co) 벤치마크와 함께 SAM 3을 오픈소스로 공개합니다.

이 모델은 yonigozlan과 ronghanghu에 의해 기여되었습니다.

사용 예시

비디오 분할 및 추적

사전 로드된 비디오 추론

이미 모든 프레임이 준비된 비디오를 텍스트 프롬프트로 처리합니다:

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}")

여러 프롬프트를 제공하여 여러 개체 카테고리를 동시에 추적할 수도 있습니다. 모델은 모든 프롬프트에 걸쳐 시각 기능을 효율적으로 재사용합니다:

# 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는 프레임이 도착하는 대로 처리할 수 있습니다:

# 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 해상도로 사용하도록 설계되었습니다.

더 빠른 추론 또는 더 낮은 메모리 사용량을 위해:

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_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 = Nonedetector_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetracker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneinitializer_range: float = 0.02low_res_mask_size: int = 288score_threshold_detection: float = 0.5det_nms_thresh: float = 0.1assoc_iou_thresh: float = 0.1trk_assoc_iou_thresh: float = 0.5new_det_thresh: float = 0.7recondition_on_trk_masks: bool = Truehotstart_delay: int = 15hotstart_unmatch_thresh: int = 8hotstart_dup_thresh: int = 8suppress_unmatched_only_within_hotstart: bool = Trueinit_trk_keep_alive: int = 30max_trk_keep_alive: int = 30min_trk_keep_alive: int = -1suppress_overlapping_based_on_recent_occlusion_threshold: float = 0.7decrease_trk_keep_alive_for_empty_masklets: bool = Falsefill_hole_area: int = 16max_num_objects: int = 10000recondition_every_nth_frame: int = 16high_conf_thresh: float = 0.8high_iou_thresh: float = 0.8 )

매개변수

  • detector_config (dict 또는 Sam3Config, 선택) — Sam3 detector 모델의 설정입니다. 제공되지 않으면 기본 Sam3Config가 사용됩니다.
  • tracker_config (dict 또는 Sam2VideoConfig, 선택) — Sam2Video 트래커 모델의 설정입니다. 제공되지 않으면 기본 Sam2VideoConfig가 사용됩니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 가중치 행렬 초기화에 사용되는 truncated_normal_initializer의 표준 편차입니다.
  • low_res_mask_size (int, 선택 사항, 기본값 288) — 트래커가 비디오 해상도로 업샘플링하기 전에 생성하는 저해상도 마스크 출력의 크기(높이와 너비).
  • score_threshold_detection (float, 선택 사항, 기본값 0.5) — 탐지 출력의 확률 임계값입니다. 이 임계값을 초과하는 탐지 결과만 유지합니다.
  • det_nms_thresh (float, 선택 사항, 기본값 0.1) — 탐지 NMS(Non-Maximum Suppression)에 사용되는 IoU 임계값입니다.
  • assoc_iou_thresh (float, 선택 사항, 기본값 0.1) — 검출과 트랙 매칭을 위한 IoU 임계값. 검출 결과가 이 임계값 이상으로 트랙렛과 겹치는 경우 해당 트랙렛과 “매칭”된 것으로 간주됩니다. 일반적으로 0.1과 같은 느슨한 임계값을 사용합니다.
  • trk_assoc_iou_thresh (float, 선택 사항, 기본값 0.5) — 검출-트랙 매칭에 사용되는 IoU 임계값으로, masklet이 어떤 검출에도 “미매칭” 상태인지 판단하는 데 사용됩니다. 일반적으로 0.5와 같이 더 엄격한 임계값을 사용합니다.
  • new_det_thresh (float, 선택 사항, 기본값 0.7) — 새로운 객체로 추가될 탐지의 확률 임계값.
  • recondition_on_trk_masks (bool, 선택 사항, 기본값 True) — 재조건화(reconditioning)에 추적 마스크(True)를 사용할지, 아니면 감지 마스크(False)를 사용할지를 결정합니다. 추적 마스크의 품질이 더 높고, 감지기가 메모리를 강화하고 드리프트를 방지하기 위한 검증 신호로 기능하는 경우 True를 사용하세요.
  • hotstart_delay (int, 선택 사항, 기본값 15) — hotstart 동안 버퍼링할 출력 프레임 수입니다. hotstart_delay 프레임 동안 출력을 보류한 후, hotstart 휴리스틱에 따라 tracklet을 제거합니다.
  • hotstart_unmatch_thresh (int, 선택 사항, 기본값 8) — hotstart 기간 동안 tracklet을 제거하는 데 필요한 미일치 프레임 수입니다.
  • hotstart_dup_thresh (int, 선택 사항, 기본값 8) — hotstart 기간 동안 중복 tracklet을 제거하는 데 필요한 겹치는 프레임 수입니다.
  • suppress_unmatched_only_within_hotstart (bool, 선택 사항, 기본값 True) — hotstart 기간 내에서만 mask를 억제할지 여부입니다. False인 경우, hotstart 기간보다 이전에 시작하더라도 mask를 억제할 수 있습니다.
  • init_trk_keep_alive (int, 선택 사항, 기본값 30) — 새 트랙의 초기 keep-alive 카운터입니다.
  • max_trk_keep_alive (int, 선택 사항, 기본값 30) — 최대 keep-alive 카운터 값입니다. 감지 결과와 매칭된 트랙의 카운터는 이 값까지 증가합니다.
  • min_trk_keep_alive (int, 선택 사항, 기본값 -1) — 최소 keep-alive 카운터 값입니다. 감지 결과와 매칭되지 않은 트랙의 카운터는 이 값으로 감소합니다.
  • suppress_overlapping_based_on_recent_occlusion_threshold (float, 선택 사항, 기본값 0.7) — 최근 가림에 기반하여 겹치는 객체를 억제하는 임계값입니다. 이 임계값보다 IoU가 높은 겹치는 마스크는 가장 최근에 가려진 객체를 기준으로 억제됩니다.
  • decrease_trk_keep_alive_for_empty_masklets (bool, 선택 사항, 기본값 False) — SAM2 예측에서 면적이 0인 masklet에 대해 keep-alive 카운터를 감소할지 여부입니다.
  • fill_hole_area (int, 선택 사항, 기본값 16) — 마스크의 구멍을 채우고 작은 노이즈를 제거할 때 적용되는 최소 영역(픽셀 단위).
  • max_num_objects (int, 선택 사항, 기본값 10000) — 추적할 객체의 최대 수입니다. 기본값 10000은 사실상 이 제한을 해제합니다.
  • recondition_every_nth_frame (int, 선택 사항, 기본값 16) — 마스크 재조건화 빈도(프레임 단위). 재조건화를 비활성화하려면 0으로 설정하세요.
  • high_conf_thresh (float, 선택 사항, 기본값 0.8) — 재조건화(reconditioning)에 사용되는 높은 신뢰도 임계값입니다. 이 임계값을 초과하는 탐지 결과만 tracklet을 재조건화할 수 있습니다.
  • high_iou_thresh (float, 선택 사항, 기본값 0.8) — 재조건화(reconditioning)에 사용되는 높은 IoU 임계값입니다. 이 임계값보다 IoU가 높은 검출 결과만 tracklet을 재조건화할 수 있습니다.

이것은 Sam3VideoModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Sam3 Video 모델을 초기화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 초기화하면 facebook/sam3와 유사한 설정이 생성됩니다.

Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.

예:

>>> 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

class transformers.Sam3VideoProcessor

< >

( image_processorvideo_processortokenizertarget_size: int | None = None**kwargs )

매개변수

  • image_processor (Sam3ImageProcessor) — 이미지 프로세서는 필수 입력값입니다.
  • video_processor (video_processor_class) — video processor는 필수 입력값입니다.
  • tokenizer (CLIPTokenizer) — 토크나이저는 필수 입력값입니다.
  • target_size (int, 선택 사항) — 이미지가 리사이즈될 대상 크기(target_size, target_size).

이미지 프로세서, 비디오 프로세서, 토크나이저를 단일 프로세서로 묶는 Sam3VideoProcessor를 생성합니다.

Sam3VideoProcessor는 Sam3ImageProcessor, video_processor_class, CLIPTokenizer의 모든 기능을 제공합니다. 자세한 내용은 ~Sam3ImageProcessor, ~video_processor_class, ~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] = Nonesegmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['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, 선택 사항) — 처리할 이미지입니다.
  • 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

  • pixel_values (torch.Tensor): 처리된 이미지(들).
  • original_sizes (list[list[float]]): 이미지의 원래 크기입니다.
  • labels (torch.Tensor, 선택 사항): 처리된 분할 맵(제공된 경우).

postprocess_outputs

< >

( inference_sessionmodel_outputsoriginal_sizes: typing.Union[list[list[float]], torch.Tensor, NoneType] = None ) → dict

매개변수

  • inference_session (Sam3VideoInferenceSession) — 추론 세션 객체입니다.
  • model_outputs (Sam3VideoSegmentationOutput) — Sam3VideoModel.forward()의 원시 모델 출력입니다.
  • original_sizes (list[list[float]] 또는 torch.Tensor, 선택) — 선택 사항인 원본 프레임 크기 [height, width]입니다. 세션에서 video_height/video_width가 설정되지 않은 경우 스트리밍 추론에 필요합니다.

반환값

dict

다음 키를 포함하는 사전:

  • object_ids (torch.Tensor, shape (num_objects,)): 각 감지된 객체에 대한 객체 ID.
  • scores (torch.Tensor, shape (num_objects,)): 각 객체에 대한 감지 점수.
  • boxes (torch.Tensor, shape (num_objects, 4)): XYXY 형식의 바운딩 박스 (top_left_x, top_left_y, bottom_right_x, bottom_right_y).
  • masks (torch.Tensor, shape (num_objects, height, width)): 원본 비디오 해상도에서 각 객체에 대한 바이너리 세그멘테이션 마스크
  • prompt_to_obj_ids (dict[str, list[int]]): 프롬프트 텍스트에서 해당 프롬프트가 감지한 객체 ID 목록으로의 매핑.

모델 출력을 후처리하여 최종 마스크, 박스, 점수를 얻습니다.

init_video_session

< >

( video: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneinference_device: typing.Union[str, ForwardRef('torch.device')] = 'cpu'inference_state_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Noneprocessing_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Nonevideo_storage_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = Nonemax_vision_features_cache_size: int = 1dtype: dtype = torch.float32 )

매개변수

  • video (VideoInput, 선택 사항) — 처리할 비디오입니다. 스트리밍 중에는 제공할 필요가 없습니다.
  • inference_device (str 또는 torch.device, 선택 사항, 기본값은 “cpu”) — 추론에 사용할 장치입니다.
  • inference_state_device (str 또는 torch.device, 선택 사항) — 추론 상태를 저장할 장치입니다.
  • processing_device (str 또는 torch.device, 선택 사항) — 비디오 처리에 사용할 장치입니다.
  • video_storage_device (str 또는 torch.device, 선택 사항) — 처리된 비디오 프레임을 저장할 장치입니다.
  • max_vision_features_cache_size (int, 선택 사항, 기본값 1) — 캐시할 최대 비전 특징 수입니다.
  • dtype (torch.dtype, 선택 사항, 기본값 torch.float32) — 세션 전체에 사용할 torch dtype입니다.

추론을 위한 비디오 세션을 초기화합니다. 비디오가 제공된 경우(비동기 추론), 비디오가 처리되어 video_storage_device에 저장됩니다.

add_text_prompt

< >

( inference_session: Sam3VideoInferenceSessiontext: str | list[str] ) → Sam3VideoInferenceSession

매개변수

  • inference_session (Sam3VideoInferenceSession) — 추론 세션입니다.
  • text (str 또는 list[str]) — 추가할 텍스트 프롬프트입니다.

반환값

Sam3VideoInferenceSession

추가된 텍스트 프롬프트가 포함된 추론 세션입니다.

추론 세션에 텍스트 프롬프트를 추가합니다.

Sam3VideoInferenceSession

class transformers.Sam3VideoInferenceSession

< >

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

매개변수

  • video (torch.Tensor, 선택 사항) — 처리할 비디오입니다. 스트리밍하는 경우 제공할 필요가 없습니다.
  • video_height (int, 선택 사항) — 비디오의 높이입니다.
  • video_width (int, 선택 사항) — 영상의 너비입니다.
  • inference_device (torch.device, 선택 사항, 기본값 "cpu") — 추론에 사용할 장치입니다.
  • inference_state_device (torch.device, 선택 사항, 기본값 "cpu") — 추론 상태를 저장할 장치입니다.
  • video_storage_device (torch.device, 선택 사항, 기본값 "cpu") — 영상을 저장할 디바이스입니다.
  • dtype (torch.dtype, 선택 사항, 기본값 "float32") — 동영상에 사용할 dtype입니다.
  • max_vision_features_cache_size (int, 선택 사항, 기본값 1) — 캐시할 최대 비전 특징 수입니다.

비디오 추론 세션의 매개변수, 상태 및 캐시를 관리합니다.

add_mask_inputs

< >

( obj_idx: intframe_idx: intinputs: Tensor )

mask 입력을 자동 장치 배치와 함께 추가합니다.

add_new_frame

< >

( pixel_values: Tensorframe_idx: int | None = None )

device 자동 배치로 새 프레임을 추가합니다.

add_prompt

< >

( prompt_text: str )

세션에 텍스트 프롬프트를 추가하고 고유 ID를 반환합니다. 프롬프트가 이미 존재하는 경우, 기존 ID를 반환합니다.

get_frame

< >

( frame_idx: int )

비디오에서 프레임을 가져옵니다.

get_obj_num

< >

( )

이 세션에서 지금까지 수신된 고유한 객체 ID의 총 개수를 가져옵니다.

get_output

< >

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

매개변수

  • obj_idx (int) — 객체의 인덱스.
  • frame_idx (int) — 프레임의 인덱스입니다.
  • output_key (str) — 출력의 키.
  • is_conditioning_frame (bool) — 출력이 conditioning frame용인지 여부.

스마트한 장치 관리를 통해 출력을 가져옵니다.

obj_id_to_idx

< >

( obj_id: int )

필요한 경우 새 항목을 생성하여 object ID를 인덱스에 매핑합니다.

obj_idx_to_id

< >

( obj_idx: int )

모델 측 객체 인덱스를 클라이언트 측 객체 ID로 매핑합니다.

remove_mask_inputs

< >

( obj_idx: intframe_idx: int )

마스크 입력을 제거합니다.

remove_object

< >

( obj_id: intstrict: bool = False )

매개변수

  • obj_id (int) — 제거할 객체 ID입니다.
  • strict (bool, 선택 사항, 기본값 False) — 객체가 존재하지 않을 경우 오류를 발생시킬지 여부.

추론 세션에서 객체를 제거합니다. 이렇게 하면 해당 객체가 비디오의 모든 프레임에서 제거됩니다.

reset_inference_session

< >

( )

추적 데이터와 캐시를 초기화합니다.

reset_state

< >

( )

추론 세션 상태를 초기화합니다.

reset_tracking_data

< >

( )

트래킹 데이터는 초기화하되 캐시는 유지합니다.

store_output

< >

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

매개변수

  • obj_idx (int) — 객체의 인덱스.
  • frame_idx (int) — 프레임의 인덱스입니다.
  • output_key (Optional[str]) — 출력의 키입니다. None인 경우, 출력은 사전으로 저장됩니다.
  • output_value (Optional[Union[torch.Tensor, dict]]) — 출력 값.
  • is_conditioning_frame (bool) — 출력이 conditioning frame용인지 여부.

output_key가 None인 경우, 출력은 사전으로 저장됩니다.

Sam3VideoSegmentationOutput

class transformers.Sam3VideoSegmentationOutput

< >

( object_ids: list[int] | None = Noneobj_id_to_mask: dict[int, torch.Tensor] | None = Noneobj_id_to_score: dict[int, float] | None = Noneobj_id_to_tracker_score: dict[int, float] | None = Noneremoved_obj_ids: set[int] | None = Nonesuppressed_obj_ids: set[int] | None = Noneframe_idx: int | None = None )

매개변수

  • object_ids (list[int], 선택 사항) — 현재 프레임에서 추적 중인 객체 ID 목록입니다.
  • obj_id_to_mask (dict[int, torch.Tensor], 선택) — 객체 ID를 예측된 저해상도 마스크로 매핑하는 사전입니다. 각 마스크의 shape은 (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의 집합(예: hotstart 휴리스틱을 통해 제거된 경우).
  • suppressed_obj_ids (set[int], 선택 사항) — 현재 프레임에서 억제된 객체 ID의 집합입니다.
  • frame_idx (int, 선택 사항) — 동영상의 프레임 인덱스입니다.

Sam3Video 모델의 출력에 대한 기본 클래스입니다.

Sam3VideoModel

class transformers.Sam3VideoModel

< >

( config: Sam3VideoConfig )

매개변수

  • config (Sam3VideoConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

Sam3 Video Model은 특정 헤드가 없는 상태에서 원시 hidden-states를 출력하는 기본 모델입니다.

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( inference_session: Sam3VideoInferenceSessionframe_idx: int | None = Noneframe: typing.Optional[torch.Tensor] = Nonereverse: bool = False**kwargs )

매개변수

  • inference_session (~models.sam3_video.modeling_sam3_video.Sam3VideoInferenceSession) — 비디오 추론 세션 객체입니다.
  • frame_idx (int, 선택 사항) — 추론을 실행할 프레임의 인덱스입니다. 새로 스트리밍된 프레임에 대해 추론을 수행할 경우 제공하지 않아도 됩니다.
  • frame (torch.Tensor, 선택 사항) — 처리할 프레임입니다. 스트리밍 시 제공하세요.
  • reverse (bool, 선택 사항, 기본값 False) — 역방향으로 전파할지 여부입니다.

스트리밍된 비디오 프레임을 통해 객체를 전파합니다.

propagate_in_video_iterator

< >

( inference_session: Sam3VideoInferenceSessionstart_frame_idx: int = 0max_frame_num_to_track: int | None = Nonereverse: bool = Falseshow_progress_bar: bool = False ) → Sam3VideoSegmentationOutput or tuple(torch.Tensor)

매개변수

  • inference_session (~models.sam3_video.modeling_sam3_video.Sam3VideoInferenceSession) — 비디오 추론 세션 객체입니다.
  • start_frame_idx (int, 선택 사항, 기본값 0) — 전파를 시작할 프레임 인덱스입니다.
  • max_frame_num_to_track (int, 선택 사항) — 추적할 최대 프레임 수입니다. 지정하지 않으면 비디오의 모든 프레임이 추적됩니다.
  • reverse (bool, 선택 사항, 기본값 False) — 역방향으로 전파할지 여부입니다.
  • show_progress_bar (bool, 선택 사항, 기본값 False) — 전파 과정에서 진행 표시줄을 표시할지 여부입니다.

반환값

Sam3VideoSegmentationOutput 또는 tuple(torch.Tensor)

torch.Tensor의 튜플 또는 Sam3VideoSegmentationOutput (return_dict=False가 전달되었거나 config.return_dict=False인 경우). 구성(Sam3VideoConfig)과 입력에 따라 다양한 요소를 포함합니다.

전체 비디오에 대한 grounding 결과를 얻기 위해 프롬프트를 전파합니다. 전체 비디오로 추론 세션을 초기화할 때 사용됩니다. 각 프레임에 대해 Sam3VideoSegmentationOutput을 반환합니다.

  • object_ids (list[int], 선택 사항) — 현재 프레임에서 추적 중인 객체 ID 목록.
  • obj_id_to_mask (dict[int, torch.Tensor], 선택) — 객체 ID를 예측된 저해상도 마스크로 매핑하는 사전. 각 마스크의 형상은 (1, H_low, W_low)입니다.
  • obj_id_to_score (dict[int, float], 선택 사항) — 객체 ID를 해당 감지 점수로 매핑하는 사전입니다.
  • obj_id_to_tracker_score (dict[int, float], 선택) — 현재 프레임에서 객체 ID를 해당 tracker 점수로 매핑하는 사전.
  • removed_obj_ids (set[int], 선택 사항) — 제거된 객체 ID의 집합(예: hotstart 휴리스틱을 통해 제거된 경우).
  • suppressed_obj_ids (set[int], 선택 사항) — 현재 프레임에서 억제된 객체 ID의 집합입니다.
  • frame_idx (int, 선택 사항) — 비디오의 프레임 인덱스입니다.
Update on GitHub