# EdgeTAMVideo

## Tổng quan

Mô hình EdgeTAM được đề xuất trong [EdgeTAM: On-Device Track Anything Model](https://huggingface.co/papers/2501.07256) Chong Zhou, Chenchen Zhu, Yunyang Xiong, Saksham Suri, Fanyi Xiao, Lemeng Wu, Raghuraman Krishnamoorthi, Bo Dai, Chen Change Loy, Vikas Chandra, Bilge Soran.

EdgeTAM là một biến thể hiệu quả của SAM 2, giới thiệu kiến trúc 2D Spatial Perceiver để tối ưu hóa các cơ chế chú ý bộ nhớ cho phân đoạn video thời gian thực trên thiết bị di động.

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

*Nằm trên nền tảng của Segment Anything Model (SAM), SAM 2 mở rộng thêm khả năng từ đầu vào hình ảnh sang đầu vào video thông qua cơ chế ngân hàng bộ nhớ (memory bank) và đạt được hiệu suất vượt trội so với các phương pháp trước đó, biến nó thành một mô hình nền tảng cho tác vụ phân đoạn video. Trong bài báo này, chúng tôi hướng đến việc làm cho SAM 2 hiệu quả hơn nhiều để nó thậm chí có thể chạy trên các thiết bị di động trong khi vẫn duy trì hiệu suất tương đương. Mặc dù đã có một số công việc tối ưu hóa SAM để cải thiện hiệu quả, chúng tôi nhận thấy chúng không đủ cho SAM 2 vì tất cả đều tập trung vào việc nén bộ mã hóa hình ảnh, trong khi benchmark của chúng tôi cho thấy các khối chú ý bộ nhớ (memory attention blocks) mới được giới thiệu cũng là nút thắt cổ chai về độ trễ. Với quan sát này, chúng tôi đề xuất EdgeTAM, tận dụng một 2D Spatial Perceiver mới để giảm chi phí tính toán. Cụ thể, 2D Spatial Perceiver được đề xuất mã hóa các bộ nhớ cấp khung (frame-level memories) được lưu trữ dày đặc bằng một Transformer nhẹ chứa một tập hợp cố định các truy vấn (queries) có thể học được. Do phân đoạn video là một tác vụ dự đoán dày đặc (dense prediction), chúng tôi nhận thấy việc bảo toàn cấu trúc không gian của các bộ nhớ là thiết yếu, do đó các truy vấn được chia thành các nhóm cấp toàn cục (global-level) và cấp mảnh (patch-level). Chúng tôi cũng đề xuất một quy trình chưng cất (distillation pipeline) giúp cải thiện thêm hiệu suất mà không gây ra chi phí suy luận (inference overhead). Kết quả, EdgeTAM đạt 87,7, 70,0, 72,3 và 71,7 J&F trên DAVIS 2017, MOSE, SA-V val và SA-V test, trong khi chạy ở 16 FPS trên iPhone 15 Pro Max.*

Mô hình này được đóng góp bởi [yonigozlan](https://huggingface.co/yonigozlan). Mã gốc có thể được tìm thấy [tại đây](https://github.com/facebookresearch/EdgeTAM).

## Ví dụ sử dụng

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

Điểm mạnh chính của EdgeTAM Video là khả năng theo dõi các đối tượng xuyên suốt các khung hình video một cách hiệu quả trên các thiết bị di động. Dưới đây là cách sử dụng nó cho phân đoạn video:

#### Theo dõi video cơ bản

```python
from transformers import EdgeTamVideoModel, Sam2VideoProcessor
import torch

model = EdgeTamVideoModel.from_pretrained("yonigozlan/edgetam-video-1", device_map="auto")
processor = Sam2VideoProcessor.from_pretrained("yonigozlan/edgetam-video-1")

# Load video frames (example assumes you have a list of PIL Images)
# video_frames = [Image.open(f"frame_{i:05d}.jpg") for i in range(num_frames)]

# For this example, we'll use the video loading utility
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,
)

# Add click on first frame to select object
ann_frame_idx = 0
ann_obj_id = 1
points = [[[[210, 350]]]]
labels = [[[1]]]

processor.add_inputs_to_inference_session(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
    obj_ids=ann_obj_id,
    input_points=points,
    input_labels=labels,
)

# Segment the object on the first frame
outputs = model(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
)
video_res_masks = processor.post_process_masks(
    [outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
)[0]
print(f"Segmentation shape: {video_res_masks.shape}")
Segmentation shape: torch.Size([1, 1, 540, 960])

# Propagate through the entire video
video_segments = {}
for sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_video_output.frame_idx] = video_res_masks

print(f"Tracked object through {len(video_segments)} frames")
Tracked object through 200 frames
```

#### Theo dõi video đa đối tượng

Theo dõi nhiều đối tượng đồng thời qua các khung hình video:

```python
# Reset for new tracking session
inference_session.reset_inference_session()

# Add multiple objects on the first frame
ann_frame_idx = 0
obj_ids = [2, 3]
input_points = [[[[200, 300]], [[400, 150]]]]  # Points for two objects (batched)
input_labels = [[[1], [1]]]

processor.add_inputs_to_inference_session(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
    obj_ids=obj_ids,
    input_points=input_points,
    input_labels=input_labels,
)

# Get masks for both objects on first frame
outputs = model(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
)

# Propagate both objects through video
video_segments = {}
for sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_video_output.frame_idx] = {
        obj_id: video_res_masks[i]
        for i, obj_id in enumerate(inference_session.obj_ids)
    }

print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")
Tracked 2 objects through 200 frames
```

#### Tinh chỉnh phân đoạn video

Bạn có thể thêm các lần nhấp bổ sung vào bất kỳ khung hình nào để tinh chỉnh việc theo dõi:

```python
# Add refinement click on a later frame
refine_frame_idx = 50
ann_obj_id = 2  # Refining first object
points = [[[[220, 280]]]]  # Additional point
labels = [[[1]]]  # Positive click

processor.add_inputs_to_inference_session(
    inference_session=inference_session,
    frame_idx=refine_frame_idx,
    obj_ids=ann_obj_id,
    input_points=points,
    input_labels=labels,
)

# Re-propagate with the additional information
video_segments = {}
for sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_video_output.frame_idx] = video_res_masks
```

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

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

```python
# Initialize session for streaming
inference_session = processor.init_video_session(
    inference_device=device,
)

# Process frames one by one
for frame_idx, frame in enumerate(video_frames[:10]):  # Process first 10 frames
    inputs = processor(images=frame, device=device, return_tensors="pt").to(model.device)
...
    if frame_idx == 0:
        # Add point input on first frame
        processor.add_inputs_to_inference_session(
            inference_session=inference_session,
            frame_idx=0,
            obj_ids=1,
            input_points=[[[[210, 350], [250, 220]]]],
            input_labels=[[[1, 1]]],
            original_size=inputs.original_sizes[0], # need to be provided when using streaming video inference
        )
...
    # Process current frame
    sam2_video_output = model(inference_session=inference_session, frame=inputs.pixel_values[0])
...
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=inputs.original_sizes, binarize=False
    )[0]
    print(f"Frame {frame_idx}: mask shape {video_res_masks.shape}")

Frame 0: mask shape torch.Size([1, 1, 540, 960])
...
```

#### Xử lý hàng loạt video cho nhiều đối tượng

Theo dõi nhiều đối tượng đồng thời trong video bằng cách thêm tất cả chúng cùng lúc:

```python
# Initialize video session
inference_session = processor.init_video_session(
    video=video_frames,
    inference_device=device,
)

# Add multiple objects on the first frame using batch processing
ann_frame_idx = 0
obj_ids = [2, 3]  # Track two different objects
input_points = [
    [[[200, 300], [230, 250], [275, 175]], [[400, 150]]]
]  # Object 2: 3 points (2 positive, 1 negative); Object 3: 1 point
input_labels = [
    [[1, 1, 0], [1]]
]  # Object 2: positive, positive, negative; Object 3: positive

processor.add_inputs_to_inference_session(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
    obj_ids=obj_ids,
    input_points=input_points,
    input_labels=input_labels,
)

# Get masks for all objects on the first frame
outputs = model(
    inference_session=inference_session,
    frame_idx=ann_frame_idx,
)
video_res_masks = processor.post_process_masks(
    [outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
)[0]
print(f"Generated masks for {video_res_masks.shape[0]} objects")
Generated masks for 2 objects

# Propagate all objects through the video
video_segments = {}
for sam2_video_output in model.propagate_in_video_iterator(inference_session):
    video_res_masks = processor.post_process_masks(
        [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
    )[0]
    video_segments[sam2_video_output.frame_idx] = {
        obj_id: video_res_masks[i]
        for i, obj_id in enumerate(inference_session.obj_ids)
    }

print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")
Tracked 2 objects through 200 frames
```

## EdgeTamVideoMaskDecoderConfig[[transformers.EdgeTamVideoMaskDecoderConfig]]

#### transformers.EdgeTamVideoMaskDecoderConfig[[transformers.EdgeTamVideoMaskDecoderConfig]]

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

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/configuration_edgetam_video.py#L57)

**Tham số:**

hidden_size (`int`, *tuỳ chọn*, mặc định là `256`) : Kích thước của các biểu diễn ẩn.

hidden_act (`str`, *tùy chọn*, mặc định là `gelu`) : Hàm kích hoạt phi tuyến (hàm hoặc chuỗi) trong bộ giải mã. Ví dụ, `"gelu"`, `"relu"`, `"silu"`, v.v.

mlp_dim (`int`, *tuỳ chọn*, mặc định là 2048) : Kích thước của MLP trong transformer hai chiều.

num_hidden_layers (`int`, *tuỳ chọn*, mặc định là `2`) : Số lượng lớp ẩn trong bộ giải mã Transformer.

num_attention_heads (`int`, *tuỳ chọn*, mặc định là `8`) : Số lượng đầu chú ý cho mỗi lớp chú ý trong bộ giải mã Transformer.

attention_downsample_rate (`int`, *tuỳ chọn*, mặc định là 2) : Tốc độ hạ mẫu cho các lớp attention.

num_multimask_outputs (`int`, *tuỳ chọn*, mặc định là 3) : Số lượng đầu ra multimask.

iou_head_depth (`int`, *tuỳ chọn*, mặc định là 3) : Độ sâu của đầu IoU.

iou_head_hidden_dim (`int`, *optional*, mặc định là 256) : Kích thước chiều ẩn của đầu IoU.

dynamic_multimask_via_stability (`bool`, *tùy chọn*, mặc định là `True`) : Có sử dụng dynamic multimask thông qua stability hay không.

dynamic_multimask_stability_delta (`float`, *tuỳ chọn*, mặc định là 0.05) : Độ lệch ổn định cho dynamic multimask.

dynamic_multimask_stability_thresh (`float`, *optional*, mặc định là 0.98) : Ngưỡng ổn định cho dynamic multimask.

Đây là lớp cấu hình để lưu trữ cấu hình của một EdgeTamVideoModel. Nó được sử dụng để khởi tạo một mô hình Edgetam 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 [yonigozlan/EdgeTAM-hf](https://huggingface.co/yonigozlan/EdgeTAM-hf)

Các đối tượng cấu hình kế thừa từ [PreTrainedConfig](/docs/transformers/main/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/main/vi/main_classes/configuration#transformers.PreTrainedConfig) để biết thêm thông tin.

## EdgeTamVideoPromptEncoderConfig[[transformers.EdgeTamVideoPromptEncoderConfig]]

#### transformers.EdgeTamVideoPromptEncoderConfig[[transformers.EdgeTamVideoPromptEncoderConfig]]

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

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/configuration_edgetam_video.py#L32)

**Tham số:**

hidden_size (`int`, *tuỳ chọn*, mặc định là `256`) : Kích thước của các biểu diễn ẩn.

image_size (`Union[int, list[int], tuple[int, int]]`, *tùy chọn*, mặc định là `1024`) : Kích thước (độ phân giải) của mỗi hình ảnh.

patch_size (`Union[int, list[int], tuple[int, int]]`, *tùy chọn*, mặc định là `16`) : Kích thước (độ phân giải) của mỗi patch.

mask_input_channels (`int`, *tuỳ chọn*, mặc định là 16) : Số lượng kênh được đưa vào module `MaskDecoder`.

num_point_embeddings (`int`, *tuỳ chọn*, mặc định là 4) : Số lượng point embeddings sẽ được sử dụng.

hidden_act (`str`, *tùy chọn*, mặc định là `gelu`) : Hàm kích hoạt phi tuyến (hàm hoặc chuỗi) trong bộ giải mã. Ví dụ, `"gelu"`, `"relu"`, `"silu"`, v.v.

layer_norm_eps (`float`, *tuỳ chọn*, mặc định là `1e-06`) : Epsilon được sử dụng bởi các lớp chuẩn hóa lớp (layer normalization).

scale (`float`, *tuỳ chọn*, mặc định là 1) : Hệ số tỷ lệ cho bộ mã hóa prompt.

Đây là lớp cấu hình để lưu trữ cấu hình của một EdgeTamVideoModel. Nó được sử dụng để khởi tạo một mô hình Edgetam 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 [yonigozlan/EdgeTAM-hf](https://huggingface.co/yonigozlan/EdgeTAM-hf)

Các đối tượng cấu hình kế thừa từ [PreTrainedConfig](/docs/transformers/main/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/main/vi/main_classes/configuration#transformers.PreTrainedConfig) để biết thêm thông tin.

## EdgeTamVideoConfig[[transformers.EdgeTamVideoConfig]]

#### transformers.EdgeTamVideoConfig[[transformers.EdgeTamVideoConfig]]

```python
transformers.EdgeTamVideoConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, prompt_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, mask_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, initializer_range: float = 0.02, num_maskmem: int = 7, image_size: int | list[int] | tuple[int, int] = 1024, sigmoid_scale_for_mem_enc: float = 20.0, sigmoid_bias_for_mem_enc: float = -10.0, enable_occlusion_spatial_embedding: bool = True, multimask_output_in_sam: bool = True, multimask_min_pt_num: int = 0, multimask_max_pt_num: int = 1, multimask_output_for_tracking: bool = True, max_object_pointers_in_encoder: int = 16, max_cond_frame_num: int = -1, enable_temporal_pos_encoding_for_object_pointers: bool = True, memory_attention_hidden_size: int = 256, memory_attention_num_layers: int = 2, memory_attention_num_attention_heads: int = 1, memory_attention_downsample_rate: int = 1, memory_attention_mlp_hidden_size: int = 2048, memory_attention_mlp_hidden_act: str = 'relu', memory_attention_dropout: float | int = 0.1, memory_attention_rope_feat_sizes: list | None = None, memory_attention_rope_k_sizes: list | None = None, memory_attention_rope_dropout: float | int = 0.1, rope_parameters: dict | None = None, perceiver_resampler_num_latents: int = 256, perceiver_resampler_num_latents_2d: int = 256, perceiver_resampler_hidden_size: int = 64, perceiver_resampler_mlp_intermediate_size: int = 256, perceiver_resampler_num_attention_heads: int = 1, perceiver_resampler_attention_head_dim: int = 64, perceiver_resampler_num_layers: int = 2, perceiver_resampler_hidden_dropout: float | int = 0.0, perceiver_resampler_attention_dropout: float | int = 0.0, memory_encoder_hidden_size: int = 256, memory_encoder_output_channels: int = 64, mask_downsampler_embed_dim: int = 256, memory_fuser_intermediate_dim: int = 1024, mask_downsampler_kernel_size: int = 3, mask_downsampler_stride: int = 2, mask_downsampler_padding: int = 1, mask_downsampler_total_stride: int = 16, mask_downsampler_hidden_act: str = 'gelu', memory_fuser_num_layers: int = 2, memory_fuser_embed_dim: int = 256, memory_fuser_kernel_size: int = 7, memory_fuser_padding: int = 3, memory_fuser_layer_scale_init_value: float = 1e-06, memory_fuser_hidden_act: str = 'gelu')
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/configuration_edgetam_video.py#L96)

**Tham số:**

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *tùy chọn*) : Đối tượng config hoặc từ điển của vision backbone.

prompt_encoder_config (Union[`dict`, `EdgeTamVideoPromptEncoderConfig`], *optional*) : Từ điển các tùy chọn cấu hình được sử dụng để khởi tạo [EdgeTamVideoPromptEncoderConfig](/docs/transformers/main/vi/model_doc/edgetam_video#transformers.EdgeTamVideoPromptEncoderConfig).

mask_decoder_config (Union[`dict`, `EdgeTamVideoMaskDecoderConfig`], *optional*) : Từ điển các tùy chọn cấu hình được sử dụng để khởi tạo [EdgeTamMaskDecoderConfig](/docs/transformers/main/vi/model_doc/edgetam#transformers.EdgeTamMaskDecoderConfig).

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

num_maskmem (`int`, *tuỳ chọn*, mặc định là 7) : Số lượng khe bộ nhớ cho bộ nhớ mặt nạ.

image_size (`Union[int, list[int], tuple[int, int]]`, *tùy chọn*, mặc định là `1024`) : Kích thước (độ phân giải) của mỗi hình ảnh.

sigmoid_scale_for_mem_enc (`float`, *tuỳ chọn*, mặc định là 20.0) : Hệ số tỷ lệ cho hàm sigmoid trong bộ mã hóa bộ nhớ.

sigmoid_bias_for_mem_enc (`float`, *tuỳ chọn*, mặc định là -10.0) : Bias cho hàm sigmoid trong bộ mã hóa bộ nhớ.

enable_occlusion_spatial_embedding (`bool`, *tùy chọn*, mặc định là `True`) : Có bật nhúng không gian cho các vùng bị che khuất hay không.

multimask_output_in_sam (`bool`, *tuỳ chọn*, mặc định là `True`) : Có xuất ra nhiều mask từ đầu SAM hay không.

multimask_min_pt_num (`int`, *optional*, mặc định là 0) : Số điểm tối thiểu để kích hoạt đầu ra multimask.

multimask_max_pt_num (`int`, *tuỳ chọn*, mặc định là 1) : Số điểm tối đa để kích hoạt đầu ra multimask.

multimask_output_for_tracking (`bool`, *tuỳ chọn*, mặc định là `True`) : Có sử dụng đầu ra đa mặt nạ cho việc theo dõi hay không.

max_object_pointers_in_encoder (`int`, *tuỳ chọn*, mặc định là 16) : Số lượng con trỏ đối tượng tối đa trong bộ mã hóa.

max_cond_frame_num (`int`, *tuỳ chọn*, mặc định là -1) : Số lượng tối đa các khung điều kiện được sử dụng trong bộ nhớ chú ý. Đặt thành -1 để sử dụng tất cả các khung điều kiện.

enable_temporal_pos_encoding_for_object_pointers (`bool`, *tùy chọn*, mặc định là `True`) : Có bật mã hóa vị trí theo thời gian cho các con trỏ đối tượng hay không.

memory_attention_hidden_size (`int`, *tuỳ chọn*, mặc định là 256) : Độ chiều của các trạng thái ẩn của chú ý bộ nhớ.

memory_attention_num_layers (`int`, *tuỳ chọn*, mặc định là 2) : Số lượng lớp trong module chú ý bộ nhớ.

memory_attention_num_attention_heads (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng đầu chú ý cho mỗi lớp chú ý trong chú ý bộ nhớ.

memory_attention_downsample_rate (`int`, *tuỳ chọn*, mặc định là 1) : Tốc độ hạ mẫu cho các lớp chú ý.

memory_attention_mlp_hidden_size (`int`, *tuỳ chọn*, mặc định là 2048) : Kích thước của mạng feedforward trong module chú ý bộ nhớ.

memory_attention_mlp_hidden_act (`str`, *tùy chọn*, mặc định là `"relu"`) : Hàm kích hoạt phi tuyến tính trong mạng feedforward của module chú ý bộ nhớ.

memory_attention_dropout (`float`, *tuỳ chọn*, mặc định là 0.1) : Tỷ lệ dropout cho module chú ý bộ nhớ.

memory_attention_rope_feat_sizes (`Tuple[int, int]`, *tùy chọn*, mặc định là `[64, 64]`) : Kích thước đặc trưng cho mã hóa vị trí Rope.

memory_attention_rope_k_sizes (`List[int]`, *tùy chọn*, mặc định là `[16, 16]`) : Kích thước các tính năng khóa cho mã hóa vị trí RoPE trong bộ nhớ chú ý.

memory_attention_rope_dropout (`float`, *optional*, mặc định là 0.1) : Tỷ lệ dropout cho mã hóa vị trí Rope.

rope_parameters (`dict`, *tùy chọn*) : Từ điển chứa các tham số cấu hình cho các embedding RoPE. Từ điển phải chứa một giá trị cho `rope_theta` và tùy chọn các tham số được sử dụng để mở rộng trong trường hợp bạn muốn sử dụng RoPE với `max_position_embeddings` dài hơn.

perceiver_resampler_num_latents (`int`, *tuỳ chọn*, mặc định là 256) : Số lượng token tiềm ẩn 1D trong perceiver resampler.

perceiver_resampler_num_latents_2d (`int`, *tuỳ chọn*, mặc định là 256) : Số lượng token tiềm ẩn 2D trong perceiver resampler.

perceiver_resampler_hidden_size (`int`, *tuỳ chọn*, mặc định là 64) : Kích thước ẩn của perceiver resampler.

perceiver_resampler_mlp_intermediate_size (`int`, *tuỳ chọn*, mặc định là 256) : Kích thước trung gian của mạng feedforward trong perceiver resampler.

perceiver_resampler_num_attention_heads (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng đầu chú ý trong perceiver resampler.

perceiver_resampler_attention_head_dim (`int`, *tuỳ chọn*, mặc định là 64) : Kích thước của mỗi đầu chú ý (attention head) trong perceiver resampler.

perceiver_resampler_num_layers (`int`, *tuỳ chọn*, mặc định là 2) : Số lượng lớp trong perceiver resampler.

perceiver_resampler_hidden_dropout (`float`, *optional*, mặc định là 0.0) : Tỷ lệ dropout cho các lớp ẩn trong perceiver resampler.

perceiver_resampler_attention_dropout (`float`, *optional*, mặc định là 0.0) : Tỷ lệ dropout cho các lớp attention trong perceiver resampler.

memory_encoder_hidden_size (`int`, *optional*, mặc định là 256) : Độ chiều của các trạng thái ẩn của bộ mã hóa bộ nhớ.

memory_encoder_output_channels (`int`, *tuỳ chọn*, mặc định là 64) : Số lượng kênh đầu ra cho bộ mã hóa bộ nhớ.

mask_downsampler_embed_dim (`int`, *optional*, mặc định là 256) : Kích thước của embedding bộ giảm mẫu mask.

memory_fuser_intermediate_dim (`int`, *optional*, mặc định là 1024) : Kích thước chiều trung gian của mạng feedforward của bộ hợp nhất bộ nhớ.

mask_downsampler_kernel_size (`int`, *tuỳ chọn*, mặc định là 3) : Kích thước kernel cho bộ giảm mẫu mask.

mask_downsampler_stride (`int`, *tuỳ chọn*, mặc định là 2) : Bước nhảy (stride) cho bộ giảm mẫu (downsampler) của mặt nạ (mask).

mask_downsampler_padding (`int`, *tuỳ chọn*, mặc định là 1) : Lề đệm cho bộ giảm mẫu mặt nạ.

mask_downsampler_total_stride (`int`, *optional*, mặc định là 16) : Tổng bước nhảy (stride) cho bộ giảm kích thước (downsampler) của mặt nạ (mask).

mask_downsampler_hidden_act (`str`, *tùy chọn*, mặc định là `"gelu"`) : Hàm kích hoạt phi tuyến tính trong bộ giảm mẫu mặt nạ.

memory_fuser_num_layers (`int`, *tuỳ chọn*, mặc định là 2) : Số lượng lớp trong bộ hợp nhất bộ nhớ.

memory_fuser_embed_dim (`int`, *optional*, mặc định là 256) : Kích thước của embedding bộ nhớ fuser.

memory_fuser_kernel_size (`int`, *tuỳ chọn*, mặc định là 7) : Kích thước kernel cho bộ hợp nhất bộ nhớ.

memory_fuser_padding (`int`, *tuỳ chọn*, mặc định là 3) : Lề đệm cho bộ hợp nhất bộ nhớ.

memory_fuser_layer_scale_init_value (`float`, *optional*, mặc định là 1e-06) : Giá trị ban đầu cho layer scale trong memory fuser.

memory_fuser_hidden_act (`str`, *tùy chọn*, mặc định là `"gelu"`) : Hàm kích hoạt phi tuyến tính trong bộ hợp nhất bộ nhớ.

Đây là lớp cấu hình để lưu trữ cấu hình của một EdgeTamVideoModel. Nó được sử dụng để khởi tạo một mô hình Edgetam 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 [yonigozlan/EdgeTAM-hf](https://huggingface.co/yonigozlan/EdgeTAM-hf)

Các đối tượng cấu hình kế thừa từ [PreTrainedConfig](/docs/transformers/main/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/main/vi/main_classes/configuration#transformers.PreTrainedConfig) để biết thêm thông tin.

Ví dụ:

```python
>>> from transformers import (
...     EdgeTamVisionConfig,
...     EdgeTamVideoPromptEncoderConfig,
...     EdgeTamVideoMaskDecoderConfig,
...     EdgeTamVideoModel,
...     EdgeTamVideoConfig,
... )

>>> # Initializing a EdgeTamVideoConfig with `"facebook/edgetam.1_hiera_tiny"` style configuration
>>> configuration = EdgeTamVideoConfig()

>>> # Initializing a EdgeTamVideoModel (with random weights) from the `"facebook/edgetam.1_hiera_tiny"` style configuration
>>> model = EdgeTamVideoModel(configuration)

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

>>> # We can also initialize a EdgeTamConfig from a EdgeTamVisionConfig, EdgeTamPromptEncoderConfig, and EdgeTamMaskDecoderConfig

>>> # Initializing EDGETAM vision encoder, memory attention, and memory encoder configurations
>>> vision_config = EdgeTamVisionConfig()
>>> prompt_encoder_config = EdgeTamVideoPromptEncoderConfig()
>>> mask_decoder_config = EdgeTamVideoMaskDecoderConfig()

>>> config = EdgeTamVideoConfig(vision_config, prompt_encoder_config, mask_decoder_config)
```

## EdgeTamVideoInferenceSession[[transformers.EdgeTamVideoInferenceSession]]

#### transformers.EdgeTamVideoInferenceSession[[transformers.EdgeTamVideoInferenceSession]]

```python
transformers.EdgeTamVideoInferenceSession(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/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L940)

**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.EdgeTamVideoInferenceSession.add_mask_inputs]]

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

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1060)

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

#### add_new_frame[[transformers.EdgeTamVideoInferenceSession.add_new_frame]]

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

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1135)

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

#### add_point_inputs[[transformers.EdgeTamVideoInferenceSession.add_point_inputs]]

```python
add_point_inputs(obj_idx: int, frame_idx: int, inputs: dict)
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1046)

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

#### get_frame[[transformers.EdgeTamVideoInferenceSession.get_frame]]

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

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1151)

Lấy khung từ video.

#### get_obj_num[[transformers.EdgeTamVideoInferenceSession.get_obj_num]]

```python
get_obj_num()
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1041)

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.EdgeTamVideoInferenceSession.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/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1108)

**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.EdgeTamVideoInferenceSession.obj_id_to_idx]]

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

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1015)

Á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.EdgeTamVideoInferenceSession.obj_idx_to_id]]

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

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1037)

Á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.EdgeTamVideoInferenceSession.remove_mask_inputs]]

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

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1066)

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

#### remove_point_inputs[[transformers.EdgeTamVideoInferenceSession.remove_point_inputs]]

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

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1056)

Xóa các đầu vào điểm.

#### reset_inference_session[[transformers.EdgeTamVideoInferenceSession.reset_inference_session]]

```python
reset_inference_session()
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1167)

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

#### reset_tracking_data[[transformers.EdgeTamVideoInferenceSession.reset_tracking_data]]

```python
reset_tracking_data()
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1155)

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

#### store_output[[transformers.EdgeTamVideoInferenceSession.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/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L1071)

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

## EdgeTamVideoModel[[transformers.EdgeTamVideoModel]]

#### transformers.EdgeTamVideoModel[[transformers.EdgeTamVideoModel]]

```python
transformers.EdgeTamVideoModel(config: EdgeTamVideoConfig)
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L2060)

**Tham số:**

config ([EdgeTamVideoConfig](/docs/transformers/main/vi/model_doc/edgetam_video#transformers.EdgeTamVideoConfig)) : 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/main/vi/main_classes/model#transformers.PreTrainedModel.from_pretrained) để tải trọng số mô hình.

Mô hình Edgetam Video ở dạng 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/main/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.EdgeTamVideoModel.forward]]

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

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L2194)

**Tham số:**

inference_session (`~models.edgetam_video.modeling_edgetam_video.EdgeTamVideoInferenceSession`) : Đố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.

**Trả về:** `EdgeTamVideoSegmentationOutput` hoặc `tuple(torch.Tensor)`

Một `EdgeTamVideoSegmentationOutput` 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 ([EdgeTamVideoConfig](/docs/transformers/main/vi/model_doc/edgetam_video#transformers.EdgeTamVideoConfig)) và đầu vào.

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

- **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.
- **pred_masks** (`torch.Tensor` có hình dạng `(batch_size, num_masks, height, width)`) -- Các mặt nạ dự đoán được lưu ở độ phân giải của mô hình.
- **object_score_logits** (`torch.Tensor` có hình dạng `(batch_size,)`, *tùy chọn*) -- Logits cho điểm của các đối tượng, cho biết các đối tượng có hiện diện hay không.
- **frame_idx** (`int`, *tùy chọn*) -- Chỉ số khung của video.

#### get_image_features[[transformers.EdgeTamVideoModel.get_image_features]]

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

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/edgetam_video/modeling_edgetam_video.py#L2293)

**Tham số:**

pixel_values (`torch.Tensor`) : Giá trị pixel đầu vào có hình dạng `(batch_size, num_channels, height, width)`.

**Trả về:** `EdgeTamVideoVisionEncoderOutput` hoặc `tuple(torch.Tensor)`

Một `EdgeTamVideoVisionEncoderOutput` 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 ([EdgeTamVideoConfig](/docs/transformers/main/vi/model_doc/edgetam_video#transformers.EdgeTamVideoConfig)) và đầu vào.

- **last_hidden_state** (`torch.Tensor` có hình dạng `(batch_size, height, width, hidden_size)`) -- Chuỗi các hidden-state tại đầu ra của lớp cuối cùng của mô hình.
- **pooler_output** (`torch.Tensor` có hình dạng `(batch_size, hidden_size)`) -- Trạng thái ẩn của lớp cuối cùng cho token đầu tiên của chuỗi (token phân loại) sau khi được xử lý thêm thông qua các lớp dùng cho tác vụ tiền huấn luyện bổ trợ. Ví dụ, đối với các mô hình thuộc họ BERT, giá trị này trả về token phân loại sau khi được xử lý qua một lớp tuyến tính và một hàm kích hoạt tanh. Trọng số của lớp tuyến tính được huấn luyện từ mục tiêu dự đoán câu tiếp theo (phân loại) trong quá trình tiền huấn luyện.
- **hidden_states** (`tuple(torch.Tensor)`, *tuỳ chọn*, được trả về khi `output_hidden_states=True` được truyền vào hoặc khi `config.output_hidden_states=True`) -- Bộ tuple của `torch.Tensor` (một cho đầu ra của các embedding, nếu mô hình có lớp embedding, + một cho đầu ra của mỗi lớp) có hình dạng `(batch_size, sequence_length, hidden_size)`.

  Trạng thái ẩn của mô hình tại đầu ra của mỗi lớp cùng với các đầu ra embedding ban đầu tùy chọn.
- **attentions** (`tuple(torch.Tensor)`, *tuỳ chọn*, được trả về khi `output_attentions=True` được truyền vào hoặc khi `config.output_attentions=True`) -- Bộ tuple của `torch.Tensor` (một cho mỗi lớp) có hình dạng `(batch_size, num_heads, sequence_length, sequence_length)`.

  Trọng số chú ý sau softmax của attention, được sử dụng để tính trung bình có trọng số trong các đầu self-attention.
- **fpn_hidden_states** (`tuple(torch.Tensor)`) -- Tuple của `torch.Tensor` (một tensor cho mỗi mức đặc trưng, từ độ phân giải cao xuống thấp) có hình dạng `(batch_size, hidden_size, height, width)`. Các bản đồ đặc trưng từ phần neck của Feature Pyramid Network.
- **fpn_position_encoding** (`tuple(torch.Tensor)`) -- Tuple của `torch.Tensor` (một cho mỗi mức đặc trưng, từ độ phân giải cao xuống thấp) có hình dạng `(batch_size, hidden_size, height, width)`. Các mã hóa vị trí tương ứng với `fpn_hidden_states`.

