SwinTransformer
PretrainedModelBackboneMixinSwinTransformer(config: SwinConfig)Swin Transformer backbone (Liu et al., 2021).
A Swin Transformer first splits the input image into non-overlapping patches via a strided convolution and then progresses through four hierarchical stages. Each stage stacks pairs of Swin blocks alternating between window attention (W-MSA) and shifted-window attention (SW-MSA), with patch-merging downsamplers between stages that halve spatial resolution and double channel width:
Window attention partitions the feature map into non-overlapping windows and runs self-attention inside each, making the per-image cost linear in . The shifted variant cycles each window by pixels so that information flows between neighbouring windows across pairs of blocks. A learnable relative position bias is added inside the softmax of every window attention.
forward_features returns a global-average-pooled
feature where . Use
this backbone when you need features rather than logits — e.g.
transfer learning, dense prediction, or contrastive pretraining.
For end-to-end image classification, use
SwinTransformerForImageClassification instead.
Parameters
configSwinConfigimage_size, patch_size,
embed_dim, depths, num_heads, window_size,
mlp_ratio, dropout, attention_dropout,
drop_path_rate, and in_channels. See SwinConfig.Attributes
patch_embed_PatchEmbedstagesnn.ModuleList_SwinStage modules, each containing a
stack of Swin blocks and (for the first three) a patch-merging
downsampler.normnn.LayerNormavgpoolnn.AdaptiveAvgPool2dfeature_infolist[FeatureInfo]Notes
Reference: Ze Liu et al., "Swin Transformer: Hierarchical Vision Transformer using Shifted Windows", ICCV 2021, arXiv:2103.14030.
Examples
Build a Swin-Tiny backbone and run a forward pass:
>>> import lucid
>>> from lucid.models.vision.swin import SwinTransformer, SwinConfig
>>> model = SwinTransformer(SwinConfig())
>>> x = lucid.randn(1, 3, 224, 224)
>>> feat = model.forward_features(x)
>>> feat.shape # (B, 8 * embed_dim)
(1, 768)
>>> out = model(x)
>>> out.last_hidden_state.shape # (B, 1, 8 * embed_dim)
(1, 1, 768)