Transformers documentation
Video Vision Transformer (ViViT)
이 모델은 2021-03-29에 HF papers에 게시되었으며, 2023-07-11에 Hugging Face Transformers에 기여되었습니다.
Video Vision Transformer (ViViT)
개요
Vivit 모델은 Anurag Arnab, Mostafa Dehghani, Georg Heigold, Chen Sun, Mario Lučić, Cordelia Schmid이 ViViT: A Video Vision Transformer에서 제안했습니다. 해당 논문은 영상 이해를 위한 최초의 성공적인 순수 Transformer 기반 모델 세트를 제안합니다.
해당 논문의 초록은 다음과 같습니다:
영상 분류를 위한 순수 Transformer 기반 모델을 제시합니다. 이는 이미지 분류에서 해당 모델이 최근 거둔 성공에 기반합니다. 본 모델은 입력 영상에서 시공간 토큰을 추출한 후, 일련의 Transformer 레이어로 인코딩합니다. 영상에서 발생하는 긴 토큰 시퀀스를 처리하기 위해, 입력의 공간 차원과 시간 차원을 분해하는 여러 가지 효율적인 모델 변형을 제안합니다. Transformer 기반 모델은 대규모 학습 데이터셋이 있을 때만 효과적이라는 것이 알려져 있지만, 학습 중에 모델을 효과적으로 정규화하고 사전 학습된 이미지 모델을 활용하여 상대적으로 작은 데이터셋에서도 학습할 수 있는 방법을 보여줍니다. 철저한 아블레이션 연구를 수행하고, Kinetics 400 및 600, Epic Kitchens, Something-Something v2, Moments in Time을 포함한 여러 영상 분류 벤치마크에서 최첨단(SOTA) 결과를 달성했으며, 심층 3D 합성곱 네트워크 기반의 기존 방법들을 능가했습니다.
이 모델은 jegormeister가 기여했습니다. 원본 코드(JAX로 작성됨)는 여기에서 찾을 수 있습니다.
Scaled Dot Product Attention(SDPA) 사용
PyTorch에는 torch.nn.functional의 일부로 네이티브 scaled dot-product attention(SDPA) 연산자가 포함되어 있습니다. 이 함수는 입력과 사용 중인 하드웨어에 따라 적용할 수 있는 여러 구현 방식을 포함합니다. 자세한 내용은 공식 문서 또는 GPU Inference 페이지를 참고하세요.
구현이 사용 가능한 경우 torch>=2.1.1에서는 기본적으로 SDPA가 사용되지만, from_pretrained()에서 attn_implementation="sdpa"를 설정하여 SDPA 사용을 명시적으로 요청할 수도 있습니다.
from transformers import VivitModel
model = VivitModel.from_pretrained("google/vivit-b-16x2-kinetics400", attn_implementation="sdpa", device_map="auto")
...최고의 속도 향상을 위해 모델은 반정밀(half-precision, 예: torch.float16 또는 torch.bfloat16)로 로드하는 것을 권장합니다.
로컬 벤치마크(A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04)에서 float32와 google/vivit-b-16x2-kinetics400 모델을 사용하여 추론 시 다음과 같은 속도 향상을 확인했습니다.
학습
| num_training_steps | batch_size | cuda | 속도 향상 (%) | Eager 피크 메모리 (MB) | sdpa 피크 메모리 (MB) | 메모리 절약 (%) |
|---|---|---|---|---|---|---|
| 100 | 1 | True | 7.122 | 2575.28 | 5932.54 | 130.364 |
추론
| num_batches | batch_size | cuda | is half | 속도 향상 (%) | Mem eager (MB) | 메모리 BT (MB) | 메모리 절약 (%) |
|---|---|---|---|---|---|---|---|
| 20 | 1 | True | False | 15.422 | 715.807 | 317.079 | 125.75 |
| 20 | 2 | True | False | 17.146 | 1234.75 | 447.175 | 176.122 |
| 20 | 4 | True | False | 18.093 | 2275.82 | 709.864 | 220.6 |
| 20 | 8 | True | False | 19.284 | 4358.19 | 1233.24 | 253.393 |
VivitConfig
클래스 transformers.VivitConfig
< 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 = Noneimage_size: int | list[int] | tuple[int, int] = 224num_frames: int = 32tubelet_size: list[int] | tuple[int, ...] = (2, 16, 16)num_channels: int = 3hidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12intermediate_size: int = 3072hidden_act: str = 'gelu_fast'hidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-06qkv_bias: bool = Truepooler_output_size: int | None = Nonepooler_act: str = 'tanh' )
매개변수
- image_size (
Union[int, list[int], tuple[int, int]], 선택 사항, 기본값224) — 각 이미지의 크기(해상도). - num_frames (
int, 선택 사항, 기본값 32) — 각 비디오의 프레임 수입니다. - tubelet_size (
list[int], 선택 사항, 기본값[2, 16, 16]) — 각 tubelet의 크기(해상도)입니다. - num_channels (
int, 선택 사항, 기본값3) — 입력 채널의 수입니다. - hidden_size (
int, 선택 사항, 기본값768) — 숨겨진 표현의 차원입니다. - num_hidden_layers (
int, 선택 사항, 기본값12) — Transformer 디코더의 숨겨진 레이어 수. - num_attention_heads (
int, 선택 사항, 기본값12) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다. - intermediate_size (
int, 선택 사항, 기본값3072) — MLP 표현의 차원입니다. - hidden_act (
str, 선택 사항, 기본값gelu_fast) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어,"gelu","relu","silu"등이 있습니다. - hidden_dropout_prob (
Union[float, int], 선택 사항, 기본값0.0) — 임베딩, 인코더, 풀러의 모든 완전 연결 계층에 적용되는 드롭아웃 확률입니다. - attention_probs_dropout_prob (
Union[float, int], 선택 사항, 기본값0.0) — Attention 확률에 적용할 dropout 비율입니다. - initializer_range (
float, 선택 사항, 기본값0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다. - layer_norm_eps (
float, 선택 사항, 기본값1e-06) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다. - qkv_bias (
bool, 선택 사항, 기본값True) — 쿼리, 키, 값에 bias를 추가할지 여부. - pooler_output_size (
int, 선택 사항) — pooler 레이어의 차원입니다. None인 경우 기본값은hidden_size입니다. - pooler_act (
str, 선택 사항, 기본값"tanh") — pooler에서 사용할 활성화 함수입니다.
이것은 VivitModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Vivit 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 google/vivit-b-16x2-kinetics400과 유사한 구성이 생성됩니다.
Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.
예:
>>> from transformers import VivitConfig, VivitModel
>>> # Initializing a ViViT google/vivit-b-16x2-kinetics400 style configuration
>>> configuration = VivitConfig()
>>> # Initializing a model (with random weights) from the google/vivit-b-16x2-kinetics400 style configuration
>>> model = VivitModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configVivitImageProcessor
클래스 transformers.VivitImageProcessor
< source >( do_resize: bool = Truesize: dict[str, int] | None = Noneresample: Resampling = <Resampling.BILINEAR: 2>do_center_crop: bool = Truecrop_size: dict[str, int] | None = Nonedo_rescale: bool = Truerescale_factor: int | float = 0.00784313725490196offset: bool = Truedo_normalize: bool = Trueimage_mean: float | list[float] | None = Noneimage_std: float | list[float] | None = None**kwargs )
매개변수
- do_resize (
bool, 선택 사항, 기본값True) — 이미지의 (height, width) 차원을 지정된size로 리사이즈할지 여부입니다.preprocess메서드의do_resize매개변수로 재정의할 수 있습니다. - size (
dict[str, int]선택, 기본값{"shortest_edge" -- 256}): 리사이즈 후 출력 이미지의 크기입니다. 원본 이미지의 종횡비를 유지하면서 이미지의 가장 짧은 변을size["shortest_edge"]로 리사이즈합니다.preprocess메서드의size로 재정의할 수 있습니다. - resample (
PILImageResampling, 선택, 기본값Resampling.BILINEAR) — 이미지 크기를 조정할 때 사용할 리샘플링 필터입니다.preprocess메서드의resample파라미터로 재정의할 수 있습니다. - do_center_crop (
bool, 선택 사항, 기본값True) — 이미지를 지정된crop_size로 중앙 크롭할지 여부입니다.preprocess메서드의do_center_crop파라미터로 재정의할 수 있습니다. - crop_size (
dict[str, int], 선택 사항, 기본값{"height" -- 224, "width": 224}): 중앙 크롭을 적용한 후의 이미지 크기입니다.preprocess메서드의crop_size매개변수로 재정의할 수 있습니다. - do_rescale (
bool, 선택 사항, 기본값True) — 지정된 scalerescale_factor로 이미지를 rescale할지 여부입니다.preprocess메서드의do_rescale파라미터로 재정의할 수 있습니다. - rescale_factor (
int또는float, 선택 사항, 기본값1/127.5) — 이미지를 리스케일할 때 사용할 스케일 팩터를 정의합니다.preprocess메서드의rescale_factor파라미터로 재정의할 수 있습니다. - offset (
bool, 선택 사항, 기본값True) — 이미지를 음의 방향과 양의 방향으로 모두 스케일링할지 여부입니다.preprocess메서드의offset로 재정의할 수 있습니다. - do_normalize (
bool, 선택 사항, 기본값True) — 이미지를 정규화할지 여부입니다.preprocess메서드의do_normalize매개변수로 재정의할 수 있습니다. - image_mean (
float또는list[float], 선택 사항, 기본값은IMAGENET_STANDARD_MEAN) — 이미지를 정규화할 때 사용할 평균입니다. 이는 이미지 채널 수와 길이가 같은 float 또는 float 리스트입니다.preprocess메서드의image_mean매개변수로 재정의할 수 있습니다. - image_std (
float또는list[float], 선택 사항, 기본값IMAGENET_STANDARD_STD) — 이미지를 정규화할 때 사용할 표준 편차입니다. 이는 이미지 채널 수와 길이가 같은 float 또는 float 리스트입니다.preprocess메서드의image_std매개변수로 재정의할 수 있습니다.
Vivit 이미지 프로세서 생성
preprocess
< source >( videos: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]do_resize: bool | None = Nonesize: dict[str, int] | None = Noneresample: PIL.Image.Resampling | None = Nonedo_center_crop: bool | None = Nonecrop_size: dict[str, int] | None = Nonedo_rescale: bool | None = Nonerescale_factor: float | None = Noneoffset: bool | None = Nonedo_normalize: bool | None = Noneimage_mean: float | list[float] | None = Noneimage_std: float | list[float] | None = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = Nonedata_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'>input_data_format: str | transformers.image_utils.ChannelDimension | None = None )
매개변수
- videos (
ImageInput) — 전처리할 비디오 프레임입니다. 픽셀 값이 0에서 255 범위로 주어지는 단일 또는 배치 비디오 프레임을 기대합니다. 픽셀 값이 0과 1 사이인 프레임을 전달하는 경우do_rescale=False로 설정하세요. - do_resize (
bool, 선택 사항, 기본값self.do_resize) — 이미지를 리사이즈할지 여부입니다. - size (
dict[str, int], 선택 사항, 기본값self.size) — 리사이즈를 적용한 후의 이미지 크기입니다. - resample (
PILImageResampling, 선택, 기본값self.resample) — 이미지를 리사이즈할 때 사용할 리샘플링 필터입니다.PILImageResamplingenum 중 하나를 사용할 수 있으며,do_resize가True로 설정된 경우에만 효과가 있습니다. - do_center_crop (
bool, 선택 사항, 기본값self.do_centre_crop) — 이미지를 중앙으로 크롭할지 여부. - crop_size (
dict[str, int], 선택 사항, 기본값self.crop_size) — 중앙 크롭을 적용한 후의 이미지 크기입니다. - do_rescale (
bool, 선택 사항, 기본값self.do_rescale) —offset이True인 경우 이미지 값을[-1 - 1]로, 그렇지 않으면[0, 1]로 재스케일할지 여부. - rescale_factor (
float, 선택, 기본값self.rescale_factor) —do_rescale이True로 설정된 경우 이미지를 재조정(rescale)하는 데 사용할 재조정 계수입니다. - offset (
bool, 선택 사항, 기본값self.offset) — 이미지를 음의 방향과 양의 방향 모두로 스케일링할지 여부. - do_normalize (
bool, 선택 사항, 기본값self.do_normalize) — 이미지를 정규화할지 여부. - image_mean (
float또는list[float], 선택, 기본값self.image_mean) — 이미지 평균값. - image_std (
float또는list[float], 선택, 기본값self.image_std) — 이미지 표준 편차입니다. - return_tensors (
str또는TensorType, 선택 사항) — 반환할 텐서의 유형입니다. 다음 중 하나일 수 있습니다:- Unset:
np.ndarray의 목록을 반환합니다. TensorType.PYTORCH또는'pt':torch.Tensor유형의 배치(batch)를 반환합니다.TensorType.NUMPY또는'np':np.ndarray유형의 배치(batch)를 반환합니다.
- Unset:
- data_format (
ChannelDimension또는str, 선택 사항, 기본값은ChannelDimension.FIRST) — 출력 이미지의 채널 차원 형식입니다. 다음 중 하나를 사용할 수 있습니다:ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지.ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지.- Unset: 입력 이미지의 추론된 채널 차원 형식을 사용합니다.
- input_data_format (
ChannelDimension또는str, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정하지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:"channels_first"또는ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지."channels_last"또는ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지."none"또는ChannelDimension.NONE: (height, width) 형식의 이미지.
이미지 또는 이미지 배치(batch)를 전처리합니다.
VivitVideoProcessor
class transformers.VivitVideoProcessor
< source >( **kwargs: *<class 'transformers.processing_utils.VideosKwargs'> )
매개변수
- do_convert_rgb (
bool, kwargs, 선택 사항, 기본값True) — 이미지를 RGB로 변환할지 여부. - do_resize (
bool, kwargs, 선택 사항, 기본값True) — 이미지를 리사이즈할지 여부. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, 기본값{'shortest_edge' -- 256}): 모델에 입력되는 최대 차원을 설명합니다. - default_to_square (
bool, kwargs, 선택 사항, 기본값False) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, 기본값2) — 이미지 크기를 조정할 때 사용할 리샘플링 필터입니다.PILImageResamplingenum 중 하나를 사용할 수 있습니다.do_resize가True로 설정된 경우에만 효과가 있습니다. - do_rescale (
bool, kwargs, 선택, 기본값True) — 이미지를 다시 스케일링할지 여부. - rescale_factor (
float, kwargs, 선택 사항, 기본값0.00784313725490196) —do_rescale이True로 설정된 경우 이미지를 재조정(rescale)하는 데 사용할 계수입니다. - do_normalize (
bool, kwargs, 선택, 기본값True) — 이미지를 정규화할지 여부. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 선택, 기본값[0.5, 0.5, 0.5]) — 정규화에 사용할 이미지 평균입니다.do_normalize가True로 설정된 경우에만 효과가 있습니다. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 선택, 기본값[0.5, 0.5, 0.5]) — 정규화에 사용할 이미지 표준 편차.do_normalize가True로 설정된 경우에만 효과가 있습니다. - do_center_crop (
bool, kwargs, 선택, 기본값True) — 이미지를 중앙으로 크롭할지 여부. - do_pad (
bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, 기본값{'height' -- 224, 'width': 224}):center_crop을 적용한 후의 출력 이미지 크기입니다. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) —ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정되지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:"channels_first"또는ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지."channels_last"또는ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지."none"또는ChannelDimension.NONE: (height, width) 형식의 이미지.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다. - do_sample_frames (
bool, kwargs, 선택 사항, 기본값False) — 처리 전에 비디오에서 프레임을 샘플링할지, 아니면 비디오 전체를 처리할지를 결정합니다. - video_metadata (
Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None], kwargs) — 총 길이, fps, 총 프레임 수에 대한 정보를 포함하는 비디오의 메타데이터입니다. 비디오에서 프레임을 샘플링하거나 타임스탬프를 계산하는 데 사용됩니다. 비디오를 수동으로 디코딩하여 처리하려는 경우를 제외하고는 메타데이터를 전달하지 마세요. - fps (
Annotated[int | float | None, None], kwargs) —do_sample_frames=True인 경우 초당 샘플링할 대상 프레임 수. - num_frames (
Annotated[int | None, None], kwargs) —do_sample_frames=True일 때 샘플링할 최대 프레임 수. - return_metadata (
bool, kwargs, 선택, 기본값False) — 비디오 메타데이터를 반환할지 여부입니다. 비디오 메타데이터는 비디오 길이, fps, 디코딩 백엔드 등에 대한 정보를 포함하는 객체입니다. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:'pt': PyTorchtorch.Tensor객체를 반환합니다.'np': NumPynp.ndarray객체를 반환합니다.
- **kwargs (VideosKwargs, optional) — 각 모달리티(텍스트, 이미지, 비디오, 오디오)에 대한 추가 처리 옵션입니다. 모델별 매개변수는 위에 나열되어 있으며, 지원되는 인자의 전체 목록은 TypedDict 클래스를 참조하세요.
VivitVideoProcessor 비디오 프로세서를 생성합니다.
preprocess
< source >( 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'> ) → ~image_processing_base.BatchFeature
매개변수
- 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]]]) — 전처리할 비디오입니다. 픽셀 값이 0에서 255 범위로 이루어진 단일 비디오 또는 비디오 배치(batch)를 기대합니다. 픽셀 값이 0에서 1 범위로 이루어진 비디오를 전달하는 경우do_rescale=False로 설정하십시오. - do_convert_rgb (
bool, kwargs, 선택 사항) — 이미지를 RGB로 변환할지 여부입니다. - do_resize (
bool, kwargs, 선택) — 이미지를 리사이즈할지 여부. - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 모델의 최대 입력 차원을 설명합니다. - default_to_square (
bool, kwargs, 선택 사항) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부. - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 이미지를 리사이즈할 경우 사용할 리샘플링 필터입니다. 이는PILImageResamplingenum 중 하나일 수 있습니다.do_resize가True로 설정된 경우에만 효과가 있습니다. - do_rescale (
bool, kwargs, 선택 사항) — 이미지를 다시 스케일링할지 여부입니다. - rescale_factor (
float, kwargs, optional) —do_rescale이True로 설정된 경우 이미지를 리스케일하기 위한 리스케일 팩터입니다. - do_normalize (
bool, kwargs, optional) — 이미지를 정규화할지 여부. - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 평균입니다.do_normalize가True로 설정된 경우에만 효과가 있습니다. - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 선택) — 정규화에 사용할 이미지 표준 편차.do_normalize가True로 설정된 경우에만 효과가 있습니다. - do_center_crop (
bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부. - do_pad (
bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다. - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) —center_crop을 적용한 후 출력 이미지의 크기. - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) —ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다. - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정되지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:"channels_first"또는ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지."channels_last"또는ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지."none"또는ChannelDimension.NONE: (height, width) 형식의 이미지.
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다. - do_sample_frames (
bool, kwargs, 선택) — 처리 전에 비디오에서 프레임을 샘플링할지, 아니면 비디오 전체를 처리할지 여부를 지정합니다. - video_metadata (
Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None], kwargs) — 총 길이, fps, 총 프레임 수에 대한 정보를 포함하는 비디오의 메타데이터입니다. 비디오에서 프레임을 샘플링하거나 타임스탬프를 계산하는 데 사용됩니다. 비디오를 수동으로 디코딩하여 처리하려는 경우를 제외하고는 메타데이터를 전달하지 마세요. - fps (
Annotated[int | float | None, None], kwargs) —do_sample_frames=True인 경우 초당 샘플링할 대상 프레임 수. - num_frames (
Annotated[int | None, None], kwargs) —do_sample_frames=True일 때 샘플링할 최대 프레임 수. - return_metadata (
bool, kwargs, 선택) — 비디오 메타데이터를 반환할지 여부를 지정합니다. 비디오 메타데이터는 비디오 길이, fps, 디코딩 백엔드 등에 대한 정보를 포함하는 객체입니다. - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) —'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
반환값
~image_processing_base.BatchFeature
- data (
dict) — call 메서드가 반환하는 리스트/배열/텐서 딕셔너리(‘pixel_values’ 등). - tensor_type (
Union[None, str, TensorType], 선택 사항) — 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type를 지정할 수 있습니다.
VivitModel
class transformers.VivitModel
< source >( config: VivitConfigadd_pooling_layer: bool = True )
매개변수
- config (VivitConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
- add_pooling_layer (
bool, 선택 사항, 기본값True) — pooling layer를 추가할지 여부
특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 기본 Vivit Model입니다.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool = Falseattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 VivitImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 VivitImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 VivitImageProcessor를 사용합니다). - interpolate_pos_encoding (
bool, 선택 사항, 기본값False) — 사전 학습된 위치 인코딩을 보간할지 여부입니다. - attention_mask (
torch.Tensor형상이(batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요?[0, 1]:- 마스크되지 않은 토큰에 대해 1
- 마스크된 토큰에 대해 0
반환값
BaseModelOutputWithPooling 또는 tuple(torch.Tensor)
torch.Tensor의 튜플 또는 BaseModelOutputWithPooling (return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(VivitConfig)과 입력에 따라 다양한 요소를 포함합니다.
VivitModel의 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 numpy as np
>>> from transformers import VivitImageProcessor, VivitModel
>>> 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 32 frames
>>> indices = sample_frame_indices(clip_len=32, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container=container, indices=indices)
>>> image_processor = VivitImageProcessor.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> model = VivitModel.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> # 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, 3137, 768]VivitForVideoClassification
class transformers.VivitForVideoClassification
< source >( config: VivitConfig )
매개변수
- config (VivitConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
ViViT Transformer 모델로, 최종 hidden state의 [CLS] 토큰 위에 linear layer를 배치한 video classification head를 포함합니다. 예를 들어 Kinetics-400에 사용됩니다.
모델의 forward에서
interpolate_pos_encoding을True로 설정하면, 학습에 사용된 해상도보다 높은 해상도의 이미지로 ViT를 fine-tune할 수 있습니다. 이렇게 하면 사전 학습된 position embeddings이 더 높은 해상도에 맞게 보간됩니다.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ImageClassifierOutput or tuple(torch.Tensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 VivitImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 VivitImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 VivitImageProcessor를 사용합니다). - labels (
torch.LongTensor, shape(batch_size,), 선택 사항) — 이미지 분류/회귀 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는[0, ..., config.num_labels - 1]범위에 있어야 합니다.config.num_labels == 1인 경우 회귀 손실(평균 제곱 오차)이 계산되고,config.num_labels > 1인 경우 분류 손실(교차 엔트로피)이 계산됩니다. - interpolate_pos_encoding (
bool, 선택 사항, 기본값False) — 사전 학습된 위치 인코딩을 보간할지 여부입니다.
반환값
ImageClassifierOutput 또는 tuple(torch.Tensor)
torch.Tensor의 튜플 또는 ImageClassifierOutput입니다. return_dict=False가 전달되거나 config.return_dict=False인 경우, 구성(VivitConfig)과 입력에 따라 다양한 요소를 포함합니다.
VivitForVideoClassification의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
loss (
torch.Tensor, shape(1,), 선택 사항,labels이 제공될 때 반환됨) — 분류 (또는 config.num_labels==1인 경우 회귀) 손실.logits (
torch.Tensor, shape(batch_size, config.num_labels)) — SoftMax 적용 전 분류(또는 config.num_labels==1인 경우 회귀) 점수.hidden_states (
tuple(torch.Tensor), 선택 사항,output_hidden_states=True가 전달되었거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩의 출력에 대한 것 1개 + 각 단계의 출력에 대한 것 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다. 각 단계의 출력에서 모델의 히든 스테이트(피처 맵이라고도 함).attentions (
tuple(torch.Tensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.Tensor의 튜플로, 모양은(batch_size, num_heads, patch_size, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
예:
>>> import av
>>> import numpy as np
>>> import torch
>>> from transformers import VivitImageProcessor, VivitForVideoClassification
>>> 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 32 frames
>>> indices = sample_frame_indices(clip_len=32, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
>>> video = read_video_pyav(container=container, indices=indices)
>>> image_processor = VivitImageProcessor.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> model = VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics400")
>>> 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])
LABEL_116