Transformers documentation

MobileViTV2

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

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

MobileViTV2

개요

MobileViTV2 모델은 Sachin Mehta와 Mohammad Rastegari가 Separable Self-attention for Mobile Vision Transformers에서 제안했습니다.

MobileViTV2는 MobileViT의 두 번째 버전으로, MobileViT의 multi-headed self-attention을 separable self-attention으로 대체하여 구성되었습니다.

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

Mobile vision transformers(MobileViT)는 분류 및 감지를 포함한 여러 모바일 비전 작업에서 최첨단 성능을 달성할 수 있습니다. 이러한 모델은 매개변수가 적지만, 합성곱 신경망 기반 모델에 비해 지연 시간이 높습니다. MobileViT의 주요 효율성 병목은 transformer의 multi-headed self-attention(MHA)으로, 토큰(또는 패치) 수 k에 대해 O(k2)의 시간 복잡도를 요구합니다. 또한 MHA는 self-attention을 계산하기 위해 비용이 높은 연산(예: 배치 단위 행렬 곱셈)을 필요로 하여, 리소스가 제한된 장치에서 지연 시간에 영향을 미칩니다. 이 논문은 선형 복잡도, 즉 O(k)를 갖는 분리 가능한 self-attention 방법을 소개합니다. 제안된 방법의 단순하면서도 효과적인 특징은 self-attention을 계산할 때 요소별 연산을 사용한다는 점으로, 이는 리소스가 제한된 장치에 적합한 선택입니다. 개선된 모델인 MobileViTV2는 ImageNet 객체 분류와 MS-COCO 객체 감지를 포함한 여러 모바일 비전 작업에서 최첨단 성능을 보입니다. 약 300만 개의 매개변수를 가진 MobileViTV2는 ImageNet 데이터셋에서 75.6%의 top-1 정확도를 달성하여, 모바일 장치에서 3.2배 더 빠르게 실행되면서도 MobileViT보다 약 1% 높은 성능을 보입니다.

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

사용 팁

  • MobileViTV2는 Transformer 모델보다는 CNN에 더 가깝습니다. 시퀀스 데이터가 아니라 이미지 배치에 적용됩니다. ViT와 달리 임베딩이 없습니다. 백본 모델은 특징 맵을 출력합니다.
  • MobileViTImageProcessor를 사용하여 모델에 사용할 이미지를 준비할 수 있습니다. 직접 전처리(preprocessing)를 수행하는 경우, 사전 학습된 체크포인트는 이미지가 BGR 픽셀 순서(RGB가 아님)로 제공되기를 기대한다는 점에 유의하세요.
  • 사용 가능한 이미지 분류 체크포인트는 ImageNet-1k(ILSVRC 2012라고도 하며, 130만 개의 이미지와 1,000개의 클래스로 구성된 데이터셋)에서 사전 학습되었습니다.
  • 분할 모델은 DeepLabV3 헤드를 사용합니다. 사용 가능한 의미론적 분할 체크포인트는 PASCAL VOC로 사전 학습되었습니다.

MobileViTV2Config

클래스 transformers.MobileViTV2Config

< >

( 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 = Nonenum_channels: int = 3image_size: int | list[int] | tuple[int, int] = 256patch_size: int | list[int] | tuple[int, int] = 2expand_ratio: float = 2.0hidden_act: str = 'swish'conv_kernel_size: int = 3output_stride: int = 32classifier_dropout_prob: float | int = 0.1initializer_range: float = 0.02layer_norm_eps: float = 1e-05aspp_out_channels: int = 512atrous_rates: list[int] | tuple[int, ...] = (6, 12, 18)aspp_dropout_prob: float | int = 0.1semantic_loss_ignore_index: int = 255n_attn_blocks: list[int] | tuple[int, ...] = (2, 4, 3)base_attn_unit_dims: list[int] | tuple[int, ...] = (128, 192, 256)width_multiplier: float | int = 1.0ffn_multiplier: int = 2attn_dropout: float | int = 0.0ffn_dropout: float | int = 0.0 )

매개변수

  • num_channels (int, 선택 사항, 기본값 3) — 입력 채널의 수입니다.
  • image_size (Union[int, list[int], tuple[int, int]], 선택, 기본값 256) — 각 이미지의 크기(해상도).
  • patch_size (Union[int, list[int], tuple[int, int]], 선택 사항, 기본값 2) — 각 패치의 크기(해상도)입니다.
  • expand_ratio (float, 선택 사항, 기본값 2.0) — 확장 비율을 설정하여 확장 출력 차원을 지정합니다
  • hidden_act (str, 선택 사항, 기본값 swish) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열). 예를 들어 "gelu", "relu", "silu" 등이 있습니다.
  • conv_kernel_size (int, 선택 사항, 기본값 3) — 합성곱 커널의 크기입니다.
  • output_stride (int, 선택 사항, 기본값 32) — 입력 및 출력 feature map의 공간 해상도 비율입니다.
  • classifier_dropout_prob (Union[float, int], 선택 사항, 기본값 0.1) — classifier의 dropout 비율입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • layer_norm_eps (float, 선택 사항, 기본값 1e-05) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.
  • aspp_out_channels (int, 선택 사항, 기본값 512) — 의미 분할을 위한 ASPP 레이어에서 사용되는 출력 채널 수.
  • atrous_rates (list[int], 선택 사항, 기본값 [6, 12, 18]) — 의미 분할을 위한 ASPP 레이어에서 사용되는 dilation(atrous) 계수입니다.
  • aspp_dropout_prob (float, 선택 사항, 기본값 0.1) — 의미 분할을 위한 ASPP 레이어의 dropout 비율입니다.
  • semantic_loss_ignore_index (int, 선택 사항, 기본값 255) — 시맨틱 세그멘테이션 모델의 손실 함수에서 무시되는 인덱스입니다.
  • n_attn_blocks (list[int], 선택 사항, 기본값 [2, 4, 3]) — 각 MobileViTV2Layer의 attention block 수
  • base_attn_unit_dims (list[int], 선택 사항, 기본값 [128, 192, 256]) — 각 MobileViTV2Layer의 attention 블록 차원 기본 배율
  • width_multiplier (float, 선택 사항, 기본값 1.0) — MobileViTV2의 폭 배율입니다.
  • ffn_multiplier (int, 선택 사항, 기본값 2) — MobileViTV2의 FFN 배율입니다.
  • attn_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • ffn_dropout (float, 선택 사항, 기본값 0.0) — FFN 레이어 사이의 dropout 비율입니다.

이것은 MobileViTV2Model의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Mobilevitv2 모델을 초기화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 초기화하면 apple/mobilevitv2-1.0의 설정과 유사한 설정이 생성됩니다.

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

예:

>>> from transformers import MobileViTV2Config, MobileViTV2Model

>>> # Initializing a mobilevitv2-small style configuration
>>> configuration = MobileViTV2Config()

>>> # Initializing a model from the mobilevitv2-small style configuration
>>> model = MobileViTV2Model(configuration)

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

MobileViTV2Model

클래스 transformers.MobileViTV2Model

< >

( config: MobileViTV2Configexpand_output: bool = True )

매개변수

  • config (MobileViTV2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
  • expand_output (bool, 선택 사항, 기본값 True) — 모델의 출력을 확장할지 여부입니다. True인 경우, 모델은 hidden states 외에도 pooled features를 출력합니다. False인 경우, hidden states만 반환됩니다.

특정 헤드가 위에 없는 맨 Mobilevitv2 모델로, 원시 hidden-states를 출력합니다.

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BaseModelOutputWithPoolingAndNoAttention or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 MobileViTImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 MobileViTImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 MobileViTImageProcessor를 사용합니다).
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

BaseModelOutputWithPoolingAndNoAttention 또는 tuple(torch.Tensor)

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

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

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

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

  • pooler_output (torch.Tensor, shape (batch_size, hidden_size)) — 공간 차원에 대해 풀링 연산을 수행한 후의 마지막 레이어 hidden-state입니다.

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

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

예:

MobileViTV2ForImageClassification

class transformers.MobileViTV2ForImageClassification

< >

( config: MobileViTV2Config )

매개변수

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

MobileViTV2 모델은 풀링된 특징 위에 선형 레이어를 배치한 이미지 분류 헤드를 포함하며, 예를 들어 ImageNet에 사용됩니다.

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Nonelabels: typing.Optional[torch.Tensor] = Nonereturn_dict: bool | None = None**kwargs ) → ImageClassifierOutputWithNoAttention or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 MobileViTImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 MobileViTImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 MobileViTImageProcessor를 사용합니다).
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • labels (torch.LongTensor, shape (batch_size,), 선택 사항) — 이미지 분류/회귀 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [0, ..., config.num_labels - 1] 범위에 있어야 합니다. config.num_labels == 1인 경우 회귀 손실(평균 제곱 오차)이 계산되고, config.num_labels > 1인 경우 분류 손실(교차 엔트로피)이 계산됩니다.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

ImageClassifierOutputWithNoAttention 또는 tuple(torch.Tensor)

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

MobileViTV2ForImageClassification의 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, num_channels, height, width)입니다. 각 단계의 출력에서 모델의 히든 스테이트(피처 맵이라고도 함).

예:

>>> from transformers import AutoImageProcessor, MobileViTV2ForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("apple/mobilevitv2-1.0")
>>> model = MobileViTV2ForImageClassification.from_pretrained("apple/mobilevitv2-1.0")

>>> inputs = image_processor(image, return_tensors="pt")

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

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...

MobileViTV2ForSemanticSegmentation

class transformers.MobileViTV2ForSemanticSegmentation

< >

( config: MobileViTV2Config )

매개변수

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

Pascal VOC과 같은 작업에 사용할 수 있도록 시맨틱 세그멘테이션 헤드가 위에 연결된 MobileViTV2 모델

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → SemanticSegmenterOutput or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 MobileViTImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 MobileViTImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 MobileViTImageProcessor를 사용합니다).
  • labels (torch.LongTensor, shape (batch_size, height, width), 선택 사항) — 손실 계산에 사용되는 ground truth semantic segmentation map입니다. 인덱스는 [0, ..., config.num_labels - 1] 범위에 있어야 합니다. config.num_labels > 1인 경우, 분류 손실(Cross-Entropy)이 계산됩니다.
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

SemanticSegmenterOutput 또는 tuple(torch.Tensor)

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

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

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

  • loss (torch.Tensor, shape (1,), 선택 사항, labels이 제공될 때 반환됨) — 분류 (또는 config.num_labels==1인 경우 회귀) 손실.

  • logits (torch.Tensor, shape (batch_size, config.num_labels, logits_height, logits_width)) — 각 픽셀에 대한 분류 점수.

    pixel_values로 전달된 입력과 반환되는 logits의 크기가 항상 동일하지는 않습니다. 이는 사용자가 후처리 단계에서 logits를 원본 이미지 크기로 리사이즈할 때 두 번의 보간을 수행하여 품질이 저하되는 것을 방지하기 위한 것입니다. 따라서 logits의 shape을 항상 확인하고 필요에 따라 리사이즈해야 합니다.

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

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

  • 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 가중치.

예:

>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch
>>> from PIL import Image
>>> from transformers import AutoImageProcessor, MobileViTV2ForSemanticSegmentation

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> image_processor = AutoImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")
>>> model = MobileViTV2ForSemanticSegmentation.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")

>>> inputs = image_processor(images=image, return_tensors="pt")

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

>>> # logits are of shape (batch_size, num_labels, height, width)
>>> logits = outputs.logits
Update on GitHub