Module contents
Lesson 22 of 25Advanced 110 min

Hierarchical transformers and modern CNNs: Swin, ConvNeXt and what each learns

Study shifted-window attention, hierarchical Swin, ConvNeXt modernization and measured shape-texture behavior.

After this lesson you can

  • Calculate global and window attention costs.
  • Explain shifted-window masks, connectivity and hierarchical merging.
  • Distinguish ConvNeXt architectural changes from its training recipe.
  • Interpret shape and texture comparisons under their measurement protocols.

Before you start

Scale changes the question

For classification, a ViT can work with a single patch grid. Detection and segmentation need details at multiple sizes, and with large images the global attention matrix grows quickly. A 1024×1024 image divided into 16×16 patches has 4096 patches; each global attention head relates every patch to every other. An efficient implementation can avoid materializing the full matrix, but that does not eliminate quadratic products.

Swin proposes another combination: hierarchical maps and attention within windows whose boundaries shift between blocks. ConvNeXt travels in the opposite direction: it retains convolutions and revisits a ResNet using architecture and training choices associated with newer models. Comparing the families requires separating the mixing operation, recipe and budget.

From global attention to windows

Consider a map of H×WH\times W tokens, N=HWN=HW, width CC and square windows of side MM that divide both axes exactly. A global attention layer forms N×NN\times N matrices; window attention forms N/M2N/M^2 matrices of size M2×M2M^2\times M^2 per head. For one image and excluding biases, normalization and softmax, costs in MACs are

MAC⁡global=4NC2+2N2C,MAC⁡ventanas=4NC2+2NM2C.\operatorname{MAC}_{\text{global}}=4NC^2+2N^2C,\qquad \operatorname{MAC}_{\text{ventanas}}=4NC^2+2NM^2C.

The first term represents Q, K, V and output projections. The second counts QKTQK^T and AVAV. With fixed MM and CC, window cost is linear in NN; increasing window size also changes that coefficient. The MLP and rest of the block are added separately. Swin expresses these same calculations under its own operation convention. Here we count one MAC as two FLOPs.

For example, with 56×5656\times56 tokens, C=96C=96 and 7×77\times7 windows, there are 3136 tokens and 64 windows. Products QKTQK^T and AVAV decrease from 3,776,446,464 to 59,006,976 FLOPs, a factor of 64. Including all four projections, attention decreases from 4,007,657,472 to 290,217,984 FLOPs, a factor of about 13.81. Product cost is not the cost of the whole block, and FLOPs alone do not determine actual latency or memory.

Shift without connecting opposite edges

If all layers use the same windows, two patches in different windows do not exchange information through that attention. Shifted-window attention alternates a regular partition with a shifted one. To implement it efficiently, the map is shifted cyclically, grouped into equal-sized windows, attention is applied and the shift is reversed. Cyclic shifting is an implementation trick, not an assumption that the image is a torus.

The mask separates fragments within a shifted window that were brought together only by wrapping image edges. It instead permits connections between patches on opposite sides of an internal boundary of the previous windows. A mask forbidding all pairs from different previous windows would prevent precisely the intended communication.

InteractiveShifting windows

Layer 1 uses regular windows; layer 2 shifts them, and subsequent layers alternate. Choose a patch and advance: reachability shows where its information can propagate.

Layer 0 / 8
0123456701234567
  • Origin
  • Reachable
  • Not yet connected

Origin in original coordinates (0, 0); after this layer’s roll it moves to (0, 0). Effective shift (rows, columns): (0, 0). Layer 0 has no attention; the mask shown is the W-MSA mask for reference.

Roll shifts each axis upward or leftward and is then reversed. The edge reappearing on the other side is separated by a mask: being in the same rolled block is not enough to permit attention. Here the map is already divisible by window size, with no padding; if a window covers an axis, its shift is zero on that axis.

Reachability is structural: it considers all allowed connections and the residual identity possible, and does not simulate attention weights or predict learned influence. The mask is ideal, equivalent to applying −∞ to forbidden links. TorchVision uses −100: resulting weights can be numerically very small, but a finite mask does not guarantee an exact mathematical zero.

2
What to show
Grid view
0
0
Layer0, no layer
Reachable patches1 / 64
Allowed link16
Masked in its block0
Alternate partitions and follow a patch's structural reach. The diagram's ideal mask removes exactly the wraparound connections.

In an ideal model one can add 00 to allowed logits and −∞-\infty to forbidden ones before softmax. The TorchVision implementation uses −100-100: in real arithmetic the resulting probability may remain positive, and its value depends on all logits. To reproduce its outputs use its value and options; −∞-\infty is useful for studying ideal connectivity. It also pads maps to window multiples and cancels the shift on an axis if one window covers that axis. Its implementation does not add a separate mask to exclude every padding token, so introducing one changes the operator at indivisible sizes.

With 0<shift<M0<\text{shift}<M on both axes, two regular and shifted layers can connect an interior patch’s window to parts of existing neighboring windows. This does not mean every pixel of each neighboring window is reached in two layers, or that learned weights guarantee nonzero influence. In a stage without merging, each layer can move a dependency at most M−1M-1 positions per axis; after LL pairs, 2L(M−1)2L(M-1) is an upper bound, limited by the actual image edge. This is a claim about possible connectivity, not a causal measure.

A hierarchy of maps

The Swin-T hierarchical transformer starts with 4×4 patches. For 224×224 input it produces an initial 56×56 grid of width 96. Its four stages use depths 2, 2, 6 and 2, and widths 96, 192, 384 and 768. Between stages, patch merging concatenates 2×2 groups and projects from 4C4C to 2C2C, halving each spatial dimension. These maps can feed an FPN and a dense-task head.

Attention also includes a relative-position bias per head. For an M×MM\times M window, possible offsets per axis run from −(M−1)-(M-1) to M−1M-1, so there are (2M−1)2(2M-1)^2 entries per head: 169 if M=7M=7. The table index must match query and key order. Swin V1 and V2 differ in block details and normalization order, so loading weights requires respecting the variant.

Table 4 of Swin compares Swin-T with and without shifting: in its configurations, removing it reduces ImageNet top-1 by 1.1 points, COCO box AP by 2.8 and ADE20K mIoU by 2.8. These are results for those recipes and tasks, not a guarantee for any model.

Modernizing a convolution

ConvNeXt starts from a ResNet and progressively changes its training and architecture. Table 10 of A ConvNet for the 2020s presents each state measured on ImageNet-1k, with three seeds for the study variants. The recipe changes from 90 to 300 epochs and adds AdamW, Mixup, CutMix, RandAugment, random erasing, stochastic depth and label smoothing. With that recipe, the starting ResNet-50 goes from 76.13% to 78.82 ± 0.07% top-1; no single ingredient has been isolated.

Next the block distribution per stage is changed, a 4×4 stride-4 stem is introduced, depthwise convolution is used and width adjusted. Depthwise alone drops to 78.28 ± 0.08% and 2.35 GFLOPs; increasing width reaches 80.50 ± 0.02% and 5.27 GFLOPs. An inverted bottleneck arrangement and changes in block order prepare for a 7×7 spatial kernel. At that state, kernels 5, 7, 9 and 11 are alternatives evaluated from the same starting point, not four cumulative changes. The study continues with kernel 7.

Finally, activations and normalizations are replaced and reduced, and spatial downsampling is separated. Separate downsampling initially caused training to diverge; adding normalization at resolution changes allowed the ConvNeXt-T trajectory to reach 81.97 ± 0.06% and 4.49 GFLOPs. Differences at each step depend on what had already changed. We cannot activate unevaluated combinations and sum their supposed gains.

InteractiveThe ConvNeXt roadmap

Improved recipe. Duration, optimization and regularization change together.

747678808284Previous76.13Current78.82 ± 0.07

Previous: Original ResNet-50. Steps are cumulative and each change is measured from the prior state. Kernel sizes are alternatives, not additive steps; afterward the 7 × 7 trajectory resumes even if another alternative is selected.

ImageNet-1k top-1 and GFLOPs from ConvNeXt table 10. The table reports mean ± 0.07 points of standard deviation for this state, over three seeds. Horizontal bars show each state’s published standard deviation, not a confidence interval for the difference. Changing the recipe also changes the budget; the difference between states alone does not identify a universal cause. The accuracy axis starts at 74%.

1
Current top-178.82 %
Published GFLOPs4.09
Change from previous state+2.69 points
Explore the published states and compare kernel sizes measured from the same starting point.

Spatial attention adapts its weights to content; a depthwise convolution applies the same learned spatial filter to every position in a channel. Both separate spatial mixing from channel mixing in different ways; that does not make them identical operations. Also, two models with similar FLOPs can behave differently on different devices.

Shape or texture?

An image can present cues pointing to different classes: for example, a cat’s outline with a texture associated with another animal. Shape versus texture bias is studied by observing the category a model predicts over a set of conflicts, not attributing intention to one prediction.

In Geirhos and colleagues, ImageNet-trained ResNet-50 chose shape in 22.1% of responses matching either shape or texture; the rest of those responses matched texture. Training on Stylized-ImageNet increased the shape percentage to approximately 81% in their experiment. The denominator excludes other-class responses. The study selected source images correctly classified by the examined networks, so it does not automatically describe any collection of images.

The figure shows a short lab run: 32 images, two per shape category, selected before consulting predictions. You can compare four models, an original view and another with the same noise for all. Bars also include decisions matching neither shape nor texture; the conditioned proportion excludes those other decisions. Stability counts decisions that keep their category after noise, not correct predictions.

InteractiveShape and texture in conflict
Stimulus with bicycle shape and car texture

ID: bicycle9-car1

Decision among the 16 categories: car (texture).

Mean ImageNet probability for shape bicycle: 0.0028. For texture car: 0.0042.

Each score averages the subclasses in that category; the 16 means need not sum to one.

ResNet-50

Shape 2 · texture 19 · other 11 · evaluated 32/32.

Conditional bias: 2/21 = 9.5 %. Coverage: 21/32 = 65.6 %.

Category unchanged after noise: 20/32 (62.5 %).

ViT-B/16

Shape 8 · texture 13 · other 11 · evaluated 32/32.

Conditional bias: 8/21 = 38.1 %. Coverage: 21/32 = 65.6 %.

Category unchanged after noise: 24/32 (75.0 %).

ConvNeXt-T

Shape 5 · texture 17 · other 10 · evaluated 32/32.

Conditional bias: 5/22 = 22.7 %. Coverage: 22/32 = 68.8 %.

Category unchanged after noise: 18/32 (56.3 %).

Style-trained ResNet-50

Shape 12 · texture 5 · other 15 · evaluated 32/32.

Conditional bias: 12/17 = 70.6 %. Coverage: 17/32 = 53.1 %.

Category unchanged after noise: 16/32 (50.0 %).

Shape Texture Other category

Short test: images were selected before predictions were known; it cannot support general conclusions. Models and their training recipes differ. Conditional proportion and prediction consistency do not measure corruption accuracy or establish causality.

Corruption: ruido gaussiano RGB aditivo antes del preprocesado del modelo, standard deviation 0.08 on a zero-to-one scale and seed 16222. This is not ImageNet-C.

Source: rgeirhos/texture-shape-cue-conflict, revision 56399a23d693b8dbe7db8b2abad8863cee6bc14f. Thumbnails and predictions come from the same exported run.

Shape: bicycle · texture: car · decision: car (texture)
Explore predictions and counts from a short test that is not representative of the full dataset.

The thumbnails come from the cue-conflict dataset by Geirhos and colleagues, available under CC BY 4.0. They have been reduced in size and the noisy versions are adaptations. Their predictions and counts come from the same short run of the cell below.

When comparing models, record shape, texture and other responses, as well as the image transformation, labels and mapping from model classes to evaluated categories. A style intervention can change more properties than texture. Greater shape bias on one dataset does not by itself demonstrate universal robustness or identify a cause; separately measure accuracy under corruptions and their conditions.

As a published robustness comparison, Table 8 of ConvNeXt reports ImageNet-C mean corruption error, mCE, of 76.7 for ResNet-50, 62.0 for Swin-T and 53.2 for ConvNeXt-T; lower is better for this metric. Its models use different training recipes, so these results do not attribute the difference to architecture or shape bias. Nor are they measurements from the reduced test you will run below.

In models studied by Raghu and colleagues, ViT representations showed greater similarity between distant layers, while ResNet showed a more stage-structured pattern. Their analysis uses CKA on activations from the same images. Representation similarity depends on data and procedure and does not imply two networks implement the same function.

Choosing a backbone

Swin offers hierarchical maps and local windows convenient for dense tasks. ConvNeXt offers an entirely convolutional hierarchy. An isotropic ViT can also be adapted to detection or segmentation through scale and head changes, but its output is not automatically a pyramid. With few labels, compare pretraining and transfer; with 8 GB, measure activation memory, resolution and batch on the actual device. Available weights, fine-tuning time and task matter as much as the family name.

MLP-Mixer alternates MLPs mixing tokens and channels; its token mixing depends on sequence size. ConvMixer retains a patch grid and alternates depthwise spatial and 1×1 channel convolutions. These experiments help distinguish architectural choices, not prove a family dominates under all conditions.

Labs

Shifted windows from scratch

The next cell requires PyTorch and torchvision. It implements shifted windows and checks outputs and gradients against torchvision. The mask uses -100, that implementation’s finite value. The benchmark compares inference implementations with shared weights, but not identical operations: windows include relative bias and a mask. Timings depend on device and load; memory is PyTorch’s incremental peak. With ORYON_VERIFY_SHORT=1 shapes and repetitions are reduced. A short run checked outputs and gradients against torchvision in four geometries.

[ ]Shifted windows and global attentionLocal GPU
"""Swin V1: ventanas, sesgo relativo y paridad de salida/gradiente con torchvision.

Requiere PyTorch y torchvision. ORYON_VERIFY_SHORT=1 reduce el benchmark. El
benchmark mide inferencia de implementaciones explícitas, con pesos compartidos;
la atención global no equivale funcionalmente a la de ventanas. Máscara -100
reproduce torchvision: es finita y por ello no equivale matemáticamente a -inf.
"""
import json
import math
import os
from pathlib import Path
import time

import torch
from torch import nn
from torch.nn import functional as F
from torchvision.models.swin_transformer import ShiftedWindowAttention

DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
OUT = Path(os.environ.get('ORYON_SWIN_OUTPUT', 'swin-windows.json'))


def partition(x, window):
    b, h, w, c = x.shape
    wh, ww = window
    if h % wh or w % ww:
        raise ValueError('Dimensiones de entrada no divisibles por ventana')
    return x.reshape(b, h // wh, wh, w // ww, ww, c).permute(0, 1, 3, 2, 4, 5).reshape(-1, wh * ww, c)


def reverse(windows, window, b, h, w):
    wh, ww = window
    c = windows.shape[-1]
    return windows.reshape(b, h // wh, w // ww, wh, ww, c).permute(0, 1, 3, 2, 4, 5).reshape(b, h, w, c)


def position_index(window, device):
    wh, ww = window
    yy, xx = torch.meshgrid(torch.arange(wh, device=device), torch.arange(ww, device=device), indexing='ij')
    coords = torch.stack((yy.flatten(), xx.flatten()))
    offsets = coords[:, :, None] - coords[:, None, :]
    return ((offsets[0] + wh - 1) * (2 * ww - 1) + offsets[1] + ww - 1).flatten()


def relative_bias(table, window):
    n = window[0] * window[1]
    return table[position_index(window, table.device)].reshape(n, n, -1).permute(2, 0, 1).unsqueeze(0)


def shifted_mask(height, width, window, shift, device, dtype):
    wh, ww = window
    sh, sw = shift
    if height % wh or width % ww or not (0 <= sh < wh and 0 <= sw < ww):
        raise ValueError('Dimensiones acolchadas o desplazamientos inválidos')
    if sh == 0 and sw == 0:
        return None
    labels = torch.zeros((1, height, width, 1), dtype=dtype, device=device)
    # Esta construcción incluye también el caso de desplazamiento cero en
    # uno de los ejes, con los mismos slices que la función de torchvision.
    hs = (slice(0, -wh), slice(-wh, -sh), slice(-sh, None))
    ws = (slice(0, -ww), slice(-ww, -sw), slice(-sw, None))
    for i, h_slice in enumerate(hs):
        for j, w_slice in enumerate(ws):
            labels[:, h_slice, w_slice, :] = 3 * i + j
    regions = partition(labels, window).squeeze(-1)
    different = regions[:, None, :] != regions[:, :, None]
    return torch.where(different, -100., 0.).to(dtype=dtype)


class WindowAttention(nn.Module):
    def __init__(self, dim, window, shift, heads):
        super().__init__()
        if dim % heads:
            raise ValueError('La dimensión debe ser múltiplo del número de cabezas')
        self.window, self.shift, self.heads = tuple(window), tuple(shift), heads
        self.qkv = nn.Linear(dim, 3 * dim)
        self.proj = nn.Linear(dim, dim)
        self.relative_position_bias_table = nn.Parameter(torch.empty((2 * window[0] - 1) * (2 * window[1] - 1), heads))
        nn.init.trunc_normal_(self.relative_position_bias_table, std=.02)
        self.register_buffer('relative_position_index', position_index(window, torch.device('cpu')))

    def forward(self, input):
        b, h, w, c = input.shape
        wh, ww = self.window
        x = F.pad(input, (0, 0, 0, (-w) % ww, 0, (-h) % wh))
        ph, pw = x.shape[1:3]
        sh = 0 if wh >= ph else self.shift[0]
        sw = 0 if ww >= pw else self.shift[1]
        if sh or sw:
            x = torch.roll(x, shifts=(-sh, -sw), dims=(1, 2))
        x = partition(x, self.window)
        nw = (ph // wh) * (pw // ww)
        n = wh * ww
        qkv = self.qkv(x).reshape(b * nw, n, 3, self.heads, c // self.heads).permute(2, 0, 3, 1, 4)
        q, k, v = qkv.unbind(0)
        attention = (q * (c // self.heads) ** -.5) @ k.transpose(-1, -2)
        attention = attention + relative_bias(self.relative_position_bias_table, self.window)
        mask = shifted_mask(ph, pw, self.window, (sh, sw), input.device, input.dtype)
        if mask is not None:
            attention = (attention.reshape(b, nw, self.heads, n, n) + mask[None, :, None]).reshape(b * nw, self.heads, n, n)
        output = self.proj((attention.softmax(-1) @ v).transpose(1, 2).reshape(b * nw, n, c))
        output = reverse(output, self.window, b, ph, pw)
        if sh or sw:
            output = torch.roll(output, shifts=(sh, sw), dims=(1, 2))
        return output[:, :h, :w].contiguous()


def global_attention(x, block):
    b, h, w, c = x.shape
    n = h * w
    qkv = block.qkv(x.reshape(b, n, c)).reshape(b, n, 3, block.heads, c // block.heads).permute(2, 0, 3, 1, 4)
    q, k, v = qkv.unbind(0)
    weights = ((q * (c // block.heads) ** -.5) @ k.transpose(-1, -2)).softmax(-1)
    return block.proj((weights @ v).transpose(1, 2).reshape(b, h, w, c))


def check_parity():
    cases = [((2, 11, 13, 12), (7, 7), (3, 3), 3),
             ((1, 8, 9, 12), (4, 3), (2, 0), 3),
             ((1, 4, 3, 12), (7, 7), (3, 3), 3),
             ((1, 8, 12, 12), (4, 3), (0, 0), 3)]
    reports = []
    for shape, window, shift, heads in cases:
        torch.manual_seed(16220)
        ours = WindowAttention(shape[-1], window, shift, heads).to(DEVICE)
        ref = ShiftedWindowAttention(shape[-1], list(window), list(shift), heads).to(DEVICE)
        ref.load_state_dict(ours.state_dict(), strict=True)
        x = torch.randn(shape, device=DEVICE, requires_grad=True)
        xr = x.detach().clone().requires_grad_()
        a, b = ours(x), ref(xr)
        torch.testing.assert_close(a, b, rtol=1e-5, atol=1e-6)
        a.square().sum().backward(); b.square().sum().backward()
        torch.testing.assert_close(x.grad, xr.grad, rtol=1e-5, atol=1e-6)
        for (name, p), (ref_name, q) in zip(ours.named_parameters(), ref.named_parameters()):
            if name != ref_name:
                raise ValueError(f'Parámetros no alineados: {name}, {ref_name}')
            torch.testing.assert_close(p.grad, q.grad, rtol=1e-5, atol=1e-6)
        delta = float((a - b).abs().max().detach().cpu())
        print('Forma', shape, 'ventana', window, 'desplazamiento', shift, 'máxima diferencia:', delta)
        reports.append({'shape': shape, 'window': window, 'shift': shift, 'max_abs_difference': delta})
    return reports


@torch.no_grad()
def measure(fn, x, repeats):
    for _ in range(2):
        fn(x)
    torch.cuda.synchronize()
    base = torch.cuda.memory_allocated()
    torch.cuda.reset_peak_memory_stats()
    start = time.perf_counter()
    for _ in range(repeats):
        fn(x)
    torch.cuda.synchronize()
    return {'milliseconds_per_call': 1000 * (time.perf_counter() - start) / repeats,
            'peak_increment_bytes': max(0, torch.cuda.max_memory_allocated() - base),
            'warmup_calls': 2, 'timed_calls': repeats}


def main():
    parity = check_parity()
    experiments = []
    if DEVICE.type == 'cuda':
        torch.manual_seed(16221)
        block = WindowAttention(96, (7, 7), (3, 3), 3).to(DEVICE).eval()
        for size in ([14, 28] if SHORT else [14, 28, 42, 56]):
            x = torch.randn(1, size, size, 96, device=DEVICE)
            repeats = 3 if SHORT else 20
            window = measure(block, x, repeats)
            global_ = measure(lambda y: global_attention(y, block), x, repeats)
            experiments.append({'height': size, 'width': size, 'window': window, 'global': global_})
            print('Mapa', size, 'ventanas', window, 'global', global_)
            del x
    else:
        print('Sin CUDA: se omite el benchmark GPU, no se inventan tiempos.')
    data = {'short': SHORT, 'device': str(DEVICE), 'torch': torch.__version__,
            'parity': parity, 'benchmarks': experiments, 'mask_value': -100,
            'protocol': 'Inferencia sin dropout; ambos proyectan QKV y salida. '
                        'Ventanas usan bias relativo y máscara, global no. '
                        'Memoria pico incremental de PyTorch, excluye entrada y parámetros residentes; '
                        'tiempos dependen de backend y carga compartida.'}
    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')
    print('Salida:', OUT.resolve())
    if DEVICE.type == 'cuda':
        torch.cuda.empty_cache()


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Shape, texture and corruptions

The cue-conflict dataset by Geirhos and colleagues contains real images generated through style transfer; its card declares CC BY 4.0. This cell needs PyTorch, torchvision, pyarrow, Pillow and huggingface_hub; it downloads data and official weights when run. It compares ResNet-50, ViT-B/16, ConvNeXt-T and the ResNet trained on Stylized-ImageNet. To skip downloading the latter, use ORYON_STYLE_MODEL=0, but that comparison is then omitted. The models use different recipes, so the result does not isolate architecture.

For each image, ImageNet probabilities are averaged over subclasses forming each of the 16 original categories. Images without conflict are excluded, decisions for shape, texture and other categories counted, and coverage reported. Shape bias is shape divided by shape plus texture, conditioned on those two decisions. The cell adds RGB Gaussian noise with standard deviation 0.08 on a zero-to-one scale and seed 16222 before each model’s preprocessing; the same identifier receives the same corruption. It saves before-and-after counts, transitions and the fraction of unchanged categories. This consistency is not ImageNet-C accuracy and does not establish causality. With ORYON_VERIFY_SHORT=1, two images per shape class are selected before consulting predictions: this checks the pipeline, not a conclusion.

[ ]Shape and texture in three backbonesLocal GPU
"""Forma frente a textura en estímulos cue-conflict reales de Geirhos et al.

Requiere torch, torchvision, pyarrow, huggingface_hub y Pillow. Descarga, al
ejecutarse, el Parquet publicado por los autores y los pesos oficiales. El modo
ORYON_VERIFY_SHORT=1 toma dos imágenes por clase de forma, elegidas antes de
ver predicciones, y verifica el circuito: no estima un sesgo general.
ORYON_STYLE_MODEL=0 omite la ResNet-50 entrenada con SIN y su comparación.
Fuente: https://github.com/rgeirhos/texture-vs-shape y ficha del conjunto
https://huggingface.co/datasets/rgeirhos/texture-shape-cue-conflict
"""
import base64
import hashlib
import io
import json
import os
from pathlib import Path

import pyarrow.parquet as pq
from PIL import Image
from huggingface_hub import hf_hub_download
import torch
from torchvision.models import (resnet50, ResNet50_Weights, vit_b_16, ViT_B_16_Weights,
                                convnext_tiny, ConvNeXt_Tiny_Weights)
from torchvision.transforms import functional as TF

DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
OUT = Path(os.environ.get('ORYON_CUE_OUTPUT', 'cue-conflict-results.json'))
REPO = 'rgeirhos/texture-shape-cue-conflict'
REVISION = '56399a23d693b8dbe7db8b2abad8863cee6bc14f'
FILENAME = 'data/test-00000-of-00001.parquet'
EXPECTED_SHA256 = 'ef5c47245e11d7cadbbfe839f4e107139d13667b2ff409227e27bb8fcdd3e98e'
NOISE_STD, NOISE_SEED = .08, 16222
SIN_URL = ('https://bitbucket.org/robert_geirhos/texture-vs-shape-pretrained-models/'
           'raw/6f41d2e86fc60566f78de64ecff35cc61eb6436f/resnet50_train_60_epochs-c8e5653e.pth.tar')

# Índices oficiales de human_categories.py, no son rangos aproximados.
# https://github.com/rgeirhos/texture-vs-shape/blob/master/code/helper/human_categories.py
CATEGORIES = {
    'airplane': [404], 'bear': [294, 295, 296, 297], 'bicycle': [444, 671],
    'bird': [8, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 22, 23, 24, 80, 81, 82, 83,
             87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100, 127, 128, 129, 130,
             131, 132, 133, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145],
    'boat': [472, 554, 625, 814, 914], 'bottle': [440, 720, 737, 898, 899, 901, 907],
    'car': [436, 511, 817], 'cat': [281, 282, 283, 284, 285, 286],
    'chair': [423, 559, 765, 857], 'clock': [409, 530, 892],
    'dog': [i for i in range(152, 269) if i not in {192, 204, 227, 242, 251, 258, 260, 264}],
    'elephant': [385, 386], 'keyboard': [508, 878], 'knife': [499], 'oven': [766],
    'truck': [555, 569, 656, 675, 717, 734, 864, 867],
}


def sha256_file(path):
    digest = hashlib.sha256()
    with open(path, 'rb') as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b''):
            digest.update(chunk)
    return digest.hexdigest()


def choose_rows(path):
    if pq.ParquetFile(path).metadata.num_rows != 1280:
        raise ValueError('El Parquet no contiene las 1280 imágenes anunciadas')
    rows = []
    columns = ['file_id', 'shape_cue', 'texture_cue']
    for batch in pq.ParquetFile(path).iter_batches(batch_size=256, columns=columns):
        for row in batch.to_pylist():
            shape = str(row['shape_cue']).strip().lower()
            texture = str(row['texture_cue']).strip().lower()
            file_id = str(row['file_id'])
            if shape not in CATEGORIES or texture not in CATEGORIES:
                raise ValueError(f'Etiquetas desconocidas: {file_id}, {shape}, {texture}')
            if shape != texture:
                rows.append({'id': file_id, 'shape': shape, 'texture': texture})
    if len({row['id'] for row in rows}) != len(rows):
        raise ValueError('Identificadores repetidos en el conjunto')
    if SHORT:
        selected = []
        for category in sorted(CATEGORIES):
            candidates = [row for row in rows if row['shape'] == category]
            candidates.sort(key=lambda row: hashlib.sha256(row['id'].encode('utf-8')).hexdigest())
            if len(candidates) < 2:
                raise ValueError(f'No hay dos imágenes en la categoría {category}')
            selected.extend(candidates[:2])
        return selected
    return rows


def load_model(name):
    if name == 'resnet50':
        weights = ResNet50_Weights.IMAGENET1K_V1
        return resnet50(weights=weights), weights.transforms(), str(weights)
    if name == 'vit_b_16':
        weights = ViT_B_16_Weights.IMAGENET1K_V1
        return vit_b_16(weights=weights), weights.transforms(), str(weights)
    if name == 'convnext_tiny':
        weights = ConvNeXt_Tiny_Weights.IMAGENET1K_V1
        return convnext_tiny(weights=weights), weights.transforms(), str(weights)
    if name == 'resnet50_sin':
        # El checkpoint oficial incluye un diccionario state_dict de DataParallel.
        model = resnet50(weights=None)
        checkpoint = torch.hub.load_state_dict_from_url(SIN_URL, map_location='cpu', check_hash=True, weights_only=True)
        state = checkpoint['state_dict']
        model.load_state_dict({k.removeprefix('module.'): v for k, v in state.items()}, strict=True)
        return model, ResNet50_Weights.IMAGENET1K_V1.transforms(), SIN_URL
    raise ValueError(name)


def read_batches(path, selected, batch_size=8):
    wanted = {row['id'] for row in selected}
    images, ids = [], []
    for batch in pq.ParquetFile(path).iter_batches(batch_size=64, columns=['image', 'file_id']):
        for row in batch.to_pylist():
            file_id = str(row['file_id'])
            if file_id not in wanted:
                continue
            blob = row['image']['bytes']
            if blob is None:
                raise ValueError(f'Imagen sin bytes: {file_id}')
            with Image.open(io.BytesIO(blob)) as source:
                images.append(source.convert('RGB').copy())
            ids.append(file_id)
            if len(images) == batch_size:
                yield ids, images
                images, ids = [], []
    if images:
        yield ids, images


def thumbnail(image):
    image = image.copy()
    image.thumbnail((256, 256), Image.Resampling.LANCZOS)
    buf = io.BytesIO()
    image.save(buf, format='PNG')
    return 'data:image/png;base64,' + base64.b64encode(buf.getvalue()).decode('ascii')


def corrupt_image(image, file_id):
    # Semilla estable por imagen: la misma corrupción se aplica a todos los
    # modelos, independientemente del orden de lotes o del orden de ejecución.
    key = hashlib.sha256(f'{NOISE_SEED}:{file_id}'.encode('utf-8')).digest()
    generator = torch.Generator(device='cpu').manual_seed(int.from_bytes(key[:8], 'little'))
    values = TF.pil_to_tensor(image).float() / 255.
    noise = torch.randn(values.shape, generator=generator) * NOISE_STD
    # Se cuantifica a RGB de 8 bits antes del preprocesado específico de pesos.
    return TF.to_pil_image((values + noise).clamp(0, 1))


def scores_for_images(model, transform, images, names):
    batch = torch.stack([transform(image) for image in images]).to(DEVICE)
    logits = model(batch)
    if logits.shape != (len(images), 1000) or not torch.isfinite(logits).all():
        raise ValueError('Los logits deben ser finitos y de dimensión 1000')
    probabilities = logits.softmax(-1)
    # La media, no la suma ni el máximo, es la regla recomendada por los autores.
    return torch.stack([probabilities[:, CATEGORIES[name]].mean(-1) for name in names], dim=-1).cpu()


@torch.inference_mode()
def predict(model, transform, path, rows, preview_ids):
    model.to(DEVICE).eval()
    names = sorted(CATEGORIES)
    results, previews, corrupt_previews = {}, {}, {}
    for ids, images in read_batches(path, rows, batch_size=2 if SHORT else 8):
        corrupt_images = [corrupt_image(image, file_id) for file_id, image in zip(ids, images)]
        score = scores_for_images(model, transform, images, names)
        corrupt_score = scores_for_images(model, transform, corrupt_images, names)
        for i, (file_id, image, corrupted) in enumerate(zip(ids, images, corrupt_images)):
            results[file_id] = {
                'decision': names[int(score[i].argmax())],
                'category_mean_probabilities': score[i].tolist(),
                'corrupted': {'decision': names[int(corrupt_score[i].argmax())],
                              'category_mean_probabilities': corrupt_score[i].tolist()},
            }
            if file_id in preview_ids:
                previews[file_id] = thumbnail(image)
                corrupt_previews[file_id] = thumbnail(corrupted)
    if set(results) != {row['id'] for row in rows}:
        raise ValueError('Faltan imágenes o hay identificadores duplicados en el Parquet')
    return results, previews, corrupt_previews


def summarize(rows, predictions):
    shape = texture = other = 0
    for item in rows:
        decision = predictions[item['id']]['decision']
        if decision == item['shape']:
            shape += 1
        elif decision == item['texture']:
            texture += 1
        else:
            other += 1
    relevant = shape + texture
    return {'shape': shape, 'texture': texture, 'other_of_16': other, 'total': len(rows),
            'coverage': relevant / len(rows),
            'shape_bias_conditional': shape / relevant if relevant else None}


def stability(rows, predictions):
    outcomes = ('shape', 'texture', 'other')
    transition = {before: {after: 0 for after in outcomes} for before in outcomes}
    unchanged = 0
    for row in rows:
        pred = predictions[row['id']]
        before, after = pred['decision'], pred['corrupted']['decision']
        def kind(decision):
            return 'shape' if decision == row['shape'] else 'texture' if decision == row['texture'] else 'other'
        transition[kind(before)][kind(after)] += 1
        unchanged += int(before == after)
    return {'same_category': unchanged, 'total': len(rows),
            'consistency': unchanged / len(rows), 'transitions': transition}


def main():
    path = hf_hub_download(repo_id=REPO, repo_type='dataset', revision=REVISION, filename=FILENAME)
    digest = sha256_file(path)
    if digest != EXPECTED_SHA256:
        raise ValueError('SHA-256 del conjunto distinto al publicado para esta revisión')
    rows = choose_rows(path)
    if not rows:
        raise ValueError('No se encontraron ejemplos con señales distintas')
    # Selección independiente de las predicciones, útil para un visor verificable.
    preview_ids = {row['id'] for row in sorted(rows, key=lambda r: hashlib.sha256(r['id'].encode('utf-8')).hexdigest())[:16]}
    models = ['resnet50', 'vit_b_16', 'convnext_tiny']
    if os.environ.get('ORYON_STYLE_MODEL', '1') == '1':
        models.append('resnet50_sin')
    output = {'dataset': REPO, 'revision': REVISION, 'filename': FILENAME, 'sha256': digest,
              'short': SHORT, 'selected': rows, 'class_order': sorted(CATEGORIES), 'models': {},
              'protocol': 'Se excluyen pares sin conflicto; cada categoría se puntúa con la media '
                          'de probabilidades ImageNet de sus índices. Se elige entre 16 categorías; '
                          'shape_bias = forma/(forma+textura), condicionado a esas decisiones. '
                          'Otras categorías se cuentan y no entran en el denominador.',
              'corruption': {'kind': 'ruido gaussiano RGB aditivo antes del preprocesado del modelo',
                             'standard_deviation': NOISE_STD, 'seed': NOISE_SEED,
                             'range': '[0,1], recorte a [0,1] y cuantización a 8 bits',
                             'same_image_same_noise_across_models': True},
              'limitation': 'Los modelos, pesos y recetas de preentrenamiento difieren; estos estímulos '
                            'no prueban una causa arquitectónica. La consistencia entre predicciones '
                            'no es exactitud y este experimento no mide ImageNet-C.'}
    OUT.parent.mkdir(parents=True, exist_ok=True)
    for name in models:
        model, transform, source = load_model(name)
        predictions, previews, corrupt_previews = predict(model, transform, path, rows, preview_ids)
        summary = summarize(rows, predictions)
        corrupt_summary = summarize(rows, {key: value['corrupted'] for key, value in predictions.items()})
        consistency = stability(rows, predictions)
        print(name, 'original:', summary, 'corrompida:', corrupt_summary, 'estabilidad:', consistency)
        output['models'][name] = {'weights': source, 'transform': str(transform),
                                  'summary': summary, 'corrupted_summary': corrupt_summary,
                                  'stability': consistency, 'predictions': predictions}
        if 'previews' not in output:
            output['previews'] = previews
            output['corrupted_previews'] = corrupt_previews
        OUT.write_text(json.dumps(output, ensure_ascii=False), encoding='utf-8')
        del model, predictions
        if DEVICE.type == 'cuda':
            torch.cuda.empty_cache()
    print('Salida:', OUT.resolve())


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericGlobal attention in a stage
A 56×56 map has C=96. How many FLOPs does global attention cost including Q, K, V and output projections and the QKᵀ and AV products? Use 1 MAC=2 FLOPs and omit biases, softmax, normalization and MLP.
NumericWindow attention
With the same map and C=96, how many FLOPs does attention with 7×7 windows cost, including all four projections? Use the previous exercise's conventions.
ProofReach between layers
Prove: Reason about possible dependencies in a stage with M×M windows, M>1, and shift s with 0<s<M on both axes.
0
Assume an interior window, regular partition followed by shifted, and a mask removing only artificial wraparound links. Consider connectivity, not specific learned weights.

Step 1 of 3. What information can a point gather after the first regular layer?

CodeRemove artificial wraparound
Implement shifted_window_mask(H, W, window, shift) with NumPy for H and W multiples of window and at least two windows per axis, with 0 < shift < window. Apply roll(−shift) to both axes and divide windows in row order. Return an additive matrix per window of shape (n_windows, window², window²): 0 if both tokens belong to the same shifted window of the image without wraparound and −inf otherwise. Token order within each window is also by rows.
import numpy as np


def shifted_window_mask(H, W, window, shift):
  pass
Shift+Enter to run
QuizArchitecture and training
Which option distinguishes an architectural choice from the recipe used in the published ConvNeXt trajectory?
QuizSegmenting with limited resources
You need to segment large images with 8 GB and few labels. Which choice is best justified before measuring?
Key idea
Windows shift attention reach in a structured way; a modern CNN can recover many recipe and hierarchical design choices. Comparison is informative when data, compute and evaluation rules are clear.