# TimeSformer

## Tổng quan

Mô hình TimeSformer được đề xuất trong [TimeSformer: Is Space-Time Attention All You Need for Video Understanding?](https://huggingface.co/papers/2102.05095) bởi Facebook Research. Công trình này là một cột mốc trong lĩnh vực nhận diện hành động khi là transformer video đầu tiên. Nó đã truyền cảm hứng cho nhiều bài báo về hiểu và phân loại video dựa trên transformer.

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

*Chúng tôi trình bày một phương pháp phân loại video không sử dụng tích chập, được xây dựng hoàn toàn dựa trên tự chú ý (self-attention) trên không gian và thời gian. Phương pháp của chúng tôi, có tên là "TimeSformer", điều chỉnh kiến trúc Transformer tiêu chuẩn cho video bằng cách cho phép học đặc trưng không-thời gian trực tiếp từ một chuỗi các mảnh (patch) ở cấp độ khung hình. Nghiên cứu thực nghiệm của chúng tôi so sánh các sơ đồ tự chú ý khác nhau và cho thấy rằng "chú ý chia tách" (divided attention), trong đó chú ý thời gian và chú ý không gian được áp dụng riêng biệt trong mỗi khối, dẫn đến độ chính xác phân loại video tốt nhất trong số các lựa chọn thiết kế được xem xét. Mặc dù có thiết kế hoàn toàn mới, TimeSformer đạt được kết quả tiên tiến (state-of-the-art) trên một số bộ chuẩn nhận dạng hành động, bao gồm độ chính xác được báo cáo tốt nhất trên Kinetics-400 và Kinetics-600. Cuối cùng, so với các mạng tích chập 3D, mô hình của chúng tôi huấn luyện nhanh hơn, có thể đạt hiệu suất kiểm tra cao hơn đáng kể (với sự sụt giảm nhỏ về độ chính xác) và cũng có thể được áp dụng cho các đoạn video dài hơn nhiều (trên một phút). Mã nguồn và mô hình có sẵn tại: [this https URL](https://github.com/facebookresearch/TimeSformer).*

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

## Mẹo sử dụng

Có nhiều biến thể được huấn luyện trước. Hãy chọn mô hình được huấn luyện trước của bạn dựa trên bộ dữ liệu mà nó được huấn luyện. Hơn nữa, số lượng khung hình đầu vào cho mỗi clip thay đổi dựa trên kích thước của mô hình, vì vậy bạn nên xem xét tham số này khi chọn mô hình được huấn luyện trước.

## Tài nguyên

- [Hướng dẫn nhiệm vụ phân loại video](../tasks/video_classification)

## TimesformerConfig[[transformers.TimesformerConfig]]

#### transformers.TimesformerConfig[[transformers.TimesformerConfig]]

```python
transformers.TimesformerConfig(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, image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, num_frames: int = 8, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 12, intermediate_size: int = 3072, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, attention_probs_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, qkv_bias: bool = True, attention_type: str = 'divided_space_time', drop_path_rate: int = 0)
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/configuration_timesformer.py#L24)

**Tham số:**

image_size (`Union[int, list[int], tuple[int, int]]`, *tùy chọn*, mặc định là `224`) : 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.

num_channels (`int`, *tuỳ chọn*, mặc định là `3`) : Số lượng kênh đầu vào.

num_frames (`int`, *tuỳ chọn*, mặc định là 8) : Số khung hình trong mỗi video.

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

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

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

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

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.

hidden_dropout_prob (`Union[float, int]`, *tùy chọn*, mặc định là `0.0`) : Xác suất dropout cho tất cả các lớp fully connected trong embeddings, encoder và pooler.

attention_probs_dropout_prob (`Union[float, int]`, *tùy chọn*, mặc định là `0.0`) : Tỷ lệ dropout cho các xác suất chú ý.

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

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

qkv_bias (`bool`, *tùy chọn*, mặc định là `True`) : Có thêm bias vào queries, keys và values hay không.

attention_type (`str`, *tùy chọn*, mặc định là `"divided_space_time"`) : Kiểu attention cần sử dụng. Phải là một trong `"divided_space_time"`, `"space_only"`, `"joint_space_time"`.

drop_path_rate (`int`, *optional*, mặc định là `0`) : Tỷ lệ drop path cho việc hợp nhất patch.

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

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 TimesformerConfig, TimesformerModel

>>> # Initializing a TimeSformer timesformer-base style configuration
>>> configuration = TimesformerConfig()

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

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

## TimesformerVideoProcessor[[transformers.TimesformerVideoProcessor]]

#### transformers.TimesformerVideoProcessor[[transformers.TimesformerVideoProcessor]]

```python
transformers.TimesformerVideoProcessor(**kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/video_processing_timesformer.py#L25)

**Tham số:**

do_convert_rgb (`bool`, *kwargs*, *tuỳ chọn*, mặc định là `True`) : Có chuyển đổi hình ảnh sang RGB hay không.

do_resize (`bool`, *kwargs*, *tuỳ chọn*, mặc định là `True`) : Xác định có thay đổi kích thước ảnh hay không.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, mặc định là `{'shortest_edge' : 224}`): Mô tả kích thước đầu vào tối đa cho mô hình.

default_to_square (`bool`, *kwargs*, *optional*, mặc định là `False`) : Có nên mặc định sử dụng ảnh vuông khi thay đổi kích thước hay không, nếu size là một số nguyên.

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*, mặc định là `2`) : Bộ lọc lấy mẫu lại (resampling filter) được sử dụng khi thay đổi kích thước ảnh. Giá trị này có thể là một trong các hằng số liệt kê (enum) của `PILImageResampling`. Chỉ có hiệu lực khi `do_resize` được đặt thành `True`.

do_rescale (`bool`, *kwargs*, *tuỳ chọn*, mặc định là `True`) : Xác định có nên điều chỉnh lại tỷ lệ ảnh hay không.

rescale_factor (`float`, *kwargs*, *optional*, mặc định là `0.00392156862745098`) : Hệ số để điều chỉnh lại kích thước ảnh nếu `do_rescale` được đặt thành `True`.

do_normalize (`bool`, *kwargs*, *tuỳ chọn*, mặc định là `True`) : Có chuẩn hóa hình ảnh hay không.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, mặc định là `[0.485, 0.456, 0.406]`) : Giá trị trung bình của ảnh để sử dụng cho việc chuẩn hóa. Chỉ có hiệu lực nếu `do_normalize` được đặt thành `True`.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, mặc định là `[0.229, 0.224, 0.225]`) : Độ lệch chuẩn của ảnh để sử dụng cho việc chuẩn hóa. Chỉ có hiệu lực nếu `do_normalize` được đặt thành `True`.

do_center_crop (`bool`, *kwargs*, *optional*, mặc định là `True`) : Xác định có cắt ảnh theo kiểu căn giữa hay không.

do_pad (`bool`, *kwargs*, *optional*) : Xác định có chèn padding cho ảnh hay không. Padding được thực hiện đến kích thước lớn nhất trong batch hoặc đến một kích thước vuông cố định cho mỗi ảnh. Chiến lược padding cụ thể phụ thuộc vào model.

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, mặc định là `{'height' : 224, 'width': 224}`): Kích thước của ảnh đầu ra sau khi áp dụng `center_crop`.

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *tuỳ chọn*) : Chỉ hỗ trợ `ChannelDimension.FIRST`. Được thêm vào để tương thích với các bộ xử lý chậm.

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *optional*) : Định dạng chiều kênh cho ảnh đầu vào. Nếu không được đặt, định dạng chiều kênh sẽ được suy ra từ ảnh đầu vào. Có thể là một trong các giá trị sau: - `"channels_first"` hoặc `ChannelDimension.FIRST`: ảnh ở định dạng (num_channels, height, width). - `"channels_last"` hoặc `ChannelDimension.LAST`: ảnh ở định dạng (height, width, num_channels). - `"none"` hoặc `ChannelDimension.NONE`: ảnh ở định dạng (height, width).

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : Thiết bị để xử lý các video. Nếu không được đặt, thiết bị sẽ được suy ra từ các video đầu vào.

do_sample_frames (`bool`, *kwargs*, *optional*, mặc định là `False`) : Xác định xem có lấy mẫu các khung hình từ video trước khi xử lý hay xử lý toàn bộ video.

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : Metadata của video, chứa thông tin về tổng thời lượng, fps và tổng số khung hình. Dữ liệu này sẽ được sử dụng để lấy mẫu các khung hình từ video hoặc tính toán mốc thời gian. Không truyền bất kỳ metadata nào trừ khi bạn đang cố gắng giải mã video thủ công trước khi xử lý

fps (`Annotated[int | float | None, None]`, *kwargs*) : Số khung hình mục tiêu cần lấy mẫu mỗi giây khi `do_sample_frames=True`.

num_frames (`Annotated[int | None, None]`, *kwargs*) : Số khung hình tối đa cần lấy mẫu khi `do_sample_frames=True`.

return_metadata (`bool`, *kwargs*, *tuỳ chọn*, mặc định là `False`) : Có trả về metadata của video hay không. Video metadata là một đối tượng chứa thông tin về thời lượng video, fps, backend giải mã, v.v.

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 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.

- ****kwargs** ([VideosKwargs](/docs/transformers/main/vi/main_classes/processors#transformers.VideosKwargs), *optional*) : Các tùy chọn xử lý bổ sung cho từng phương thức (text, hình ảnh, video, âm thanh). Các tham số cụ thể của model được liệt kê ở trên; xem lớp TypedDict để biết danh sách đầy đủ các đối số được hỗ trợ.

Tạo một trình xử lý video TimesformerVideoProcessor.

#### preprocess[[transformers.TimesformerVideoProcessor.preprocess]]

```python
preprocess(videos: 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]]], **kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/video_processing_timesformer.py#L41)

**Tham số:**

videos (`Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]`) : Video cần tiền xử lý. Kỳ vọng một video đơn hoặc một batch video có giá trị pixel từ 0 đến 255. Nếu truyền vào video có giá trị pixel từ 0 đến 1, hãy đặt `do_rescale=False`.

do_convert_rgb (`bool`, *kwargs*, *optional*) : Có chuyển đổi hình ảnh sang RGB hay không.

do_resize (`bool`, *kwargs*, *optional*) : Xác định có nên thay đổi kích thước ảnh hay không.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*): Mô tả các kích thước đầu vào tối đa của mô hình.

default_to_square (`bool`, *kwargs*, *tuỳ chọn*) : Có mặc định dùng ảnh vuông khi thay đổi kích thước hay không, nếu size là một số nguyên.

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : Bộ lọc resampling để sử dụng khi thay đổi kích thước ảnh. Giá trị này có thể là một trong các enum `PILImageResampling`. Chỉ có hiệu lực khi `do_resize` được đặt thành `True`.

do_rescale (`bool`, *kwargs*, *tuỳ chọn*) : Xác định có nên điều chỉnh lại tỷ lệ hình ảnh hay không.

rescale_factor (`float`, *kwargs*, *optional*) : Hệ số để thay đổi tỷ lệ ảnh nếu `do_rescale` được đặt thành `True`.

do_normalize (`bool`, *kwargs*, *tuỳ chọn*) : Xác định có chuẩn hóa hình ảnh hay không.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : Giá trị trung bình của ảnh để sử dụng cho việc chuẩn hóa. Chỉ có hiệu lực nếu `do_normalize` được đặt thành `True`.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : Độ lệch chuẩn của ảnh để sử dụng cho việc chuẩn hóa. Chỉ có hiệu lực nếu `do_normalize` được đặt thành `True`.

do_center_crop (`bool`, *kwargs*, *optional*) : Có nên cắt ảnh theo kiểu căn giữa hay không.

do_pad (`bool`, *kwargs*, *optional*) : Xác định có chèn padding cho ảnh hay không. Padding được thực hiện đến kích thước lớn nhất trong batch hoặc đến một kích thước vuông cố định cho mỗi ảnh. Chiến lược padding cụ thể phụ thuộc vào model.

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : Kích thước của ảnh đầu ra sau khi áp dụng `center_crop`.

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *tuỳ chọn*) : Chỉ hỗ trợ `ChannelDimension.FIRST`. Được thêm vào để tương thích với các bộ xử lý chậm.

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *optional*) : Định dạng chiều kênh cho ảnh đầu vào. Nếu không được đặt, định dạng chiều kênh sẽ được suy ra từ ảnh đầu vào. Có thể là một trong các giá trị sau: - `"channels_first"` hoặc `ChannelDimension.FIRST`: ảnh ở định dạng (num_channels, height, width). - `"channels_last"` hoặc `ChannelDimension.LAST`: ảnh ở định dạng (height, width, num_channels). - `"none"` hoặc `ChannelDimension.NONE`: ảnh ở định dạng (height, width).

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : Thiết bị để xử lý các video. Nếu không được đặt, thiết bị sẽ được suy ra từ các video đầu vào.

do_sample_frames (`bool`, *kwargs*, *tuỳ chọn*) : Xác định xem có lấy mẫu các khung hình từ video trước khi xử lý hay xử lý toàn bộ video.

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : Metadata của video, chứa thông tin về tổng thời lượng, fps và tổng số khung hình. Dữ liệu này sẽ được sử dụng để lấy mẫu các khung hình từ video hoặc tính toán mốc thời gian. Không truyền bất kỳ metadata nào trừ khi bạn đang cố gắng giải mã video thủ công trước khi xử lý

fps (`Annotated[int | float | None, None]`, *kwargs*) : Số khung hình mục tiêu cần lấy mẫu mỗi giây khi `do_sample_frames=True`.

num_frames (`Annotated[int | None, None]`, *kwargs*) : Số khung hình tối đa cần lấy mẫu khi `do_sample_frames=True`.

return_metadata (`bool`, *kwargs*, *tuỳ chọn*) : Xác định có trả về metadata của video hay không. Video metadata là một đối tượng chứa thông tin về thời lượng video, fps, backend giải mã, v.v.

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : Trả về các tensor đã xếp chồng nếu được đặt thành `'pt'`, ngược lại trả về một danh sách các tensor.

**Trả về:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- Từ điển chứa các danh sách/mảng/tensor được trả về bởi phương thức __call__ ('pixel_values', v.v.).
- **tensor_type** (`Union[None, str, TensorType]`, *tùy chọn*) -- Bạn có thể cung cấp tensor_type tại đây để chuyển đổi các danh sách số nguyên trong Tensor PyTorch/Numpy khi khởi tạo.

## TimesformerModel[[transformers.TimesformerModel]]

#### transformers.TimesformerModel[[transformers.TimesformerModel]]

```python
transformers.TimesformerModel(config: TimesformerConfig)
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/modeling_timesformer.py#L462)

**Tham số:**

config ([TimesformerConfig](/docs/transformers/main/vi/model_doc/timesformer#transformers.TimesformerConfig)) : 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 Timesformer cơ bản, xuất ra các hidden-states thô mà không có 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.TimesformerModel.forward]]

```python
forward(pixel_values: Tensor, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/modeling_timesformer.py#L478)

**Tham số:**

pixel_values (`torch.Tensor` có shape `(batch_size, num_channels, image_size, image_size)`) : Các tensor tương ứng với các ảnh đầu vào. Giá trị pixel có thể được lấy bằng [VideoMAEImageProcessor](/docs/transformers/main/vi/model_doc/videomae#transformers.VideoMAEImageProcessor). Xem [VideoMAEImageProcessor.__call__()](/docs/transformers/main/vi/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) để biết chi tiết (`processor_class` sử dụng [VideoMAEImageProcessor](/docs/transformers/main/vi/model_doc/videomae#transformers.VideoMAEImageProcessor) để xử lý ảnh).

output_attentions (`bool`, *tùy chọn*) : Có trả về các tensor chú ý của tất cả các lớp chú ý hay không. Xem `attentions` trong phần tensor trả về để biết thêm chi tiết.

output_hidden_states (`bool`, *tuỳ chọn*) : Có trả về trạng thái ẩn của tất cả các lớp hay không. Xem `hidden_states` trong phần tensor trả về để biết thêm chi tiết.

return_dict (`bool`, *tùy chọn*) : Có trả về [ModelOutput](/docs/transformers/main/vi/main_classes/output#transformers.utils.ModelOutput) thay vì một tuple thông thường hay không.

**Trả về:** [BaseModelOutput](/docs/transformers/main/vi/main_classes/output#transformers.modeling_outputs.BaseModelOutput) hoặc `tuple(torch.Tensor)`

Một [BaseModelOutput](/docs/transformers/main/vi/main_classes/output#transformers.modeling_outputs.BaseModelOutput) 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 ([TimesformerConfig](/docs/transformers/main/vi/model_doc/timesformer#transformers.TimesformerConfig)) và đầu vào.

Phương thức forward của [TimesformerModel](/docs/transformers/main/vi/model_doc/timesformer#transformers.TimesformerModel) ghi đè lên phương thức đặc biệt `__call__`.

Mặc dù công thức cho bước truyền tiến cần được định nghĩa bên trong hàm này, bạn nên gọi instance của `Module` sau đó thay vì gọi hàm này, vì instance `Module` sẽ đảm nhận việc thực hiện các bước tiền xử lý và hậu xử lý, trong khi hàm này sẽ bỏ qua chúng một cách im lặng.

- **last_hidden_state** (`torch.Tensor` có hình dạng `(batch_size, sequence_length, 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.
- **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.

Ví dụ:

```python
>>> import av
>>> import numpy as np

>>> from transformers import AutoImageProcessor, TimesformerModel
>>> from huggingface_hub import hf_hub_download

>>> np.random.seed(0)

>>> def read_video_pyav(container, indices):
...     '''
...     Decode the video with PyAV decoder.
...     Args:
...         container (`av.container.input.InputContainer`): PyAV container.
...         indices (`list[int]`): List of frame indices to decode.
...     Returns:
...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
...     '''
...     frames = []
...     container.seek(0)
...     start_index = indices[0]
...     end_index = indices[-1]
...     for i, frame in enumerate(container.decode(video=0)):
...         if i > end_index:
...             break
...         if i >= start_index and i in indices:
...             frames.append(frame)
...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])

>>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
...     '''
...     Sample a given number of frame indices from the video.
...     Args:
...         clip_len (`int`): Total number of frames to sample.
...         frame_sample_rate (`int`): Sample every n-th frame.
...         seg_len (`int`): Maximum allowed index of sample's last frame.
...     Returns:
...         indices (`list[int]`): List of sampled frame indices
...     '''
...     converted_len = int(clip_len * frame_sample_rate)
...     end_idx = np.random.randint(converted_len, seg_len)
...     start_idx = end_idx - converted_len
...     indices = np.linspace(start_idx, end_idx, num=clip_len)
...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
...     return indices

>>> # video clip consists of 300 frames (10 seconds at 30 FPS)
>>> file_path = hf_hub_download(
...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)

>>> # sample 8 frames
>>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)

>>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
>>> model = TimesformerModel.from_pretrained("facebook/timesformer-base-finetuned-k400")

>>> # prepare video for the model
>>> inputs = image_processor(list(video), return_tensors="pt")

>>> # forward pass
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 1569, 768]
```

## TimesformerForVideoClassification[[transformers.TimesformerForVideoClassification]]

#### transformers.TimesformerForVideoClassification[[transformers.TimesformerForVideoClassification]]

```python
transformers.TimesformerForVideoClassification(config: TimesformerConfig)
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/modeling_timesformer.py#L595)

**Tham số:**

config ([TimesformerConfig](/docs/transformers/main/vi/model_doc/timesformer#transformers.TimesformerConfig)) : 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.

TimeSformer Model transformer với đầu phân loại video phía trên (một lớp tuyến tính phía trên trạng thái ẩn cuối cùng của token [CLS]) ví dụ cho ImageNet.

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.TimesformerForVideoClassification.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[Nguồn](https://github.com/huggingface/transformers/blob/main/src/transformers/models/timesformer/modeling_timesformer.py#L608)

**Tham số:**

pixel_values (`torch.Tensor` có shape `(batch_size, num_channels, image_size, image_size)`, *tùy chọn*) : Các tensor tương ứng với các ảnh đầu vào. Giá trị pixel có thể được lấy bằng cách sử dụng [VideoMAEImageProcessor](/docs/transformers/main/vi/model_doc/videomae#transformers.VideoMAEImageProcessor). Xem [VideoMAEImageProcessor.__call__()](/docs/transformers/main/vi/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) để biết chi tiết (`processor_class` sử dụng [VideoMAEImageProcessor](/docs/transformers/main/vi/model_doc/videomae#transformers.VideoMAEImageProcessor) để xử lý ảnh).

labels (`torch.LongTensor` có hình dạng `(batch_size,)`, *tùy chọn*) : Nhãn để tính toán tổn thất phân loại/hồi quy hình ảnh. Chỉ số phải nằm trong `[0, ..., config.num_labels - 1]`. Nếu `config.num_labels == 1`, tổn thất hồi quy sẽ được tính toán (tổn thất Mean-Square). Nếu `config.num_labels > 1`, tổn thất phân loại sẽ được tính toán (Cross-Entropy).

output_attentions (`bool`, *tùy chọn*) : Có trả về các tensor chú ý của tất cả các lớp chú ý hay không. Xem `attentions` trong phần tensor trả về để biết thêm chi tiết.

output_hidden_states (`bool`, *tuỳ chọn*) : Có trả về trạng thái ẩn của tất cả các lớp hay không. Xem `hidden_states` trong phần tensor trả về để biết thêm chi tiết.

return_dict (`bool`, *tùy chọn*) : Có trả về [ModelOutput](/docs/transformers/main/vi/main_classes/output#transformers.utils.ModelOutput) thay vì một tuple thông thường hay không.

**Trả về:** [ImageClassifierOutput](/docs/transformers/main/vi/main_classes/output#transformers.modeling_outputs.ImageClassifierOutput) hoặc `tuple(torch.Tensor)`

Một [ImageClassifierOutput](/docs/transformers/main/vi/main_classes/output#transformers.modeling_outputs.ImageClassifierOutput) 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 ([TimesformerConfig](/docs/transformers/main/vi/model_doc/timesformer#transformers.TimesformerConfig)) và đầu vào.

Phương thức forward của [TimesformerForVideoClassification](/docs/transformers/main/vi/model_doc/timesformer#transformers.TimesformerForVideoClassification) ghi đè lên phương thức đặc biệt `__call__`.

Mặc dù công thức cho bước truyền tiến cần được định nghĩa bên trong hàm này, bạn nên gọi instance của `Module` sau đó thay vì gọi hàm này, vì instance `Module` sẽ đảm nhận việc thực hiện các bước tiền xử lý và hậu xử lý, trong khi hàm này sẽ bỏ qua chúng một cách im lặng.

- **loss** (`torch.Tensor` có shape `(1,)`, *optional*, được trả về khi `labels` được cung cấp) -- Loss phân loại (hoặc hồi quy nếu config.num_labels==1).
- **logits** (`torch.Tensor` có hình dạng `(batch_size, config.num_labels)`) -- Điểm phân loại (hoặc hồi quy nếu config.num_labels==1) (trước SoftMax).
- **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 embeddings, nếu mô hình có lớp embedding, + một cho đầu ra của mỗi giai đoạn) có hình dạng `(batch_size, sequence_length, hidden_size)`. Hidden-states (còn gọi là feature maps) của mô hình tại đầu ra của mỗi giai đoạ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, patch_size, 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.

Ví dụ:

```python
>>> import av
>>> import torch
>>> import numpy as np

>>> from transformers import AutoImageProcessor, TimesformerForVideoClassification
>>> from huggingface_hub import hf_hub_download

>>> np.random.seed(0)

>>> def read_video_pyav(container, indices):
...     '''
...     Decode the video with PyAV decoder.
...     Args:
...         container (`av.container.input.InputContainer`): PyAV container.
...         indices (`list[int]`): List of frame indices to decode.
...     Returns:
...         result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
...     '''
...     frames = []
...     container.seek(0)
...     start_index = indices[0]
...     end_index = indices[-1]
...     for i, frame in enumerate(container.decode(video=0)):
...         if i > end_index:
...             break
...         if i >= start_index and i in indices:
...             frames.append(frame)
...     return np.stack([x.to_ndarray(format="rgb24") for x in frames])

>>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
...     '''
...     Sample a given number of frame indices from the video.
...     Args:
...         clip_len (`int`): Total number of frames to sample.
...         frame_sample_rate (`int`): Sample every n-th frame.
...         seg_len (`int`): Maximum allowed index of sample's last frame.
...     Returns:
...         indices (`list[int]`): List of sampled frame indices
...     '''
...     converted_len = int(clip_len * frame_sample_rate)
...     end_idx = np.random.randint(converted_len, seg_len)
...     start_idx = end_idx - converted_len
...     indices = np.linspace(start_idx, end_idx, num=clip_len)
...     indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
...     return indices

>>> # video clip consists of 300 frames (10 seconds at 30 FPS)
>>> file_path = hf_hub_download(
...     repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
... )
>>> container = av.open(file_path)

>>> # sample 8 frames
>>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container, indices)

>>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
>>> model = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")

>>> inputs = image_processor(list(video), return_tensors="pt")

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

>>> # model predicts one of the 400 Kinetics-400 classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
eating spaghetti
```

