# SAM3 Video

    
        
        
    

## Tổng quan

SAM3 (Segment Anything Model 3) được giới thiệu trong [SAM 3: Segment Anything with Concepts](https://ai.meta.com/research/publications/sam-3-segment-anything-with-concepts/).

SAM3 Video thực hiện **Phân đoạn Khái niệm Có thể Gợi ý (Promptable Concept Segmentation - PCS)** trên video. PCS nhận văn bản làm đầu vào (ví dụ: "xe buýt trường học màu vàng") và dự đoán các mặt nạ (mask) thực thể và ngữ nghĩa cho **mọi đối tượng** khớp với khái niệm, đồng thời duy trì danh tính của các đối tượng xuyên suốt các khung hình video.

Mô hình kết hợp một module phát hiện (SAM3) với một module theo dõi (tracker kiểu SAM2) để cho phép theo dõi đối tượng ổn định xuyên suốt các khung hình video bằng cách sử dụng prompt văn bản.

Tóm tắt từ bài báo như sau:

*Chúng tôi giới thiệu Segment Anything Model (SAM) 3, một mô hình thống nhất có khả năng phát hiện, phân đoạn và theo dõi các đối tượng trong ảnh và video dựa trên các prompt khái niệm, được chúng tôi định nghĩa là các cụm danh từ ngắn (ví dụ: "yellow school bus"), các ví dụ hình ảnh, hoặc sự kết hợp của cả hai. Promptable Concept Segmentation (PCS) nhận các prompt như vậy và trả về các mặt nạ phân đoạn cùng với danh tính duy nhất cho tất cả các phiên bản đối tượng khớp. Để thúc đẩy PCS, chúng tôi xây dựng một động cơ dữ liệu có khả năng mở rộng, tạo ra một bộ dữ liệu chất lượng cao với 4 triệu nhãn khái niệm duy nhất, bao gồm cả các âm tính khó, trên cả ảnh và video. Mô hình của chúng tôi bao gồm một bộ phát hiện ở cấp độ ảnh và một bộ theo dõi video dựa trên bộ nhớ, chia sẻ một backbone duy nhất. Nhận dạng và định vị được tách rời bằng một presence head, giúp tăng độ chính xác của việc phát hiện. SAM 3 gấp đôi độ chính xác so với các hệ thống hiện có trong cả PCS trên ảnh và video, đồng thời cải thiện các khả năng trước đó của SAM trên các nhiệm vụ phân đoạn thị giác. Chúng tôi mã nguồn mở SAM 3 cùng với bộ chuẩn đánh giá mới Segment Anything with Concepts (SA-Co) của chúng tôi cho phân đoạn khái niệm có thể prompt.*

Mô hình này được đóng góp bởi [yonigozlan](https://huggingface.co/yonigozlan) và [ronghanghu](https://huggingface.co/ronghanghu).

## Ví dụ sử dụng

### Phân đoạn và Theo dõi Video

#### Suy luận video được nạp trước

Xử lý một video với tất cả các khung hình đã có sẵn bằng các lời nhắc văn bản:

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

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

# Load video frames
from transformers.video_utils import load_video
video_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/bedroom.mp4"
video_frames, _ = load_video(video_url)

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

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

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

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

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

Bạn cũng có thể theo dõi nhiều danh mục đối tượng cùng lúc bằng cách cung cấp nhiều prompt. Mô hình tái sử dụng hiệu quả các đặc trưng thị giác xuyên suốt tất cả các prompt:

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

#### Suy luận Video trực tiếp

⚠️ **Ghi chú về chất lượng suy luận trực tiếp**: Suy luận trực tiếp sẽ vô hiệu hóa các thuật toán khởi động nóng (hotstart heuristics) nhằm loại bỏ các đối tượng không khớp và trùng lặp, vì các thuật toán này cần truy cập vào các khung hình tương lai để đưa ra quyết định chính xác. Điều này có thể dẫn đến nhiều phát hiện dương tính giả và các vết theo dõi đối tượng trùng lặp hơn so với suy luận trên video đã tải trước. Để đạt kết quả tốt nhất, hãy sử dụng suy luận trên video đã tải trước khi tất cả các khung hình đều có sẵn.

Đối với các ứng dụng thời gian thực, SAM3 Video hỗ trợ xử lý các khung hình video ngay khi chúng được nhận:

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

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

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

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

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

#### Suy luận Độ phân giải Tùy chỉnh

⚠️ **Ghi chú về hiệu năng**: Độ phân giải tùy chỉnh có thể làm giảm độ chính xác. Mô hình được thiết kế để sử dụng ở độ phân giải 1008px.

Để suy luận nhanh hơn hoặc sử dụng ít bộ nhớ hơn:

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

## Sam3VideoConfig[[transformers.Sam3VideoConfig]]

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

```python
transformers.Sam3VideoConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, detector_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, tracker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, initializer_range: float = 0.02, low_res_mask_size: int = 288, score_threshold_detection: float = 0.5, det_nms_thresh: float = 0.1, assoc_iou_thresh: float = 0.1, trk_assoc_iou_thresh: float = 0.5, new_det_thresh: float = 0.7, recondition_on_trk_masks: bool = True, hotstart_delay: int = 15, hotstart_unmatch_thresh: int = 8, hotstart_dup_thresh: int = 8, suppress_unmatched_only_within_hotstart: bool = True, init_trk_keep_alive: int = 30, max_trk_keep_alive: int = 30, min_trk_keep_alive: int = -1, suppress_overlapping_based_on_recent_occlusion_threshold: float = 0.7, decrease_trk_keep_alive_for_empty_masklets: bool = False, fill_hole_area: int = 16, max_num_objects: int = 10000, recondition_every_nth_frame: int = 16, high_conf_thresh: float = 0.8, high_iou_thresh: float = 0.8)
```

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/configuration_sam3_video.py#L28)

**Tham số:**

detector_config (`dict` hoặc `Sam3Config`, *tùy chọn*) : Cấu hình cho mô hình detector Sam3. Nếu không được cung cấp, Sam3Config mặc định sẽ được sử dụng.

tracker_config (`dict` hoặc `Sam2VideoConfig`, *không bắt buộc*) : Cấu hình cho mô hình tracker Sam2Video. Nếu không được cung cấp, Sam2VideoConfig mặc định sẽ được sử dụng.

initializer_range (`float`, *optional*, mặc định là 0.02) : Độ lệch chuẩn của truncated_normal_initializer để khởi tạo các ma trận trọng số.

low_res_mask_size (`int`, *optional*, mặc định là 288) : Kích thước (chiều cao và chiều rộng) của các đầu ra mask độ phân giải thấp từ tracker trước khi được tăng kích thước lên độ phân giải video.

score_threshold_detection (`float`, *optional*, mặc định là 0.5) : Ngưỡng xác suất cho đầu ra phát hiện - chỉ giữ lại các phát hiện có xác suất cao hơn ngưỡng này.

det_nms_thresh (`float`, *tuỳ chọn*, mặc định là 0.1) : Ngưỡng IoU cho NMS (Non-Maximum Suppression) trong phát hiện.

assoc_iou_thresh (`float`, *optional*, mặc định là 0.1) : Ngưỡng IoU cho việc khớp giữa phát hiện và track. Một phát hiện được coi là "khớp" với một tracklet nếu nó chồng lấp với tracklet vượt quá ngưỡng này. Thường là một ngưỡng lỏng lẻo như 0.1.

trk_assoc_iou_thresh (`float`, *optional*, mặc định là 0.5) : Ngưỡng IoU cho việc khớp giữa phát hiện và theo dõi, được sử dụng để xác định xem một masklet có "không khớp" với bất kỳ phát hiện nào hay không. Thường sử dụng ngưỡng chặt chẽ hơn như 0.5.

new_det_thresh (`float`, *tuỳ chọn*, mặc định là 0.7) : Ngưỡng xác suất để một phát hiện được thêm vào như một đối tượng mới.

recondition_on_trk_masks (`bool`, *tuỳ chọn*, mặc định là `True`) : Có sử dụng các mặt nạ được theo dõi (True) hay các mặt nạ phát hiện (False) cho việc tái điều kiện hay không. Sử dụng True khi các mặt nạ được theo dõi có chất lượng cao hơn và bộ phát hiện đóng vai trò là tín hiệu xác thực để tăng cường bộ nhớ và ngăn ngừa sự trôi dạt.

hotstart_delay (`int`, *tuỳ chọn*, mặc định là 15) : Số khung hình để đệm đầu ra trong quá trình khởi động nóng. Chúng tôi giữ lại các đầu ra trong `hotstart_delay` khung hình và loại bỏ các tracklet dựa trên các phép thử khởi động nóng.

hotstart_unmatch_thresh (`int`, *tuỳ chọn*, mặc định là 8) : Số khung hình không khớp cần thiết để loại bỏ một tracklet trong giai đoạn khởi động nóng.

hotstart_dup_thresh (`int`, *tuỳ chọn*, mặc định là 8) : Số lượng khung hình chồng chéo cần thiết để loại bỏ một tracklet trùng lặp trong giai đoạn hotstart.

suppress_unmatched_only_within_hotstart (`bool`, *tùy chọn*, mặc định là `True`) : Có nên chỉ áp dụng việc tắt các mask trong giai đoạn khởi động nóng hay không. Nếu là False, chúng ta có thể tắt các mask ngay cả khi chúng bắt đầu trước giai đoạn khởi động nóng.

init_trk_keep_alive (`int`, *tuỳ chọn*, mặc định là 30) : Bộ đếm keep-alive ban đầu cho các track mới.

max_trk_keep_alive (`int`, *tuỳ chọn*, mặc định là 30) : Giá trị bộ đếm keep-alive tối đa. Các đối tượng được theo dõi cùng với các phát hiện khớp sẽ có bộ đếm của chúng được tăng lên đến giá trị này.

min_trk_keep_alive (`int`, *optional*, mặc định là -1) : Giá trị bộ đếm keep-alive tối thiểu. Các track có phát hiện không khớp sẽ có bộ đếm của chúng bị giảm xuống giá trị này.

suppress_overlapping_based_on_recent_occlusion_threshold (`float`, *optional*, mặc định là 0.7) : Ngưỡng để loại bỏ các đối tượng chồng chéo dựa trên tình trạng bị che khuất gần nhất. Các mặt nạ chồng chéo có IoU cao hơn ngưỡng này sẽ bị loại bỏ dựa trên đối tượng nào bị che khuất gần nhất.

decrease_trk_keep_alive_for_empty_masklets (`bool`, *tùy chọn*, mặc định là `False`) : Có giảm bộ đếm keep-alive cho các masklet có diện tích bằng không trong dự đoán SAM2 hay không.

fill_hole_area (`int`, *optional*, mặc định là 16) : Diện tích tối thiểu (tính bằng pixel) để lấp đầy các lỗ hổng trong mask và loại bỏ các đốm nhỏ.

max_num_objects (`int`, *tuỳ chọn*, mặc định là 10000) : Số lượng đối tượng tối đa cần theo dõi. Giá trị mặc định 10000 thực chất là tắt giới hạn này.

recondition_every_nth_frame (`int`, *tuỳ chọn*, mặc định là 16) : Tần suất tái điều kiện hóa mặt nạ (tính theo khung hình). Đặt thành 0 để tắt tái điều kiện hóa.

high_conf_thresh (`float`, *optional*, mặc định là 0.8) : Ngưỡng độ tin cậy cao cho việc reconditioning. Chỉ các phát hiện có độ tin cậy cao hơn ngưỡng này mới có thể recondition tracklet.

high_iou_thresh (`float`, *optional*, mặc định là 0.8) : Ngưỡng IoU cao cho việc reconditioning. Chỉ các phát hiện có IoU cao hơn ngưỡng này mới có thể recondition tracklet.

Đây là lớp cấu hình để lưu trữ cấu hình của một Sam3VideoModel. Nó được sử dụng để khởi tạo một mô hình Sam3 Video theo các đối số được chỉ định, xác định kiến trúc của mô hình. Khởi tạo một cấu hình với các giá trị mặc định sẽ tạo ra một cấu hình tương tự như cấu hình của [facebook/sam3](https://huggingface.co/facebook/sam3)

Các đối tượng cấu hình kế thừa từ [PreTrainedConfig](/docs/transformers/v5.23.0/vi/main_classes/configuration#transformers.PreTrainedConfig) và có thể được sử dụng để kiểm soát đầu ra của mô hình. Đọc tài liệu từ [PreTrainedConfig](/docs/transformers/v5.23.0/vi/main_classes/configuration#transformers.PreTrainedConfig) để biết thêm thông tin.

Ví dụ:
```python
>>> from transformers import Sam3VideoConfig, Sam3VideoModel

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

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

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

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

## Sam3VideoProcessor[[transformers.Sam3VideoProcessor]]

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/processing_sam3_video.py#L39)

**Tham số:**

image_processor (`Sam3ImageProcessor`) : Bộ xử lý ảnh là một đầu vào bắt buộc.

video_processor (`video_processor_class`) : Bộ xử lý video là một đầu vào bắt buộc.

tokenizer (`CLIPTokenizer`) : Tokenizer là một đầu vào bắt buộc.

target_size (`int`, *optional*) : Kích thước đích (target_size, target_size) mà hình ảnh sẽ được thay đổi kích thước.

Tạo một Sam3VideoProcessor, đóng gói một bộ xử lý ảnh, một bộ xử lý video và một tokenizer thành một bộ xử lý duy nhất.

[Sam3VideoProcessor](/docs/transformers/v5.23.0/vi/model_doc/sam3_video#transformers.Sam3VideoProcessor) cung cấp đầy đủ các chức năng của [Sam3ImageProcessor](/docs/transformers/v5.23.0/vi/model_doc/sam3#transformers.Sam3ImageProcessor), `video_processor_class` và [CLIPTokenizer](/docs/transformers/v5.23.0/vi/model_doc/clip#transformers.CLIPTokenizer). Xem [~Sam3ImageProcessor](/docs/transformers/v5.23.0/vi/model_doc/sam3#transformers.Sam3ImageProcessor), `~video_processor_class` và [~CLIPTokenizer](/docs/transformers/v5.23.0/vi/model_doc/clip#transformers.CLIPTokenizer) để biết thêm thông tin.

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

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, original_sizes: typing.Union[list[list[float]], torch.Tensor, NoneType] = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, **kwargs)
```

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/processing_sam3_video.py#L55)

**Tham số:**

images (`ImageInput`, *tùy chọn*) : Ảnh cần xử lý.

segmentation_maps (`ImageInput`, *tùy chọn*) : Các bản đồ phân đoạn cần xử lý (tùy chọn, dành cho bộ xử lý ảnh).

original_sizes (`list[list[float]]`, `torch.Tensor`, *tùy chọn*) : Kích thước gốc của các hình ảnh. Chỉ được sử dụng khi images không được cung cấp.

return_tensors (`Union[str, ~utils.generic.TensorType]`, *tùy chọn*) : Nếu được đặt, sẽ trả về các tensor của một framework cụ thể. Các giá trị chấp nhận được là:  - `'pt'`: Trả về các đối tượng `torch.Tensor` của PyTorch. - `'np'`: Trả về các đối tượng `np.ndarray` của NumPy.

**Trả về:** Một [BatchEncoding](/docs/transformers/v5.23.0/vi/main_classes/tokenizer#transformers.BatchEncoding) với các trường sau

- `pixel_values` (`torch.Tensor`): Ảnh đã được xử lý.
- `original_sizes` (`list[list[float]]`): Kích thước gốc của các hình ảnh.
- `labels` (`torch.Tensor`, *tùy chọn*): Bản đồ phân đoạn đã được xử lý (nếu được cung cấp).

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/processing_sam3_video.py#L247)

**Tham số:**

inference_session (`Sam3VideoInferenceSession`) : Đối tượng phiên suy luận.

model_outputs (`Sam3VideoSegmentationOutput`) : Đầu ra thô của mô hình từ `Sam3VideoModel.forward()`.

original_sizes (`list[list[float]]` hoặc `torch.Tensor`, *tuỳ chọn*) : Kích thước khung hình gốc [chiều cao, chiều rộng] tuỳ chọn. Bắt buộc cho suy luận dạng streaming khi video_height/video_width không được đặt trong phiên.

**Trả về:** `dict`

Một từ điển chứa các khóa sau:
- **object_ids** (`torch.Tensor` có hình dạng `(num_objects,)`): ID của từng đối tượng được phát hiện.
- **scores** (`torch.Tensor` có hình dạng `(num_objects,)`): Điểm phát hiện cho từng đối tượng.
- **boxes** (`torch.Tensor` có shape `(num_objects, 4)`): Các bounding box ở định dạng XYXY (top_left_x, top_left_y, bottom_right_x, bottom_right_y).
- **masks** (`torch.Tensor` có shape `(num_objects, height, width)`): Các mask phân đoạn nhị phân cho từng đối tượng ở độ phân giải video gốc.
- **prompt_to_obj_ids** (`dict[str, list[int]]`): Ánh xạ từ văn bản prompt đến danh sách các ID đối tượng được phát hiện bởi prompt đó.

Xử lý hậu kỳ đầu ra của mô hình để lấy các mặt nạ, hộp và điểm số cuối cùng.

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

```python
init_video_session(video: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None, inference_device: typing.Union[str, ForwardRef('torch.device')] = 'cpu', inference_state_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = None, processing_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = None, video_storage_device: typing.Union[str, ForwardRef('torch.device'), NoneType] = None, max_vision_features_cache_size: int = 1, dtype: dtype = torch.float32)
```

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/processing_sam3_video.py#L133)

**Tham số:**

video (`VideoInput`, *tùy chọn*) : Video cần xử lý. Không cần cung cấp khi đang phát trực tiếp.

inference_device (`str` hoặc `torch.device`, *tuỳ chọn*, mặc định là "cpu") : Thiết bị được sử dụng cho suy luận.

inference_state_device (`str` hoặc `torch.device`, *tùy chọn*) : Thiết bị để lưu trữ trạng thái suy luận.

processing_device (`str` hoặc `torch.device`, *tùy chọn*) : Thiết bị được sử dụng để xử lý video.

video_storage_device (`str` hoặc `torch.device`, *tùy chọn*) : Thiết bị để lưu các khung video đã xử lý.

max_vision_features_cache_size (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng tối đa các đặc trưng thị giác để lưu vào bộ nhớ đệm.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `torch.float32`) : torch dtype được sử dụng cho toàn bộ phiên.

Khởi tạo phiên video cho suy luận. Nếu một video được cung cấp (suy luận bất đồng bộ), video sẽ được xử lý và lưu trữ trên `video_storage_device`.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/processing_sam3_video.py#L101)

**Tham số:**

inference_session (`Sam3VideoInferenceSession`) : Phiên suy luận.

text (`str` hoặc `list[str]`) : Các prompt văn bản cần thêm.

**Trả về:** `Sam3VideoInferenceSession`

Phiên suy luận với các prompt văn bản đã thêm.

Thêm prompt văn bản vào phiên suy luận.

## Sam3VideoInferenceSession[[transformers.Sam3VideoInferenceSession]]

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

```python
transformers.Sam3VideoInferenceSession(video: typing.Optional[torch.Tensor] = None, video_height: int | None = None, video_width: int | None = None, inference_device: typing.Union[torch.device, str] = 'cpu', inference_state_device: typing.Union[torch.device, str] = 'cpu', video_storage_device: typing.Union[torch.device, str] = 'cpu', dtype: typing.Union[torch.dtype, str] = 'float32', max_vision_features_cache_size: int = 1)
```

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L119)

**Tham số:**

video (`torch.Tensor`, *tùy chọn*) : Video cần xử lý. Không cần cung cấp khi đang phát trực tiếp.

video_height (`int`, *tuỳ chọn*) : Chiều cao của video.

video_width (`int`, *tuỳ chọn*) : Độ rộng của video.

inference_device (`torch.device`, *tùy chọn*, mặc định là `"cpu"`) : Thiết bị được sử dụng cho suy luận.

inference_state_device (`torch.device`, *tùy chọn*, mặc định là `"cpu"`) : Thiết bị để lưu trữ trạng thái suy luận.

video_storage_device (`torch.device`, *tùy chọn*, mặc định là `"cpu"`) : Thiết bị để lưu trữ video.

dtype (`torch.dtype`, *tùy chọn*, mặc định là `"float32"`) : Kiểu dữ liệu (dtype) để sử dụng cho video.

max_vision_features_cache_size (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng tối đa các đặc trưng thị giác để lưu vào bộ nhớ đệm.

Quản lý các tham số, trạng thái và bộ nhớ đệm của phiên suy luận video.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L255)

Thêm đầu vào mask với việc đặt thiết bị tự động.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L384)

Thêm khung mới với việc đặt thiết bị tự động.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L215)

Thêm một prompt văn bản vào phiên và trả về ID duy nhất của nó. Nếu prompt đã tồn tại, trả về ID hiện có.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L400)

Lấy khung từ video.

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

```python
get_obj_num()
```

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L251)

Lấy tổng số lượng id đối tượng duy nhất đã nhận được cho đến nay trong phiên này.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L357)

**Tham số:**

obj_idx (int) : Chỉ số của đối tượng.

frame_idx (int) : Chỉ số của khung hình.

output_key (str) : Khóa của đầu ra.

is_conditioning_frame (bool) : Xác định xem đầu ra có phải cho một khung điều kiện hay không.

Lấy kết quả với quản lý thiết bị thông minh.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L229)

Ánh xạ ID đối tượng tới chỉ số, tạo mục mới nếu cần.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L247)

Ánh xạ chỉ mục đối tượng phía mô hình sang id đối tượng phía client.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L261)

Xóa các đầu vào mask.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L265)

**Tham số:**

obj_id (`int`) : ID của đối tượng cần xóa.

strict (`bool`, *tùy chọn*, mặc định là `False`) : Có nên gây ra lỗi nếu đối tượng không tồn tại hay không.

Xóa một đối tượng khỏi phiên suy luận. Thao tác này sẽ xóa đối tượng khỏi tất cả các khung hình trong video.

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

```python
reset_inference_session()
```

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L416)

Đặt lại dữ liệu theo dõi và bộ nhớ đệm.

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

```python
reset_state()
```

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L428)

Đặt lại trạng thái phiên suy luận.

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

```python
reset_tracking_data()
```

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L404)

Đặt lại dữ liệu theo dõi nhưng giữ lại bộ nhớ đệm.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L320)

**Tham số:**

obj_idx (int) : Chỉ số của đối tượng.

frame_idx (int) : Chỉ số của khung hình.

output_key (Optional[str]) : Khóa của đầu ra. Nếu là None, đầu ra sẽ được lưu dưới dạng từ điển.

output_value (Optional[Union[torch.Tensor, dict]]) : Giá trị của đầu ra.

is_conditioning_frame (bool) : Xác định xem đầu ra có phải cho một khung điều kiện hay không.

Lưu trữ đầu ra với quản lý thiết bị thông minh. Nếu output_key là None, đầu ra sẽ được lưu trữ dưới dạng từ điển.

## Sam3VideoSegmentationOutput[[transformers.Sam3VideoSegmentationOutput]]

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L462)

**Tham số:**

object_ids (`list[int]`, *tùy chọn*) : Danh sách các ID đối tượng đang được theo dõi trong khung hình hiện tại.

obj_id_to_mask (`dict[int, torch.Tensor]`, *tùy chọn*) : Từ điển ánh xạ ID đối tượng đến các mặt nạ độ phân giải thấp dự đoán của chúng. Mỗi mặt nạ có hình dạng `(1, H_low, W_low)`.

obj_id_to_score (`dict[int, float]`, *tùy chọn*) : Từ điển ánh xạ ID đối tượng đến điểm phát hiện của chúng.

obj_id_to_tracker_score (`dict[int, float]`, *tùy chọn*) : Từ điển ánh xạ ID đối tượng đến điểm theo dõi của chúng cho khung hình hiện tại.

removed_obj_ids (`set[int]`, *tùy chọn*) : Tập hợp các ID đối tượng đã bị xóa (ví dụ: thông qua các phép suy luận hotstart).

suppressed_obj_ids (`set[int]`, *tùy chọn*) : Tập hợp các ID đối tượng đã bị tắt tiếng trong khung hiện tại.

frame_idx (`int`, *tuỳ chọn*) : Chỉ số khung của video.

Lớp cơ sở cho đầu ra của mô hình Sam3Video.

## Sam3VideoModel[[transformers.Sam3VideoModel]]

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L507)

**Tham số:**

config ([Sam3VideoConfig](/docs/transformers/v5.23.0/vi/model_doc/sam3_video#transformers.Sam3VideoConfig)) : Lớp cấu hình mô hình chứa tất cả các tham số của mô hình. Khởi tạo bằng tệp cấu hình sẽ không tải trọng số liên quan đến mô hình, chỉ tải cấu hình. Xem phương thức [from_pretrained()](/docs/transformers/v5.23.0/vi/main_classes/model#transformers.PreTrainedModel.from_pretrained) để tải trọng số mô hình.

Mô hình Sam3 Video cơ bản, xuất ra các hidden-states thô mà không có bất kỳ head cụ thể nào ở phía trên.

Mô hình này kế thừa từ [PreTrainedModel](/docs/transformers/v5.23.0/vi/main_classes/model#transformers.PreTrainedModel). Xem tài liệu của lớp cha để biết các phương thức chung mà thư viện triển khai cho tất cả các mô hình của nó (chẳng hạn như tải xuống hoặc lưu trữ, thay đổi kích thước các nhúng đầu vào, cắt tỉa các đầu ra, v.v.)

Mô hình này cũng là một lớp con của [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) trong PyTorch. Hãy sử dụng nó như một Module PyTorch thông thường và tham khảo tài liệu PyTorch cho mọi vấn đề liên quan đến cách sử dụng và hành vi chung.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L1693)

**Tham số:**

inference_session (`~models.sam3_video.modeling_sam3_video.Sam3VideoInferenceSession`) : Đối tượng phiên suy luận video.

frame_idx (`int`, *optional*) : Chỉ số của khung hình mà bạn muốn chạy suy luận. Không cần cung cấp khi suy luận trên một khung hình mới được phát trực tiếp.

frame (`torch.Tensor`, *tùy chọn*) : Khung cần xử lý. Cung cấp khi đang phát trực tiếp.

reverse (`bool`, *tùy chọn*, mặc định là `False`) : Có lan truyền theo chiều ngược lại hay không.

Truyền các đối tượng qua một khung video được phát trực tiếp.

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

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

[Nguồn](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/sam3_video/modeling_sam3_video.py#L1784)

**Tham số:**

inference_session (`~models.sam3_video.modeling_sam3_video.Sam3VideoInferenceSession`) : Đối tượng phiên suy luận video.

start_frame_idx (`int`, *tuỳ chọn*, mặc định là `0`) : Chỉ số khung bắt đầu cho quá trình lan truyền.

max_frame_num_to_track (`int`, *tùy chọn*) : Số khung hình tối đa cần theo dõi. Nếu không được cung cấp, tất cả các khung hình trong video sẽ được theo dõi.

reverse (`bool`, *tùy chọn*, mặc định là `False`) : Có lan truyền theo chiều ngược lại hay không.

show_progress_bar (`bool`, *tùy chọn*, mặc định là `False`) : Có hiển thị thanh tiến trình trong quá trình lan truyền hay không.

**Trả về:** [Sam3VideoSegmentationOutput](/docs/transformers/v5.23.0/vi/model_doc/sam3_video#transformers.Sam3VideoSegmentationOutput) hoặc `tuple(torch.Tensor)`

Một [Sam3VideoSegmentationOutput](/docs/transformers/v5.23.0/vi/model_doc/sam3_video#transformers.Sam3VideoSegmentationOutput) hoặc một tuple của `torch.Tensor` (nếu `return_dict=False` được truyền hoặc khi `config.return_dict=False`) bao gồm các phần tử khác nhau tùy thuộc vào cấu hình ([Sam3VideoConfig](/docs/transformers/v5.23.0/vi/model_doc/sam3_video#transformers.Sam3VideoConfig)) và đầu vào.

Truyền các prompt để lấy kết quả grounding cho toàn bộ video. Được sử dụng khi khởi tạo phiên suy luận với một video hoàn chỉnh. Trả về Sam3VideoSegmentationOutput cho mỗi khung hình.

- **object_ids** (`list[int]`, *tùy chọn*) -- Danh sách các ID đối tượng đang được theo dõi trong khung hình hiện tại.
- **obj_id_to_mask** (`dict[int, torch.Tensor]`, *tùy chọn*) -- Từ điển ánh xạ ID đối tượng đến các mặt nạ độ phân giải thấp dự đoán của chúng. Mỗi mặt nạ có hình dạng `(1, H_low, W_low)`.
- **obj_id_to_score** (`dict[int, float]`, *tùy chọn*) -- Từ điển ánh xạ ID đối tượng đến điểm phát hiện tương ứng.
- **obj_id_to_tracker_score** (`dict[int, float]`, *tùy chọn*) -- Từ điển ánh xạ ID đối tượng đến điểm theo dõi của chúng cho khung hình hiện tại.
- **removed_obj_ids** (`set[int]`, *tùy chọn*) -- Tập hợp các ID đối tượng đã bị xóa (ví dụ: thông qua các phép suy luận khởi động nóng).
- **suppressed_obj_ids** (`set[int]`, *tùy chọn*) -- Tập hợp các ID đối tượng đã bị tắt trong khung hiện tại.
- **frame_idx** (`int`, *tùy chọn*) -- Chỉ số khung của video.

