Transformers documentation

X-CLIP

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2022-08-04에 HF papers에 게시되었으며, 2023-06-20에 Hugging Face Transformers에 기여되었습니다.

X-CLIP

개요

X-CLIP 모델은 Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling이 Expanding Language-Image Pretrained Models for General Video Recognition에서 제안했습니다. X-CLIP은 CLIP의 비디오용 최소 확장입니다. 이 모델은 텍스트 인코더, 크로스 프레임 비전 인코더, 멀티 프레임 통합 Transformer, 비디오 전용 프롬프트 생성기로 구성됩니다.

해당 논문의 초록은 다음과 같습니다:

대조적 언어-이미지 사전학습은 웹 규모 데이터에서 시각-텍스트 결합 표현을 학습하는 데 큰 성공을 거두며, 다양한 이미지 작업에서 뛰어난 “제로샷” 일반화 능력을 입증했습니다. 그러나 이러한 새로운 언어-이미지 사전학습 방법을 비디오 도메인에 효과적으로 확장하는 방법은 여전히 미해결 과제로 남아 있습니다. 본 연구에서는 새 모델을 처음부터 사전학습하는 대신, 사전학습된 언어-이미지 모델을 비디오 인식에 직접 적용하는 단순하면서도 효과적인 접근법을 제시합니다. 보다 구체적으로, 시간 차원 프레임 간 장거리 의존성을 포착하기 위해 프레임 간 정보를 명시적으로 교환하는 크로스 프레임 어텐션 메커니즘을 제안합니다. 해당 모듈은 경량이며 사전학습된 언어-이미지 모델에 매끄럽게 통합할 수 있습니다. 또한, 비디오 콘텐츠 정보를 활용하여 차별적인 텍스트 프롬프트를 생성하는 비디오 전용 프롬프팅 스킴을 제안합니다. 광범위한 실험을 통해 제안한 접근법이 효과적이며 다양한 비디오 인식 시나리오로 일반화될 수 있음을 입증했습니다. 특히, 완전 지도 학습 설정에서 제안한 접근법은 Kinectics-400에서 87.1%의 top-1 정확도를 달성했으며, Swin-L과 ViViT-H에 비해 FLOPs를 12분의 1로 줄였습니다. 제로샷 실험에서는 제안한 접근법이 두 가지 인기 있는 프로토콜에서 top-1 정확도 기준으로 각각 +7.6%와 +14.9%로 현재 최첨단(SOTA) 방법들을 상회했습니다. 소수샷 시나리오에서는 레이블이 붙은 데이터가 극도로 제한적인 상황에서 제안한 접근법이 기존 최선 방법들보다 각각 +32.1%와 +23.1% 높은 성능을 보였습니다.

팁:

  • X-CLIP의 사용법은 CLIP와 동일합니다.
drawing X-CLIP architecture. Taken from the original paper.

이 모델은 nielsr님이 기여했습니다. 원본 코드는 여기에서 찾을 수 있습니다.

리소스

X-CLIP을 시작하는 데 도움이 되는 공식 Hugging Face 및 커뮤니티(🌎로 표시) 리소스 목록입니다.

  • X-CLIP 데모 노트북은 여기에서 찾을 수 있습니다.

여기에 포함할 리소스를 제출하고 싶으시면 Pull Request를 열어 주시면 검토하겠습니다! 기존 리소스와 중복되지 않고 새로운 것을 보여주는 것이 이상적입니다.

XCLIPProcessor

클래스 transformers.XCLIPProcessor

< >

( image_processor = Nonetokenizer = None**kwargs )

매개변수

  • image_processor (image_processor_class) — 이미지 프로세서가 필수 입력값입니다.
  • tokenizer (tokenizer_class) — 토크나이저는 필수 입력값입니다.

XCLIPProcessor를 생성하여 이미지 프로세서와 토크나이저를 단일 프로세서로 래핑합니다.

XCLIPProcessor는 image_processor_class과 tokenizer_class의 모든 기능을 제공합니다. 자세한 내용은 ~image_processor_class와 ~tokenizer_class를 참고하세요.

__call__

< >

( images = Nonetext = Nonevideos = None**kwargs )

XCLIPConfig

class transformers.XCLIPConfig

< >

( 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 = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneprojection_dim: int = 512prompt_layers: int = 2prompt_alpha: float = 0.1prompt_hidden_act: str = 'quick_gelu'prompt_num_attention_heads: int = 8prompt_attention_dropout: float | int = 0.0prompt_projection_dropout: float | int = 0.0logit_scale_init_value: float = 2.6592initializer_factor: float = 1.0 )

매개변수

  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig], 선택) — 텍스트 백본의 config 객체 또는 사전입니다.
  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig], 선택) — 비전 백본의 config 객체 또는 사전입니다.
  • projection_dim (int, 선택 사항, 기본값 512) — 텍스트 및 비전 투영 레이어의 차원입니다.
  • prompt_layers (int, 선택 사항, 기본값 2) — 비디오 전용 프롬프트 생성기에 사용되는 레이어 수입니다.
  • prompt_alpha (float, 선택, 기본값 0.1) — 비디오 전용 프롬프트 생성기에 사용할 Alpha 값입니다.
  • prompt_hidden_act (str 또는 function, 선택 사항, 기본값 "quick_gelu") — 비디오 전용 프롬프트 생성기에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 문자열인 경우, "gelu", "relu", "selu", "gelu_new", "quick_gelu"가 지원됩니다.
  • prompt_num_attention_heads (int, 선택 사항, 기본값 8) — 비디오 전용 프롬프트 생성기의 cross-attention에서 사용할 attention head의 수입니다.
  • prompt_attention_dropout (float, 선택 사항, 기본값 0.0) — 비디오 전용 프롬프트 생성기의 어텐션 레이어에 적용되는 dropout 확률입니다.
  • prompt_projection_dropout (float, 선택 사항, 기본값 0.0) — 비디오 전용 프롬프트 생성기의 투영 레이어에 적용되는 dropout 확률입니다.
  • logit_scale_init_value (float, 선택 사항, 기본값 2.6592) — logit_scale 매개변수의 초기 값입니다.
  • initializer_factor (float, 선택 사항, 기본값 1.0) — 모든 가중치 행렬을 초기화하는 계수입니다(1로 유지해야 하며, 초기화 테스트를 위해 내부적으로 사용됨).

이것은 X ClipModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 X Clip 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 microsoft/xclip-base-patch32와 유사한 구성이 생성됩니다.

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

XCLIPTextConfig

class transformers.XCLIPTextConfig

< >

( 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 = Nonevocab_size: int = 49408hidden_size: int = 512intermediate_size: int = 2048num_hidden_layers: int = 12num_attention_heads: int = 8max_position_embeddings: int = 77hidden_act: str = 'quick_gelu'layer_norm_eps: float = 1e-05attention_dropout: float | int = 0.0initializer_range: float = 0.02initializer_factor: float = 1.0pad_token_id: int | None = 1bos_token_id: int | None = 0eos_token_id: int | list[int] | None = 2 )

매개변수

  • vocab_size (int, 선택 사항, 기본값 49408) — 모델의 어휘 크기입니다. input_ids로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.
  • hidden_size (int, 선택 사항, 기본값 512) — 숨겨진 표현의 차원입니다.
  • intermediate_size (int, 선택 사항, 기본값 2048) — MLP 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 12) — Transformer 디코더의 숨겨진 레이어 수.
  • num_attention_heads (int, 선택 사항, 기본값 8) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • max_position_embeddings (int, 선택 사항, 기본값 77) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.
  • hidden_act (str, 선택 사항, 기본값 quick_gelu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • layer_norm_eps (float, 선택 사항, 기본값 1e-05) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • initializer_factor (float, 선택 사항, 기본값 1.0) — 모든 가중치 행렬을 초기화하는 계수입니다(1로 유지해야 하며, 초기화 테스트를 위해 내부적으로 사용됨).
  • pad_token_id (int, 선택 사항, 기본값 1) — 어휘에서 패딩에 사용되는 토큰 ID입니다.
  • bos_token_id (int, 선택 사항, 기본값 0) — 어휘에서 스트림 시작에 사용되는 토큰 id입니다.
  • eos_token_id (Union[int, list[int]], 선택 사항, 기본값 2) — 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.

이것은 X ClipModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 X Clip 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 microsoft/xclip-base-patch32와 유사한 구성이 생성됩니다.

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

예:

>>> from transformers import XCLIPTextModel, XCLIPTextConfig

>>> # Initializing a XCLIPTextModel with microsoft/xclip-base-patch32 style configuration
>>> configuration = XCLIPTextConfig()

>>> # Initializing a XCLIPTextConfig from the microsoft/xclip-base-patch32 style configuration
>>> model = XCLIPTextModel(configuration)

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

XCLIPVisionConfig

클래스 transformers.XCLIPVisionConfig

< >

( 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 = 768intermediate_size: int = 3072num_hidden_layers: int = 12num_attention_heads: int = 12mit_hidden_size: int = 512mit_intermediate_size: int = 2048mit_num_hidden_layers: int = 1mit_num_attention_heads: int = 8num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 224patch_size: int | list[int] | tuple[int, int] = 32num_frames: int = 8hidden_act: str = 'quick_gelu'layer_norm_eps: float = 1e-05attention_dropout: float | int = 0.0initializer_range: float = 0.02initializer_factor: float = 1.0drop_path_rate: float | int = 0.0 )

매개변수

  • hidden_size (int, 선택 사항, 기본값 768) — 숨겨진 표현의 차원입니다.
  • intermediate_size (int, 선택 사항, 기본값 3072) — MLP 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 12) — Transformer 디코더의 숨겨진 레이어 수.
  • num_attention_heads (int, 선택 사항, 기본값 12) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • mit_hidden_size (int, 선택 사항, 기본값 512) — Multiframe Integration Transformer(MIT) 인코더 레이어의 차원입니다.
  • mit_intermediate_size (int, 선택 사항, 기본값 2048) — Multiframe Integration Transformer(MIT)의 “intermediate”(즉, feed-forward) 레이어의 차원.
  • mit_num_hidden_layers (int, 선택 사항, 기본값 1) — Multiframe Integration Transformer(MIT)의 숨겨진 레이어 수입니다.
  • mit_num_attention_heads (int, 선택 사항, 기본값 8) — Multiframe Integration Transformer(MIT)의 각 attention layer에 사용할 attention head의 수입니다.
  • num_channels (int, 선택 사항, 기본값 3) — 입력 채널의 수입니다.
  • image_size (Union[int, list[int], tuple[int, int]], 선택 사항, 기본값 224) — 각 이미지의 크기(해상도).
  • patch_size (Union[int, list[int], tuple[int, int]], 선택 사항, 기본값 32) — 각 패치의 크기(해상도)입니다.
  • num_frames (int, 선택 사항, 기본값 8) — 각 비디오의 프레임 수입니다.
  • hidden_act (str, 선택 사항, 기본값 quick_gelu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • layer_norm_eps (float, 선택 사항, 기본값 1e-05) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • initializer_factor (float, 선택 사항, 기본값 1.0) — 모든 가중치 행렬을 초기화하는 계수입니다(1로 유지해야 하며, 초기화 테스트를 위해 내부적으로 사용됨).
  • drop_path_rate (Union[float, int], 선택 사항, 기본값 0.0) — 패치 융합에 사용할 드롭 패스 비율입니다.

이것은 X ClipModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 X Clip 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 microsoft/xclip-base-patch32와 유사한 구성이 생성됩니다.

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

예:

>>> from transformers import XCLIPVisionModel, XCLIPVisionConfig

>>> # Initializing a XCLIPVisionModel with microsoft/xclip-base-patch32 style configuration
>>> configuration = XCLIPVisionConfig()

>>> # Initializing a XCLIPVisionModel model from the microsoft/xclip-base-patch32 style configuration
>>> model = XCLIPVisionModel(configuration)

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

XCLIPModel

class transformers.XCLIPModel

< >

( config: XCLIPConfig )

매개변수

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

특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 bare X Clip Model입니다.

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonereturn_loss: bool | None = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → XCLIPOutput or tuple(torch.Tensor)

매개변수

  • input_ids (torch.LongTensor 형상이 (batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은 image_processor_class.__call__를 참조하세요 (processor_class는 이미지 처리에 image_processor_class를 사용합니다).
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • position_ids (torch.LongTensor 의 shape (batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

  • return_loss (bool, 선택) — contrastive loss를 반환할지 여부.
  • interpolate_pos_encoding (bool, 선택 사항, 기본값 False) — 사전 학습된 위치 인코딩을 보간할지 여부입니다.

반환값

XCLIPOutput 또는 tuple(torch.Tensor)

XCLIPOutput 또는 torch.Tensor 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, XCLIPConfig 및 입력에 따라 다양한 요소로 구성됩니다.

XCLIPModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • loss (torch.Tensor, shape (1,), 선택, return_loss가 True일 때 반환됨) — 비디오-텍스트 유사도를 위한 Contrastive loss.
  • logits_per_text (torch.Tensor, shape (text_batch_size, video_batch_size)) — text_embeds와 video_embeds 사이의 스케일된 도트 프로덕트 점수입니다. 이는 텍스트-비디오 유사도 점수를 나타냅니다.
  • text_embeds (torch.Tensor, shape (batch_size, output_dim) — XCLIPTextModel의 pooled output에 projection layer를 적용하여 얻은 텍스트 임베딩입니다.
  • text_model_output (~modeling_outputs.BaseModelOutputWithPooling, 선택) — XCLIPTextModel의 출력입니다.
  • vision_model_output (~modeling_outputs.BaseModelOutputWithPooling, 선택) — XCLIPVisionModel의 출력입니다.
  • logits_per_video (torch.Tensor, shape (video_batch_size, text_batch_size)) — video_embeds와 text_embeds 사이의 스케일된 도트 프로덕트 점수입니다. 이는 비디오-텍스트 유사도 점수를 나타냅니다.
  • video_embeds (torch.Tensor, shape (batch_size, output_dim) — XCLIPVisionModel의 pooled output에 projection layer를 적용하여 얻은 video embeddings입니다.
  • mit_output (~modeling_outputs.BaseModelOutputWithPooling, 선택 사항) — XCLIPMultiframeIntegrationTransformer(MIT)의 출력입니다.

예:

>>> import av
>>> import torch
>>> import numpy as np

>>> from transformers import AutoProcessor, AutoModel
>>> 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)

>>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
>>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = processor(
...     text=["playing sports", "eating spaghetti", "go shopping"],
...     videos=list(video),
...     return_tensors="pt",
...     padding=True,
... )

>>> # forward pass
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> logits_per_video = outputs.logits_per_video  # this is the video-text similarity score
>>> probs = logits_per_video.softmax(dim=1)  # we can take the softmax to get the label probabilities
>>> print(probs)
tensor([[1.9496e-04, 9.9960e-01, 2.0825e-04]])

get_text_features

< >

( input_ids: Tensorattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

매개변수

  • input_ids (torch.Tensor 의 shape (batch_size, sequence_length)) — 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 Padding은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

반환값

BaseModelOutputWithPooling 또는 tuple(torch.Tensor)

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

  • last_hidden_state (torch.Tensor, shape (batch_size, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • pooler_output (torch.Tensor, shape (batch_size, hidden_size)) — 보조 사전 학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 후의 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전 학습 동안 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.

  • hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

  • attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.

예:

>>> import torch
>>> from transformers import AutoTokenizer, AutoModel

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/xclip-base-patch32")
>>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> with torch.inference_mode():
...     text_features = model.get_text_features(**inputs)

get_video_features

< >

( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은 image_processor_class.__call__를 참조하세요. (processor_class는 이미지 처리에 image_processor_class를 사용합니다.)

반환값

BaseModelOutputWithPooling 또는 tuple(torch.Tensor)

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

  • last_hidden_state (torch.Tensor, shape (batch_size, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • pooler_output (torch.Tensor, shape (batch_size, hidden_size)) — 보조 사전 학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 후의 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전 학습 동안 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.

  • hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

  • attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.

예:

>>> import av
>>> import torch
>>> import numpy as np

>>> from transformers import AutoProcessor, AutoModel
>>> 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)

>>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
>>> model = AutoModel.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = processor(videos=list(video), return_tensors="pt")

>>> video_features = model.get_video_features(**inputs)

XCLIPTextModel

클래스 transformers.XCLIPTextModel

< >

( config: XCLIPTextConfig )

매개변수

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

XCLIP의 텍스트 모델로, 상단에 헤드나 투영이 없는 모델입니다.

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

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

forward

< >

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

매개변수

  • input_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

반환값

BaseModelOutputWithPooling 또는 tuple(torch.Tensor)

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

XCLIPTextModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • last_hidden_state (torch.Tensor, shape (batch_size, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • pooler_output (torch.Tensor, shape (batch_size, hidden_size)) — 보조 사전 학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 후의 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전 학습 동안 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.

  • hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

  • attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.

예:

>>> from transformers import AutoTokenizer, XCLIPTextModel

>>> model = XCLIPTextModel.from_pretrained("microsoft/xclip-base-patch32")
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/xclip-base-patch32")

>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled (EOS token) states

XCLIPVisionModel

class transformers.XCLIPVisionModel

< >

( config: XCLIPVisionConfig )

매개변수

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

head나 projection이 없는 XCLIP의 비전 모델입니다.

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor]interpolate_pos_encoding: bool | None = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은 image_processor_class.__call__를 참조하세요 (processor_class는 이미지 처리에 image_processor_class를 사용합니다).
  • interpolate_pos_encoding (bool, 선택 사항, 기본값 False) — 사전 학습된 위치 인코딩을 보간할지 여부입니다.

반환값

BaseModelOutputWithPooling 또는 tuple(torch.Tensor)

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

XCLIPVisionModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • last_hidden_state (torch.Tensor, shape (batch_size, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • pooler_output (torch.Tensor, shape (batch_size, hidden_size)) — 보조 사전 학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 후의 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전 학습 동안 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.

  • hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

  • attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.

예:

>>> import av
>>> import torch
>>> import numpy as np

>>> from transformers import AutoProcessor, XCLIPVisionModel
>>> 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 16 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)

>>> processor = AutoProcessor.from_pretrained("microsoft/xclip-base-patch32")
>>> model = XCLIPVisionModel.from_pretrained("microsoft/xclip-base-patch32")

>>> pixel_values = processor(videos=list(video), return_tensors="pt").pixel_values

>>> batch_size, num_frames, num_channels, height, width = pixel_values.shape
>>> pixel_values = pixel_values.reshape(-1, num_channels, height, width)

>>> outputs = model(pixel_values)
>>> last_hidden_state = outputs.last_hidden_state
Update on GitHub