AI Wiki中文/EN

Swin Transformer: crossing window boundaries without wraparound

Swin Transformer

Compute shifted-window attention, audit masks against an unrolled reference, and run a two-stage hierarchical classifier.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with a prediction

Imagine an 8×8 grid of patch tokens divided into four 4×4 windows. Token(3,3) lies in the upper-left window; token(4,4) is just across its boundary. Ordinary window attention cannot connect them in that layer. Move the window boundaries by two cells, and both tokens fall inside a new window.

Now inspect the image corners. A cyclic array shift places some tokens from the bottom or right next to tokens from the top or left. Those are artificial neighbors created by the implementation. Swin uses a mask to prevent attention across those wrapped boundaries. It changes the grouping without turning a flat image into a torus.

The architecture combines that alternating window pattern with patch merging. Later stages have fewer spatial tokens and more channels, producing a hierarchy of feature maps. This differs from the original fixed-resolution, globally attending ViT encoder. Swin method,§3.1–3.2

The tests below put a single nonzero value in the grid. They verify both effects: a nearby token across an old window boundary becomes visible, while an opposite-corner token remains excluded. Drawing shifted boxes would not establish those properties; computing the output does.

Computed regular and shifted attention neighbors of query Q at row 3 column 3.

The blue region contains the 16 keys allowed for Q(3,3). In A, S(4,4) lies outside its regular window; in B, shifting by 2 puts S in Q’s permitted group. Coordinates start at zero. This original illustration is generated from the program’s mask; it does not depict learned attention weights.

Follow the tensors and equations

Use h×w for the current patch grid and C for its channel width. A window contains M×M tokens. There are hw/M² windows when the grid is divisible by M. Within each window, multi-head attention still computes Q, K and V, forms a score matrix and mixes values; the neighborhood changes, not the basic attention operator.

Counting the four channel projections and the score/value matrix products, and omitting softmax and elementwise operations, gives:

Cglobal=4hwC2+2(hw)2C,Cwindow=4hwC2+2M2hwC.\begin{aligned}C_{\mathrm{global}}&=4hwC^2+2(hw)^2C,\\C_{\mathrm{window}}&=4hwC^2+2M^2hwC.\end{aligned}

These are MAC-style multiplication/addition counts for the stated dense projections. At fixed M and C, window attention is linear in the number of patch tokens hw. It is not linear in image side length, nor a claim about a whole model whose width and stage structure are also changing. On an 8×8 grid with C=8 and M=4, the counts are 81,920 and 32,768. Paper equations 1–2

A standard block normalizes before attention and before the MLP, with a residual addition after each. Consecutive blocks alternate ordinary window attention and shifted-window attention. The MLP has two linear layers with GELU between them:

X^=X+WAttn⁡(LN⁡(X)),X′=X^+MLP⁡(LN⁡(X^)).\begin{aligned}\widehat X&=X+\operatorname{WAttn}(\operatorname{LN}(X)),\\X'&=\widehat X+\operatorname{MLP}(\operatorname{LN}(\widehat X)).\end{aligned}

The next block uses the shifted neighborhood in the same formula. A shift is normally half a window, rounded down. An available cross-window connection is not the same as every token immediately receiving global context; the reachable region depends on the sequence of blocks and merges.

For one attention head, relative position bias and the exclusion mask enter the score before rowwise softmax:

A=softmax⁡row ⁣(QK⊤/dh+B+M),O=AV.\begin{aligned}A&=\operatorname{softmax}_{\mathrm{row}}\!\left(QK^\top/\sqrt{d_h}+B+\mathcal M\right),\\O&=AV.\end{aligned}

Here B uses the query-minus-key offset inside the window. Each axis has 2M−1 possible offsets, so the learned table contains(2M−1)² values per head, not a separate free parameter for every token pair. The same offset shares a bias value. The table does not by itself enforce rotation or translation invariance. Relative bias, equation 4

In our mathematical mask, an allowed pair adds zero and an excluded pair adds negative infinity. The pinned Microsoft implementation instead inserts−100 for excluded pairs. Our exact exclusion makes forbidden probabilities zero; it is a declared numerical simplification, not bit-identical reproduction of that finite mask. Fixed attention and mask code

A complete small forward pass

To construct the shifted mask independently, label each token by its non-periodic shifted-window coordinates in the original grid. For shift s, token(r,c) receives:

g(r,c)=(⌊r−sM⌋,⌊c−sM⌋).g(r,c)=\left(\left\lfloor\frac{r-s}{M}\right\rfloor,\left\lfloor\frac{c-s}{M}\right\rfloor\right).

Roll tokens toward the top-left by s, partition into regular windows, and allow attention only between equal labels. Then reverse partitioning and roll back. Labels at opposite image edges remain different even if the array roll placed them together. This coordinate construction is checked against the official nine-region mask and against a direct attention calculation that never rolls the grid.

Patch merging is a separate operation. It concatenates each 2×2 group into 4C channels, applies LN over that concatenated vector, then projects to 2C channels without a projection bias. Both grid sides halve. The fixed code orders the four cells as top-left, bottom-left, top-right, bottom-right. That order matters when comparing weights and outputs. PatchMerging implementation

For reference, Swin-T on a 224×224 RGB image uses patch side 4 and the following hierarchy. These are architecture settings, not results of running our small example. Original settings,§3.3

StageToken gridChannelsBlocks
156×56962
228×281922
314×143846
47×77682

The complete NumPy program below instead has two small stages. A 16×16 RGB image with patch side 2 becomes 8×8×4; after two blocks it is merged into 4×4×8, followed by two more blocks, final LN, global mean pooling and a three-class head. There is no class token or absolute position table. At the second stage, a 4×4 window already covers the full grid, so the implementation disables the requested shift. Dropout and stochastic depth are disabled; weights are random and untrained.

"""Original two-stage Swin teaching forward; strict grid sizes, no training.
Uses exact exclusion masks rather than the pinned implementation's finite -100.
"""
import math
import numpy as np


def positive(n):
    if isinstance(n,(bool,np.bool_)) or not isinstance(n,(int,np.integer)) or n<1:
        raise ValueError('expected a positive integer')
    return int(n)


def finite(x,ndim):
    x=np.asarray(x,dtype=float)
    if x.ndim!=ndim or min(x.shape)<1 or not np.isfinite(x).all():
        raise ValueError('expected finite nonempty tensor of the specified rank')
    return x


def patchify(x,patch):
    x=finite(x,3);p=positive(patch);h,w,c=x.shape
    if h%p or w%p:raise ValueError('image sides must be divisible by patch size')
    return x.reshape(h//p,p,w//p,p,c).transpose(0,2,1,3,4).reshape(-1,p*p*c)


def norm_params(width):
    width=positive(width)
    return (np.ones(width),np.zeros(width))


def layer_norm(x,params,eps=1e-5):
    x=np.asarray(x,dtype=float);gamma,beta=map(np.asarray,params)
    if x.ndim<2 or x.shape[-1]<1 or not np.isfinite(x).all():raise ValueError('invalid normalization input')
    if gamma.shape!=(x.shape[-1],) or beta.shape!=gamma.shape or eps<=0 or not np.isfinite(eps):
        raise ValueError('normalization shape or epsilon mismatch')
    if not np.isfinite(gamma).all() or not np.isfinite(beta).all():raise ValueError('invalid normalization parameters')
    centered=x-x.mean(axis=-1,keepdims=True)
    return centered/np.sqrt((centered*centered).mean(axis=-1,keepdims=True)+eps)*gamma+beta


def softmax(x):
    x=np.asarray(x,dtype=float)
    if x.ndim<1 or x.shape[-1]<1 or not np.isfinite(x).all():raise ValueError('invalid logits')
    z=np.exp(x-x.max(axis=-1,keepdims=True))
    return z/z.sum(axis=-1,keepdims=True)


def gelu(x):
    x=np.asarray(x,dtype=float)
    return .5*x*(1+np.vectorize(math.erf,otypes=[float])(x/np.sqrt(2)))


def make_block(width,heads,hidden,rng):
    width,heads,hidden=map(positive,(width,heads,hidden))
    if width%heads:raise ValueError('width must divide into equal heads')
    matrix=lambda a,b:rng.normal(0,.1,(a,b))
    return dict(qkv=matrix(width,3*width),qkv_bias=np.zeros(3*width),
                projection=matrix(width,width),projection_bias=np.zeros(width),
                first=matrix(width,hidden),first_bias=np.zeros(hidden),
                second=matrix(hidden,width),second_bias=np.zeros(width),
                norm1=norm_params(width),norm2=norm_params(width),heads=heads)



def settings(h,w,window,shift):
    h,w,window=map(positive,(h,w,window))
    if isinstance(shift,(bool,np.bool_)) or not isinstance(shift,(int,np.integer)) or not 0<=shift<window:
        raise ValueError('shift must be an integer in [0, window)')
    if min(h,w)<window or h%window or w%window:
        raise ValueError('grid must be divisible by the fixed window; no implicit padding')
    return window,0 if min(h,w)==window else int(shift)


def partition(x,window):
    x=finite(x,3);h,w,c=x.shape;window,_=settings(h,w,window,0)
    return x.reshape(h//window,window,w//window,window,c).transpose(0,2,1,3,4).reshape(-1,window*window,c)


def reverse(windows,h,w,window):
    windows=finite(windows,3);window,_=settings(h,w,window,0)
    if windows.shape[:2]!=(h//window*(w//window),window*window):raise ValueError('window shape mismatch')
    c=windows.shape[-1]
    return windows.reshape(h//window,w//window,window,window,c).transpose(0,2,1,3,4).reshape(h,w,c)


def shifted_mask(h,w,window,shift):
    window,shift=settings(h,w,window,shift)
    rows,cols=np.indices((h,w))
    # Labels are non-periodic window coordinates in the ORIGINAL image grid.
    groups=np.stack(((rows-shift)//window,(cols-shift)//window),axis=-1)
    packed=partition(np.roll(groups,(-shift,-shift),axis=(0,1)),window)
    return (packed[:,:,None,:]==packed[:,None,:,:]).all(axis=-1)


def relative_index(window):
    window=positive(window);coords=np.indices((window,window)).reshape(2,-1).T
    offsets=coords[:,None,:]-coords[None,:,:]+window-1
    return offsets[:,:,0]*(2*window-1)+offsets[:,:,1]


def masked_softmax(scores,allowed):
    scores=np.asarray(scores,dtype=float);allowed=np.asarray(allowed,dtype=bool)
    if not np.isfinite(scores).all():raise ValueError('nonfinite attention scores')
    allowed=np.broadcast_to(allowed,scores.shape)
    if not allowed.any(axis=-1).all():raise ValueError('every query needs at least one allowed key')
    z=np.where(allowed,scores,-np.inf);z=np.exp(z-z.max(axis=-1,keepdims=True))
    return z/z.sum(axis=-1,keepdims=True)


def make_window_block(width,heads,hidden,window,rng):
    block=make_block(width,heads,hidden,rng);window=positive(window)
    block.update(window=window,relative_bias=rng.normal(0,.02,((2*window-1)**2,heads)))
    return block


def window_attention(x,block,shift=0):
    x=finite(x,3);h,w,c=x.shape;heads=positive(block['heads']);window,shift=settings(h,w,block['window'],shift)
    if c%heads:raise ValueError('width must divide into equal heads')
    tokens=partition(np.roll(x,(-shift,-shift),axis=(0,1)),window);nw,n,_=tokens.shape
    qkv=(tokens@block['qkv']+block['qkv_bias']).reshape(nw,n,3,heads,c//heads)
    q,k,v=qkv.transpose(2,0,3,1,4)
    bias=block['relative_bias'][relative_index(window)].transpose(2,0,1)
    scores=q@k.transpose(0,1,3,2)/np.sqrt(c//heads)+bias[None]
    weights=masked_softmax(scores,shifted_mask(h,w,window,shift)[:,None])
    out=(weights@v).transpose(0,2,1,3).reshape(nw,n,c)
    out=out@block['projection']+block['projection_bias']
    return np.roll(reverse(out,h,w,window),(shift,shift),axis=(0,1)),weights


def swin_block(x,block,shift=0):
    x=finite(x,3)
    delta,weights=window_attention(layer_norm(x,block['norm1']),block,shift)
    x=x+delta;y=layer_norm(x,block['norm2'])
    return x+gelu(y@block['first']+block['first_bias'])@block['second']+block['second_bias'],weights


def merge(x,projection,norm):
    x=finite(x,3);h,w,c=x.shape
    if h%2 or w%2:raise ValueError('patch merging requires even grid sides')
    if np.asarray(projection).shape!=(4*c,2*c):raise ValueError('merge projection must map 4C to 2C')
    grouped=np.concatenate((x[0::2,0::2],x[1::2,0::2],x[0::2,1::2],x[1::2,1::2]),axis=-1)
    return layer_norm(grouped,norm)@projection


def tiny_swin(x,seed=13):
    x=finite(x,3)
    if x.shape!=(16,16,3):raise ValueError('this complete teaching model expects a 16 by 16 RGB image')
    rng=np.random.default_rng(seed)
    z=(patchify(x,2)@rng.normal(0,.1,(12,4))).reshape(8,8,4)
    z=layer_norm(z,norm_params(4));shapes=[z.shape]
    for shift in (0,2):
        z,_=swin_block(z,make_window_block(4,2,8,4,rng),shift)
    z=merge(z,rng.normal(0,.1,(16,8)),norm_params(16));shapes.append(z.shape)
    for shift in (0,2):
        z,_=swin_block(z,make_window_block(8,2,16,4,rng),shift)
    pooled=layer_norm(z,norm_params(8)).mean(axis=(0,1))
    probabilities=softmax(pooled@rng.normal(0,.1,(8,3)))
    return shapes,probabilities


if __name__=='__main__':
    x=np.arange(768.,dtype=float).reshape(16,16,3)/768
    shapes,probs=tiny_swin(x)
    print('stage grids:',shapes)
    print('probabilities:',np.round(probs,6).tolist())
    allowed=shifted_mask(8,8,4,2)
    print('allowed entries after shift:',int(allowed.sum()),'of',allowed.size)
    print('global/window attention MACs, grid8 width8 window4:',4*64*8**2+2*64**2*8,4*64*8**2+2*16*64*8)

Python 3.12.4 and NumPy 1.26.4 produce:

stage grids: [(8, 8, 4), (4, 4, 8)]
probabilities: [0.366298, 0.250201, 0.383501]
allowed entries after shift: 576 of 1024
global/window attention MACs, grid8 width8 window4: 81920 32768

The mask permits 576 of the 1,024 allocated score entries per head across the four packed windows. Exclusion does not reduce the allocated matrix size in this implementation. The probabilities are outputs on a synthetic numeric ramp, with no claim of image-recognition accuracy.

Limits and comparisons

Mask boundaries are part of the algorithm. Without the shifted mask, the token at(0,0) can attend to tokens wrapped from the bottom-right. With the checked mask, an impulse at(7,7) contributes nothing to(0,0). Under zero queries, keys and relative biases, attention becomes a mean over permitted values; the impulse contributes 1/4 to its own 2×2 corner group. In contrast, an impulse at(4,4) contributes 1/16 to(3,3) in the shifted central 4×4 group, while ordinary windows keep that contribution zero.

The program requires grid sides divisible by the fixed window size and even sides at merging. It refuses unsupported sizes instead of padding silently. The paper discusses bottom/right padding when needed; supporting that generally also requires specifying which padded queries and keys are valid. This example does not implement that extension. Its single-window shift rule matches the checked fixed implementation, but it does not adapt an oversized window to arbitrary smaller rectangles. Window and boundary discussion

Patch merging reduces token count by four while doubling channels. It is a learned compression, not a reversible reshaping or an average pool. Since the normalized 4C-vector is mapped into 2C coordinates, reconstruction is not guaranteed. Token count alone is therefore not a complete measure of retained information.

This is the original Swin-style block pattern, not all later Swin variants. The tiny classifier does not reproduce ImageNet training, object detection, segmentation, inference throughput or a pretrained checkpoint. Local attention also retains projection, MLP, normalization and data-movement costs; a linear token-scaling term is not proof of a specific device speedup.

Exercises with answers

1. Which tokens become neighbors?

Answer: On the 8×8 grid with M=4,s=2, positions(3,3) and(4,4) share the shifted group with rows/columns 2–5. Their old regular windows differ. Positions(0,0) and(7,7) remain in different non-periodic groups despite cyclic packing.

2. Count relative bias parameters

Answer: A 7×7 window has 13 offsets per axis, giving 169 bias values per head. With 3 heads this is 507 parameters, excluding Q/K/V and output projections. It is not49² independent bias parameters per head.

3. Merge a token grid

Answer: An 8×8×4 grid becomes 4×4×8. Each 2×2 group first forms a 16-dimensional vector, then LN and a 16-to-8 linear projection are applied. The token count falls from 64 to 16; this does not prove lossless compression.

4. Audit a speed claim

Answer: At h=w=8,C=8,M=4 the declared attention MAC counts are 81,920 global and 32,768 windowed. They omit softmax and elementwise work; MLP and memory traffic also matter. Measure a fixed device, precision, batch and shape before claiming a latency ratio.

Sources and next steps

Read the original hierarchy, alternating-block equations and cyclic-shift/mask discussion together. The relative-position bias is a separate learned component, and merging is a separate compression step. ICCV 2021 paper,§3.1–3.3

The implementation reference is Microsoft’s models/swin_transformer.py at commite43ac64ce8abfe133ae582741ccaf6761eea05f7, dated 2022-07-08. The checked sections cover window partition/reverse, relative indices, the nine-region mask, pre-LN residual blocks, patch merging and the pooled classifier. Its MIT license was checked. The NumPy code is original and uses an independently constructed coordinate mask; no upstream model or training code was executed. Fixed source

For a further experiment, track which input cells can influence one corner after each attention block and merge. Separate graph reachability from the magnitude of learned attention weights. A connection that exists in the graph may contribute very little in a particular model.

Make a prediction, then check

Why does shifted-window attention need a mask after cyclic packing?

Choose one answer

Learning objectives

  • Derive global and fixed-window attention costs.
  • Verify cross-window communication without cyclic boundary leakage.
  • Track relative position bias and learned patch merging.

Prerequisites & connections

Explore related knowledge →

References

  1. Swin Transformer: Hierarchical Vision Transformer Using Shifted Windows — ICCV2021 method
    Ze Liu; Yutong Lin; Yue Cao; Han Hu; Yixuan Wei; Zheng Zhang; Stephen Lin; Baining Guo · 2021
  2. Microsoft Swin Transformer — fixed commit e43ac64 (2022-07-08)
    Microsoft contributors · 2022

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded original method passages and fixed official code, explicit NumPy teaching models, independent numerical references, boundary cases and corresponding bilingual reasoning. Not independent human or second-agent review; no full training or deployment benchmark reproduction.

  • Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
  • Verified partition/reverse, coordinate mask against independent nine-region construction, relative-offset indices, full shifted attention against non-rolled original-grid reference, forbidden probabilities zero, near-boundary communication without opposite-corner leakage, merge order/LN, signed residual and full two-stage classifier. 10 article checks; exact exclusion and strict divisible-grid teaching scope.
  • Both languages compared section by section for claims, caveats, definitions, examples, formulas and four answer explanations. English spacing edited only outside code, mathematics, tags and link destinations before freezing.
  • Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.
  • Original figure derived from the exact mask: Q(3,3) has16 permitted keys in each panel; S(4,4) is excluded with shift0 and included with shift2. Expected coordinate sets asserted; PNG actually viewed. Symbolic A/B labels share localized article captions. Generator scripts/figures/swin-window-neighbors.py SHA256 b5c3425c93805945e96da485e037705d2e794567c173f32685ad52af01571d0f.
  • Final English read-through separated adjoining words and numerals such as An8 and permits576. Protected code, math, tags and link targets are identical; definitions, figures, numbers and exercise answers unchanged. Frozen wording retained; formal English SHA rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.