Buckets:
Swin Transformer
Swin Transformer is a hierarchical vision transformer. Images are processed in patches and windowed self-attention is used to capture local information. These windows are shifted across the image to allow for cross-window connections, capturing global information more efficiently. This hierarchical approach with shifted windows allows the Swin Transformer to process images effectively at different scales and achieve linear computational complexity relative to image size, making it a versatile backbone for various vision tasks like image classification and object detection.
You can find all official Swin Transformer checkpoints under the Microsoft organization.
Click on the Swin Transformer models in the right sidebar for more examples of how to apply Swin Transformer to different image tasks.
The example below demonstrates how to classify an image with Pipeline or the AutoModel class.
from transformers import pipeline
pipeline = pipeline(
task="image-classification",
model="microsoft/swin-tiny-patch4-window7-224",
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/swin-tiny-patch4-window7-224",
use_fast=True,
)
model = AutoModelForImageClassification.from_pretrained(
"microsoft/swin-tiny-patch4-window7-224",
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()
class_labels = model.config.id2label
predicted_class_label = class_labels[predicted_class_id]
print(f"The predicted class label is: {predicted_class_label}")
Notes
- Swin can pad the inputs for any input height and width divisible by
32. - Swin can be used as a backbone. When
output_hidden_states = True, it outputs bothhidden_statesandreshaped_hidden_states. Thereshaped_hidden_stateshave a shape of(batch, num_channels, height, width)rather than(batch_size, sequence_length, num_channels).
SwinConfig[[transformers.SwinConfig]]
transformers.SwinConfig[[transformers.SwinConfig]]
transformers.SwinConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, image_size: int | list[int] | tuple[int, int] = 224, patch_size: int | list[int] | tuple[int, int] = 4, num_channels: int = 3, embed_dim: int = 96, depths: list[int] | tuple[int, ...] = (2, 2, 6, 2), num_heads: list[int] | tuple[int, ...] = (3, 6, 12, 24), window_size: int = 7, mlp_ratio: float | int = 4.0, qkv_bias: bool = True, hidden_dropout_prob: float | int = 0.0, attention_probs_dropout_prob: float | int = 0.0, drop_path_rate: float | int = 0.1, hidden_act: str = 'gelu', use_absolute_embeddings: bool = False, initializer_range: float = 0.02, layer_norm_eps: float = 1e-05, encoder_stride: int = 32, _out_features: list[str] | None = None, _out_indices: list[int] | None = None)
Parameters:
image_size (Union[int, list[int], tuple[int, int]], optional, defaults to 224) : The size (resolution) of each image.
patch_size (Union[int, list[int], tuple[int, int]], optional, defaults to 4) : The size (resolution) of each patch.
num_channels (int, optional, defaults to 3) : The number of input channels.
embed_dim (int, optional, defaults to 96) : Dimensionality of the embeddings and hidden states.
depths (list(int), optional, defaults to [2, 2, 6, 2]) : Depth of each layer in the Transformer encoder.
num_heads (list(int), optional, defaults to [3, 6, 12, 24]) : Number of attention heads in each layer of the Transformer encoder.
window_size (int, optional, defaults to 7) : Size of windows.
mlp_ratio (Union[float, int], optional, defaults to 4.0) : Ratio of the MLP hidden dim to the embedding dim.
qkv_bias (bool, optional, defaults to True) : Whether to add a bias to the queries, keys and values.
hidden_dropout_prob (Union[float, int], optional, defaults to 0.0) : The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (Union[float, int], optional, defaults to 0.0) : The dropout ratio for the attention probabilities.
drop_path_rate (Union[float, int], optional, defaults to 0.1) : Drop path rate for the patch fusion.
hidden_act (str, optional, defaults to gelu) : The non-linear activation function (function or string) in the decoder. For example, "gelu", "relu", "silu", etc.
use_absolute_embeddings (bool, optional, defaults to False) : Whether to use absolute position embeddings.
initializer_range (float, optional, defaults to 0.02) : The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (float, optional, defaults to 1e-05) : The epsilon used by the layer normalization layers.
encoder_stride (int, optional, defaults to 32) : Factor to increase the spatial resolution by in the decoder head for masked image modeling.
This is the configuration class to store the configuration of a SwinModel. It is used to instantiate a Swin model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the microsoft/swin-tiny-patch4-window7-224
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Example:
>>> from transformers import SwinConfig, SwinModel
>>> # Initializing a Swin microsoft/swin-tiny-patch4-window7-224 style configuration
>>> configuration = SwinConfig()
>>> # Initializing a model (with random weights) from the microsoft/swin-tiny-patch4-window7-224 style configuration
>>> model = SwinModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
SwinModel[[transformers.SwinModel]]
transformers.SwinModel[[transformers.SwinModel]]
transformers.SwinModel(config, add_pooling_layer = True, use_mask_token = False)
Parameters:
config (SwinModel) : Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
add_pooling_layer (bool, optional, defaults to True) : Whether or not to apply pooling layer.
use_mask_token (bool, optional, defaults to False) : Whether or not to create and apply mask tokens in the embedding layer.
The bare Swin Model outputting raw hidden-states without any specific head on top.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward[[transformers.SwinModel.forward]]
forward(pixel_values: typing.Optional[torch.FloatTensor] = None, bool_masked_pos: typing.Optional[torch.BoolTensor] = None, interpolate_pos_encoding: bool = False, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
Parameters:
pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size), optional) : The tensors corresponding to the input images. Pixel values can be obtained using ViTImageProcessor. See ViTImageProcessor.call() for details (processor_class uses ViTImageProcessor for processing images).
bool_masked_pos (torch.BoolTensor of shape (batch_size, num_patches), optional) : Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
interpolate_pos_encoding (bool, optional, defaults to False) : Whether to interpolate the pre-trained position encodings.
Returns: SwinModelOutput or tuple(torch.FloatTensor)
A SwinModelOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (SwinConfig) and inputs.
The SwinModel forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
last_hidden_state (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) -- Sequence of hidden-states at the output of the last layer of the model.pooler_output (
torch.FloatTensorof shape(batch_size, hidden_size), optional, returned whenadd_pooling_layer=Trueis passed) -- Average pooling of the last layer hidden-state.hidden_states (
tuple[torch.FloatTensor, ...], optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (
tuple[torch.FloatTensor, ...], optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
reshaped_hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.FloatTensor(one for the output of the embeddings + one for the output of each stage) of shape(batch_size, hidden_size, height, width).Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to include the spatial dimensions.
Example:
SwinForMaskedImageModeling[[transformers.SwinForMaskedImageModeling]]
transformers.SwinForMaskedImageModeling[[transformers.SwinForMaskedImageModeling]]
transformers.SwinForMaskedImageModeling(config)
Parameters:
config (SwinForMaskedImageModeling) : Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
Swin Model with a decoder on top for masked image modeling, as proposed in SimMIM.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward[[transformers.SwinForMaskedImageModeling.forward]]
forward(pixel_values: typing.Optional[torch.FloatTensor] = None, bool_masked_pos: typing.Optional[torch.BoolTensor] = None, interpolate_pos_encoding: bool = False, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
Parameters:
pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size), optional) : The tensors corresponding to the input images. Pixel values can be obtained using ViTImageProcessor. See ViTImageProcessor.call() for details (processor_class uses ViTImageProcessor for processing images).
bool_masked_pos (torch.BoolTensor of shape (batch_size, num_patches)) : Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
interpolate_pos_encoding (bool, optional, defaults to False) : Whether to interpolate the pre-trained position encodings.
Returns: SwinMaskedImageModelingOutput or tuple(torch.FloatTensor)
A SwinMaskedImageModelingOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (SwinConfig) and inputs.
The SwinForMaskedImageModeling forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
loss (
torch.FloatTensorof shape(1,), optional, returned whenbool_masked_posis provided) -- Masked image modeling (MLM) loss.reconstruction (
torch.FloatTensorof shape(batch_size, num_channels, height, width)) -- Reconstructed pixel values.hidden_states (
tuple[torch.FloatTensor, ...], optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (
tuple[torch.FloatTensor, ...], optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
reshaped_hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.FloatTensor(one for the output of the embeddings + one for the output of each stage) of shape(batch_size, hidden_size, height, width).Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to include the spatial dimensions.
Examples:
>>> from transformers import AutoImageProcessor, SwinForMaskedImageModeling
>>> 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/swin-base-simmim-window6-192")
>>> model = SwinForMaskedImageModeling.from_pretrained("microsoft/swin-base-simmim-window6-192")
>>> 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, 192, 192]
SwinForImageClassification[[transformers.SwinForImageClassification]]
transformers.SwinForImageClassification[[transformers.SwinForImageClassification]]
transformers.SwinForImageClassification(config)
Parameters:
config (SwinForImageClassification) : Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
Swin Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet.
Note that it's possible to fine-tune Swin on higher resolution images than the ones it has been trained on, by
setting interpolate_pos_encoding to True in the forward of the model. This will interpolate the pre-trained
position embeddings to the higher resolution.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward[[transformers.SwinForImageClassification.forward]]
forward(pixel_values: typing.Optional[torch.FloatTensor] = None, labels: typing.Optional[torch.LongTensor] = None, interpolate_pos_encoding: bool = False, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
Parameters:
pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size), optional) : The tensors corresponding to the input images. Pixel values can be obtained using ViTImageProcessor. See ViTImageProcessor.call() for details (processor_class uses ViTImageProcessor for processing images).
labels (torch.LongTensor of shape (batch_size,), optional) : Labels for computing the image classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy).
interpolate_pos_encoding (bool, optional, defaults to False) : Whether to interpolate the pre-trained position encodings.
Returns: SwinImageClassifierOutput or tuple(torch.FloatTensor)
A SwinImageClassifierOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (SwinConfig) and inputs.
The SwinForImageClassification forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) -- Classification (or regression if config.num_labels==1) loss.logits (
torch.FloatTensorof shape(batch_size, config.num_labels)) -- Classification (or regression if config.num_labels==1) scores (before SoftMax).hidden_states (
tuple[torch.FloatTensor, ...], optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.FloatTensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (
tuple[torch.FloatTensor, ...], optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) -- Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
reshaped_hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) -- Tuple oftorch.FloatTensor(one for the output of the embeddings + one for the output of each stage) of shape(batch_size, hidden_size, height, width).Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to include the spatial dimensions.
Example:
>>> from transformers import AutoImageProcessor, SwinForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224")
>>> model = SwinForImageClassification.from_pretrained("microsoft/swin-tiny-patch4-window7-224")
>>> 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])
...
Xet Storage Details
- Size:
- 25.7 kB
- Xet hash:
- 959db91c2e17751e5b8b422611a3f00639ed3dcbc996d339cebb13c51cd2d813
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.