Transformers documentation
Swin Transformer V2
이 모델은 2021-11-18에 HF papers에 게시되었으며, 2022-07-27에 Hugging Face Transformers에 기여되었습니다.
Swin Transformer V2
Swin Transformer V2는 비전 모델을 수십억 개 파라미터 규모로 확장하는 데 초점을 맞춘 3B 파라미터 모델입니다. 학습 안정성을 높이기 위해 residual-post-norm과 cosine attention을 결합한 기법, 사전 학습과 미세 조정 간 다양한 이미지 해상도를 더 잘 처리하기 위한 log-spaced continuous position bias, 그리고 대량의 라벨링 데이터 필요성을 줄이는 새로운 사전 학습 방법(SimMIM)을 도입합니다. 이러한 개선 사항 덕분에 고해상도 이미지를 처리할 수 있는 매우 큰 모델(최대 30억 개 파라미터)을 효율적으로 학습할 수 있습니다.
Microsoft 조직에서 공식 Swin Transformer V2 체크포인트를 찾을 수 있습니다.
우측 사이드바의 Swin Transformer V2 모델에 클릭하여 Swin Transformer V2를 비전 작업에 적용하는 방법에 대한 추가 예제를 확인하세요.
from transformers import pipeline
pipeline = pipeline(
task="image-classification",
model="microsoft/swinv2-tiny-patch4-window8-256",
device=0
)
pipeline("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")import requests
import torch
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForImageClassification
image_processor = AutoImageProcessor.from_pretrained(
"microsoft/swinv2-tiny-patch4-window8-256",
)
model = AutoModelForImageClassification.from_pretrained(
"microsoft/swinv2-tiny-patch4-window8-256",
device_map="auto"
)
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.no_grad():
logits = model(**inputs).logits
predicted_class_id = logits.argmax(dim=-1).item()
predicted_class_label = model.config.id2label[predicted_class_id]
print(f"The predicted class label is: {predicted_class_label}")The input is a single word "Notes". 참고
- Swin Transformer V2는
32로 나누어 떨어지는 모든 입력 높이와 너비에 대해 입력을 패딩할 수 있습니다. - Swin Transformer V2는 backbone으로 사용할 수 있습니다.
output_hidden_states = True인 경우hidden_states와reshaped_hidden_states를 모두 출력합니다.reshaped_hidden_states의 shape은(batch_size, sequence_length, num_channels)이 아니라(batch, num_channels, height, width)입니다.
Swinv2Config
class transformers.Swinv2Config
< 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] = 224patch_size: int | list[int] | tuple[int, int] = 4num_channels: int = 3embed_dim: int = 96depths: list[int] | tuple[int, ...] = (2, 2, 6, 2)num_heads: list[int] | tuple[int, ...] = (3, 6, 12, 24)window_size: int = 7pretrained_window_sizes: list[int] | tuple[int, ...] = (0, 0, 0, 0)mlp_ratio: float = 4.0qkv_bias: bool = Truehidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0drop_path_rate: float | int = 0.1hidden_act: str = 'gelu'use_absolute_embeddings: bool = Falseinitializer_range: float = 0.02layer_norm_eps: float = 1e-05encoder_stride: int = 32_out_features: list[str] | None = None_out_indices: list[int] | None = None )
매개변수
- image_size (
Union[int, list[int], tuple[int, int]], 선택 사항, 기본값224) — 각 이미지의 크기(해상도). - patch_size (
Union[int, list[int], tuple[int, int]], 선택 사항, 기본값4) — 각 패치의 크기(해상도)입니다. - num_channels (
int, 선택 사항, 기본값3) — 입력 채널의 수입니다. - embed_dim (
int, 선택 사항, 기본값96) — 임베딩 및 숨겨진 상태의 차원입니다. - depths (
Union[list[int], tuple[int, ...]], 선택 사항, 기본값(2, 2, 6, 2)) — Transformer의 각 레이어 깊이. - num_heads (
Union[list[int], tuple[int, ...]], 선택 사항, 기본값(3, 6, 12, 24)) — Transformer decoder의 각 attention layer에 사용할 attention head의 수. - window_size (
int, 선택 사항, 기본값 7) — 윈도우의 크기. - pretrained_window_sizes (
list(int), 선택 사항, 기본값[0, 0, 0, 0]) — 사전 학습 시 사용되는 윈도우 크기입니다. - mlp_ratio (
float, 선택 사항, 기본값4.0) — 임베딩 차원에 대한 MLP 숨겨진 차원의 비율입니다. - qkv_bias (
bool, 선택 사항, 기본값True) — 쿼리, 키, 값에 bias를 추가할지 여부. - hidden_dropout_prob (
Union[float, int], 선택 사항, 기본값0.0) — 임베딩, 인코더, 풀러의 모든 완전 연결 계층에 적용되는 드롭아웃 확률입니다. - attention_probs_dropout_prob (
Union[float, int], 선택 사항, 기본값0.0) — Attention 확률에 적용할 dropout 비율입니다. - drop_path_rate (
Union[float, int], 선택 사항, 기본값0.1) — 패치 융합에 사용할 드롭 패스 비율입니다. - hidden_act (
str, 선택 사항, 기본값gelu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어,"gelu","relu","silu"등이 있습니다. - use_absolute_embeddings (
bool, 선택 사항, 기본값False) — 절대 위치 임베딩을 사용할지 여부입니다. - initializer_range (
float, 선택 사항, 기본값0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다. - layer_norm_eps (
float, 선택 사항, 기본값1e-05) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다. - encoder_stride (
int, 선택 사항, 기본값 32) — masked image modeling에서 decoder head의 공간 해상도를 높이는 배율입니다.
이것은 Swinv2Model의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Swinv2 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 microsoft/swinv2-tiny-patch4-window8-256과 유사한 설정이 생성됩니다.
Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.
예:
>>> from transformers import Swinv2Config, Swinv2Model
>>> # Initializing a Swinv2 microsoft/swinv2-tiny-patch4-window8-256 style configuration
>>> configuration = Swinv2Config()
>>> # Initializing a model (with random weights) from the microsoft/swinv2-tiny-patch4-window8-256 style configuration
>>> model = Swinv2Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configSwinv2Model
class transformers.Swinv2Model
< source >( config: Swinv2Configadd_pooling_layer = Trueuse_mask_token = False )
매개변수
- config (Swinv2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
- add_pooling_layer (
bool, 선택 사항, 기본값True) — pooling layer를 적용할지 여부. - use_mask_token (
bool, 선택 사항, 기본값False) — 임베딩 레이어에서 mask token을 생성하고 적용할지 여부.
특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 기본 Swinv2 Model입니다.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonebool_masked_pos: typing.Optional[torch.BoolTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Noneinterpolate_pos_encoding: bool = Falsereturn_dict: bool | None = None**kwargs ) → Swinv2ModelOutput or tuple(torch.Tensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 ViTImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 ViTImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 ViTImageProcessor를 사용합니다). - bool_masked_pos (
torch.BoolTensor, shape(batch_size, num_patches), 선택 사항) — Boolean masked positions. 어떤 patch가 mask된 상태(1)인지, 아닌 상태(0)인지를 나타냅니다. - output_attentions (
bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의attentions항목을 참조하세요. - output_hidden_states (
bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중hidden_states항목을 참고하세요. - interpolate_pos_encoding (
bool, 선택 사항, 기본값False) — 사전 학습된 위치 인코딩을 보간할지 여부입니다. - return_dict (
bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.
반환값
Swinv2ModelOutput 또는 tuple(torch.Tensor)
Swinv2ModelOutput 또는 torch.Tensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(Swinv2Config)과 입력에 따라 다양한 요소를 포함합니다.
Swinv2Model의 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), 선택 사항,add_pooling_layer=True가 전달될 때 반환됨) — 마지막 레이어 hidden-state의 평균 풀링.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 가중치.
reshaped_hidden_states (
tuple(torch.Tensor), 선택 사항,output_hidden_states=True가 전달되거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(임베딩 출력 1개 + 각 단계의 출력 1개)로, shape는(batch_size, hidden_size, height, width)입니다.각 레이어의 출력에서 모델의 Hidden-states와 공간 차원을 포함하도록 재구성된 초기 임베딩 출력을 더한 값.
Swinv2ForMaskedImageModeling
클래스 transformers.Swinv2ForMaskedImageModeling
< source >( config: Swinv2Config )
매개변수
- config (Swinv2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
SimMIM에서 제안한 바와 같이, 마스크 이미지 모델링을 위해 상단에 디코더가 있는 Swinv2 모델
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonebool_masked_pos: typing.Optional[torch.BoolTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Noneinterpolate_pos_encoding: bool = Falsereturn_dict: bool | None = None**kwargs ) → Swinv2MaskedImageModelingOutput or tuple(torch.Tensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 ViTImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 ViTImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 ViTImageProcessor를 사용합니다). - bool_masked_pos (
torch.BoolTensor, shape(batch_size, num_patches)) — Boolean masked positions. 어떤 patch가 mask된 것(1)이고 어떤 patch가 mask되지 않은 것(0)인지를 나타냅니다. - output_attentions (
bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의attentions항목을 참조하세요. - output_hidden_states (
bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중hidden_states항목을 참고하세요. - interpolate_pos_encoding (
bool, 선택 사항, 기본값False) — 사전 학습된 위치 인코딩을 보간할지 여부입니다. - return_dict (
bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.
반환값
Swinv2MaskedImageModelingOutput 또는 tuple(torch.Tensor)
Swinv2MaskedImageModelingOutput 또는 torch.Tensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(Swinv2Config)과 입력에 따라 다양한 요소를 포함합니다.
Swinv2ForMaskedImageModeling의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
loss (
torch.Tensor, shape(1,), 선택 사항,bool_masked_pos가 제공될 때 반환됨) — Masked image modeling (MLM) 손실.reconstruction (
torch.Tensor, shape(batch_size, num_channels, height, width)) — 재구성된 픽셀 값.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 가중치.
reshaped_hidden_states (
tuple(torch.Tensor), 선택 사항,output_hidden_states=True가 전달되거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(임베딩 출력 1개 + 각 단계의 출력 1개)로, shape는(batch_size, hidden_size, height, width)입니다.각 레이어의 출력에서 모델의 Hidden-states와 공간 차원을 포함하도록 재구성된 초기 임베딩 출력을 더한 값.
예:
>>> from transformers import AutoImageProcessor, Swinv2ForMaskedImageModeling
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> 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("microsoft/swinv2-tiny-patch4-window8-256")
>>> model = Swinv2ForMaskedImageModeling.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
>>> # create random boolean mask of shape (batch_size, num_patches)
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
>>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
>>> list(reconstructed_pixel_values.shape)
[1, 3, 256, 256]Swinv2ForImageClassification
class transformers.Swinv2ForImageClassification
< source >( config: Swinv2Config )
매개변수
- config (Swinv2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
Swinv2 모델은 최종 hidden state의 [CLS] 토큰 위에 선형 레이어를 배치한 이미지 분류 헤드를 포함하며, 예로 ImageNet에 사용됩니다.
모델의 forward에서
interpolate_pos_encoding을True로 설정하면, SwinV2를 학습에 사용된 것보다 더 높은 해상도의 이미지로 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] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Noneinterpolate_pos_encoding: bool = Falsereturn_dict: bool | None = None**kwargs ) → Swinv2ImageClassifierOutput or tuple(torch.Tensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 ViTImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 ViTImageProcessor.call()를 참조하세요 (processor_class는 이미지 처리에 ViTImageProcessor를 사용합니다). - labels (
torch.LongTensor, shape(batch_size,), 선택 사항) — 이미지 분류/회귀 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는[0, ..., config.num_labels - 1]범위에 있어야 합니다.config.num_labels == 1인 경우 회귀 손실(평균 제곱 오차)이 계산되고,config.num_labels > 1인 경우 분류 손실(교차 엔트로피)이 계산됩니다. - output_attentions (
bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의attentions항목을 참조하세요. - output_hidden_states (
bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중hidden_states항목을 참고하세요. - interpolate_pos_encoding (
bool, 선택 사항, 기본값False) — 사전 학습된 위치 인코딩을 보간할지 여부입니다. - return_dict (
bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.
반환값
Swinv2ImageClassifierOutput 또는 tuple(torch.Tensor)
Swinv2ImageClassifierOutput 또는 torch.Tensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(Swinv2Config)과 입력에 따라 다양한 요소를 포함합니다.
Swinv2ForImageClassification의 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)입니다.각 레이어의 출력에서 모델의 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 가중치.
reshaped_hidden_states (
tuple(torch.Tensor), 선택 사항,output_hidden_states=True가 전달되거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(임베딩 출력 1개 + 각 단계의 출력 1개)로, shape는(batch_size, hidden_size, height, width)입니다.각 레이어의 출력에서 모델의 Hidden-states와 공간 차원을 포함하도록 재구성된 초기 임베딩 출력을 더한 값.
예:
>>> from transformers import AutoImageProcessor, Swinv2ForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")
>>> model = Swinv2ForImageClassification.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")
>>> 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])
...