Transformers documentation
EdgeTAMVideo
Mô hình này được công bố trên HF papers vào ngày 13-01-2025 và được đóng góp cho Hugging Face Transformers vào ngày 29-09-2025.
EdgeTAMVideo
Tổng quan
Mô hình EdgeTAM được đề xuất trong EdgeTAM: On-Device Track Anything Model 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. Mã nguồn gốc có thể được tìm thấy tại đây.
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
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 framesTheo 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:
# 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 framesTinh 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:
# 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_masksSuy 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:
# 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:
# 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 framesEdgeTamVideoMaskDecoderConfig
lớp transformers.EdgeTamVideoMaskDecoderConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 256hidden_act: str = 'gelu'mlp_dim: int = 2048num_hidden_layers: int = 2num_attention_heads: int = 8attention_downsample_rate: int = 2num_multimask_outputs: int = 3iou_head_depth: int = 3iou_head_hidden_dim: int = 256dynamic_multimask_via_stability: bool = Truedynamic_multimask_stability_delta: float = 0.05dynamic_multimask_stability_thresh: float = 0.98 )
Tham số
- hidden_size (
int, tùy 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, tùy chọn, mặc định là 2048) — Kích thước của MLP trong transformer hai chiều. - num_hidden_layers (
int, tùy chọn, mặc định là2) — Số lượng lớp ẩn trong bộ giải mã Transformer. - num_attention_heads (
int, tùy chọn, mặc định là8) — Số lượng đầu attention cho mỗi lớp attention trong bộ giải mã Transformer. - attention_downsample_rate (
int, tùy chọn, mặc định là 2) — Tỷ lệ hạ mẫu cho các lớp attention. - num_multimask_outputs (
int, tùy chọn, mặc định là 3) — Số lượng đầu ra đa mặt nạ. - iou_head_depth (
int, tùy chọn, mặc định là 3) — Độ sâu của đầu IoU. - iou_head_hidden_dim (
int, tùy chọn, mặc định là 256) — 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 qua stability hay không. - dynamic_multimask_stability_delta (
float, tùy chọn, mặc định là 0.05) — Delta ổn định cho dynamic multimask. - dynamic_multimask_stability_thresh (
float, tùy chọn, 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ủa yonigozlan/EdgeTAM-hf
Các đối tượng cấu hình kế thừa từ 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 để biết thêm thông tin.
EdgeTamVideoPromptEncoderConfig
lớp transformers.EdgeTamVideoPromptEncoderConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 256image_size: int | list[int] | tuple[int, int] = 1024patch_size: int | list[int] | tuple[int, int] = 16mask_input_channels: int = 16num_point_embeddings: int = 4hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06scale: int = 1 )
Tham số
- hidden_size (
int, tùy 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, tùy chọn, mặc định là 16) — Số lượng kênh được đưa vào moduleMaskDecoder. - num_point_embeddings (
int, tùy 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, tùy chọn, mặc định là1e-06) — Giá trị epsilon được sử dụng bởi các lớp chuẩn hóa lớp (layer normalization). - scale (
float, tùy 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ủa yonigozlan/EdgeTAM-hf
Các đối tượng cấu hình kế thừa từ 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 để biết thêm thông tin.
EdgeTamVideoConfig
lớp transformers.EdgeTamVideoConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneprompt_encoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonemask_decoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneinitializer_range: float = 0.02num_maskmem: int = 7image_size: int | list[int] | tuple[int, int] = 1024sigmoid_scale_for_mem_enc: float = 20.0sigmoid_bias_for_mem_enc: float = -10.0enable_occlusion_spatial_embedding: bool = Truemultimask_output_in_sam: bool = Truemultimask_min_pt_num: int = 0multimask_max_pt_num: int = 1multimask_output_for_tracking: bool = Truemax_object_pointers_in_encoder: int = 16max_cond_frame_num: int = -1enable_temporal_pos_encoding_for_object_pointers: bool = Truememory_attention_hidden_size: int = 256memory_attention_num_layers: int = 2memory_attention_num_attention_heads: int = 1memory_attention_downsample_rate: int = 1memory_attention_mlp_hidden_size: int = 2048memory_attention_mlp_hidden_act: str = 'relu'memory_attention_dropout: float | int = 0.1memory_attention_rope_feat_sizes: list | None = Nonememory_attention_rope_k_sizes: list | None = Nonememory_attention_rope_dropout: float | int = 0.1rope_parameters: dict | None = Noneperceiver_resampler_num_latents: int = 256perceiver_resampler_num_latents_2d: int = 256perceiver_resampler_hidden_size: int = 64perceiver_resampler_mlp_intermediate_size: int = 256perceiver_resampler_num_attention_heads: int = 1perceiver_resampler_attention_head_dim: int = 64perceiver_resampler_num_layers: int = 2perceiver_resampler_hidden_dropout: float | int = 0.0perceiver_resampler_attention_dropout: float | int = 0.0memory_encoder_hidden_size: int = 256memory_encoder_output_channels: int = 64mask_downsampler_embed_dim: int = 256memory_fuser_intermediate_dim: int = 1024mask_downsampler_kernel_size: int = 3mask_downsampler_stride: int = 2mask_downsampler_padding: int = 1mask_downsampler_total_stride: int = 16mask_downsampler_hidden_act: str = 'gelu'memory_fuser_num_layers: int = 2memory_fuser_embed_dim: int = 256memory_fuser_kernel_size: int = 7memory_fuser_padding: int = 3memory_fuser_layer_scale_init_value: float = 1e-06memory_fuser_hidden_act: str = 'gelu' )
Tham số
- vision_config (
Union[dict, ~configuration_utils.PreTrainedConfig], tùy chọn) — Đối tượng cấu hình hoặc từ điển của bộ khung thị giác. - prompt_encoder_config (Union[
dict,EdgeTamVideoPromptEncoderConfig], tuỳ chọn) — Từ điển các tùy chọn cấu hình được sử dụng để khởi tạo EdgeTamVideoPromptEncoderConfig. - mask_decoder_config (Union[
dict,EdgeTamVideoMaskDecoderConfig], tuỳ chọn) — Từ điển các tùy chọn cấu hình được sử dụng để khởi tạo EdgeTamMaskDecoderConfig. - initializer_range (
float, tùy chọn, 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 ô nhớ cho bộ nhớ mask. - 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, tùy 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, tùy 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 spatial embedding cho các vùng bị che khuất hay không. - multimask_output_in_sam (
bool, tùy chọn, mặc định làTrue) — Có nên xuất nhiều mask từ đầu SAM hay không. - multimask_min_pt_num (
int, tùy chọn, mặc định là 0) — Số lượng điểm tối thiểu để kích hoạt đầu ra multimask. - multimask_max_pt_num (
int, tùy chọn, mặc định là 1) — Số lượng điểm tối đa để kích hoạt đầu ra multimask. - multimask_output_for_tracking (
bool, tùy 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, tùy 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, tùy 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 memory attention. Đặ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, tùy chọn, mặc định là 256) — Kích thước chiều của các trạng thái ẩn của chú ý bộ nhớ. - memory_attention_num_layers (
int, tùy chọn, mặc định là 2) — Số lượng lớp trong module chú ý bộ nhớ. - memory_attention_num_attention_heads (
int, tùy chọn, mặc định là 1) — Số lượng attention heads cho mỗi lớp attention trong memory attention. - memory_attention_downsample_rate (
int, tùy chọn, mặc định là 1) — Tỷ lệ hạ mẫu cho các lớp attention. - memory_attention_mlp_hidden_size (
int, tùy 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 trong mạng feedforward của module chú ý bộ nhớ. - memory_attention_dropout (
float, tùy chọn, mặc định là 0.1) — Tỷ lệ dropout cho module chú ý bộ nhớ. - memory_attention_rope_feat_sizes (
Tuple[int, int], tuỳ 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 đặc trưng khóa cho mã hóa vị trí RoPE trong chú ý bộ nhớ. - memory_attention_rope_dropout (
float, tùy chọn, 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ị chorope_thetavà 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ớimax_position_embeddingsdài hơn. - perceiver_resampler_num_latents (
int, tùy chọn, mặc định là 256) — Số lượng token tiềm ẩn 1D trong perceiver resampler. - perceiver_resampler_num_latents_2d (
int, tùy chọn, mặc định là 256) — Số lượng token tiềm ẩn 2D trong perceiver resampler. - perceiver_resampler_hidden_size (
int, tùy chọn, mặc định là 64) — Kích thước ẩn của perceiver resampler. - perceiver_resampler_mlp_intermediate_size (
int, tùy 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, tùy chọn, mặc định là 1) — Số lượng đầu chú ý trong perceiver resampler. - perceiver_resampler_attention_head_dim (
int, tùy chọn, mặc định là 64) — Kích thước của mỗi đầu chú ý trong perceiver resampler. - perceiver_resampler_num_layers (
int, tùy chọn, mặc định là 2) — Số lượng lớp trong perceiver resampler. - perceiver_resampler_hidden_dropout (
float, tùy chọn, mặc định là 0.0) — Tỷ lệ dropout cho các lớp ẩn trong perceiver resampler. - perceiver_resampler_attention_dropout (
float, tùy chọn, mặc định là 0.0) — Tỷ lệ dropout cho các lớp attention trong perceiver resampler. - memory_encoder_hidden_size (
int, tùy chọn, mặc định là 256) — Kích thước chiều của các trạng thái ẩn của bộ mã hóa bộ nhớ. - memory_encoder_output_channels (
int, tùy chọn, mặc định là 64) — Số lượng kênh đầu ra của bộ mã hóa bộ nhớ. - mask_downsampler_embed_dim (
int, tùy chọn, mặc định là 256) — Kích thước của embedding cho bộ giảm mẫu mặt nạ. - memory_fuser_intermediate_dim (
int, tuỳ chọn, mặc định là 1024) — Chiều trung gian của mạng feedforward của memory fuser. - mask_downsampler_kernel_size (
int, tùy chọn, mặc định là 3) — Kích thước kernel cho bộ giảm mẫu mặt nạ. - mask_downsampler_stride (
int, tùy chọn, mặc định là 2) — Bước (stride) của bộ giảm kích thước mask. - mask_downsampler_padding (
int, tùy chọn, mặc định là 1) — Độ đệm cho bộ giảm kích thước mask. - mask_downsampler_total_stride (
int, tùy chọn, mặc định là 16) — Tổng số bước nhảy (stride) của bộ giảm kích thước mask. - mask_downsampler_hidden_act (
str, tùy chọn, mặc định là"gelu") — Hàm kích hoạt phi tuyến 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, tuỳ chọn, mặc định là 256) — Kích thước của embedding memory 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, tùy chọn, mặc định là 3) — Độ đệm cho bộ hợp nhất bộ nhớ. - memory_fuser_layer_scale_init_value (
float, tuỳ chọn, 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ủa yonigozlan/EdgeTAM-hf
Các đối tượng cấu hình kế thừa từ 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 để biết thêm thông tin.
Ví dụ:
>>> 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
lớp transformers.EdgeTamVideoInferenceSession
< source >( 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 )
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, tùy chọn) — Chiều cao của video. - video_width (
int, tùy chọn) — Chiều 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") — Dtype được sử dụng cho video. - max_vision_features_cache_size (
int, tùy chọn, mặc định là 1) — Số lượng tối đa các đặc trưng thị giác đượ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.
Thêm đầu vào mask với việc đặt thiết bị tự động.
Thêm khung mới với việc đặt thiết bị tự động.
Thêm các đầu vào điểm với việc đặt thiết bị tự động.
Lấy khung từ video.
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
< source >( obj_idx: intframe_idx: intoutput_key: stris_conditioning_frame: bool = True )
Lấy kết quả với quản lý thiết bị thông minh.
Ánh xạ ID đối tượng tới chỉ số, tạo mục mới nếu cần.
Ánh xạ chỉ mục đối tượng phía mô hình sang id đối tượng phía client.
Xóa các đầu vào mask.
Xóa các đầu vào điểm.
Đặt lại dữ liệu theo dõi và bộ nhớ đệm.
Đặt lại dữ liệu theo dõi nhưng giữ lại bộ nhớ đệm.
store_output
< source >( obj_idx: intframe_idx: intoutput_key: str | None = Noneoutput_value: typing.Union[torch.Tensor, dict, NoneType] = Noneis_conditioning_frame: bool = True )
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ó dành cho khung điều kiện (conditioning frame) 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
lớp transformers.EdgeTamVideoModel
< source >( config: EdgeTamVideoConfig )
Tham số
- config (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 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() để 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. 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, v.v.)
Mô hình này cũng là một lớp con của 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
< source >( inference_session: EdgeTamVideoInferenceSessionframe_idx: int | None = Noneframe: typing.Optional[torch.Tensor] = Nonereverse: bool = False**kwargs ) → EdgeTamVideoSegmentationOutput or tuple(torch.Tensor)
Tham số
- inference_session (
~models.edgetam_video.modeling_edgetam_video.EdgeTamVideoInferenceSession) — Đối tượng phiên suy luận video. - frame_idx (
int, tùy chọn) — Chỉ số của khung hình cầ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ó nên 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
thành phần khác nhau tùy thuộc vào cấu hình (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.Tensorcó hình dạng(batch_size, num_masks, height, width)) — Các mặt nạ dự đoán được lưu trữ ở độ phân giải của mô hình. - object_score_logits (
torch.Tensorcó 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
< source >( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → EdgeTamVideoVisionEncoderOutput or tuple(torch.Tensor)
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
thành phần khác nhau tùy thuộc vào cấu hình (EdgeTamVideoConfig) và đầu vào.
last_hidden_state (
torch.Tensorcó 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.Tensorcó hình dạng(batch_size, hidden_size)) — Trạng thái ẩn của lớp cuối cùng của token đầu tiên trong chuỗi (token phân loại) sau khi được xử lý thêm qua các lớp được sử 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ề khioutput_hidden_states=Trueđược truyền vào hoặc khiconfig.output_hidden_states=True) — Bộ tuple củatorch.Tensor(một cho đầu ra của embeddings, 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ề khioutput_attentions=Trueđược truyền vào hoặc khiconfig.output_attentions=True) — Tuple củatorch.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ủatorch.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ủatorch.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ớifpn_hidden_states.