Module contents
Lesson 23 of 25Advanced 120 min

Self-supervised vision: MAE, DINO and iBOT

Study masked image modeling, MAE, DINO self-distillation and the evaluation of frozen visual representations.

After this lesson you can

  • Compare masked pixel reconstruction with visual token prediction.
  • Explain MAE masking, reconstruction and encoder compute.
  • Derive DINO cross-view distillation and analyze collapse diagnostics.
  • Interpret attention visualizations and compare linear probes, k-NN and fine-tuning.

Before you start

The objective creates the question

Self-supervision constructs a task from the data itself. The general framework of self-supervised learning includes prediction, reconstruction and comparison of views. Here we focus on a visual challenge: an image contains redundant information across regions, but also objects whose identity cannot be reduced to reconstructing every pixel.

Masked image modeling means hiding part of an image and defining what must be inferred from it. Choices about what to hide, which representation to predict and how to use the encoder afterward produce different problems. In BEiT, targets are discrete indices produced by a visual tokenizer; in MAE, targets are pixel values of hidden patches. Those labels are not the same signal and neither objective directly equals a class label.

MAE: the encoder does not see the masks

A masked autoencoder divides an image into patches and randomly selects the visible ones. The encoder processes only those tokens and the class token, while a lighter decoder receives their representations along with mask tokens, reordered into their original positions. The decoder predicts patches and loss is evaluated on hidden ones. If loss uses per-patch normalized pixels, normalize each target with its own mean and variance according to the implementation’s convention; state that choice because unnormalized pixel targets can also be used.

MAE uses a high masking rate in its protocol, around 75%. A useful percentage depends on spatial redundancy, patch size, data and objective; it is not a universal constant or proof that hiding 15% is always trivial. Reconstruction can recover visual patterns without every hidden pixel being uniquely identifiable. A coherent image does not prove the representation is good for every downstream task.

In MAE Table 1, ViT-L/16 pretrained for 800 epochs on ImageNet-1K with 75% of patches hidden achieves 84.9% after fine-tuning and 73.5% with linear evaluation when reconstructing unnormalized pixels; with per-patch normalized pixels it achieves 85.4% and 73.9% respectively. These are two evaluation protocols and two specific targets, not a guarantee of improvement on any dataset.

InteractiveHow much can be hidden?
OriginalVisible inputReconstruction
Original image, input with hidden patches and reconstruction combined with visible patches

Pretrained weights facebook/vit-mae-base, revision 25b184bea5538bf5c4c852c79d221195fdd2778d. Masks use the same permutation per image and are nested. The effective fraction may vary due to rounding to a whole number of patches.

Mean squared error is calculated only on hidden patches, over model-preprocessor-normalized values; this checkpoint does not normalize each patch for its target. In the right panel visible patches are copied from the input. At 0% there is no loss on hidden patches and only visible pixels are shown.

Image data/train-00000-of-00003.parquet:965; original image SHA-256 bc4860dbafa13328438ec7d7484f13b971d2beb09cecf035d47aa3d1ae979058. Source: Oxford-IIIT Pet, Parkhi, Vedaldi, Zisserman and Jawahar, CC BY-SA 4.0; rights belong to their original owners. One image does not demonstrate general performance.

75 %
Hidden patches147 / 196
Effective mask75.00 %
MSE on hidden patches0.1269
Compare input and reconstruction from a pretrained MAE on two validation images with different nested masks.

This panel uses the public MAE ViT-B/16 checkpoint and two images from the short semantic segmentation validation. Values and images were obtained by running this lesson’s visualization lab. There is no single correct reconstruction for hidden pixels, and such a small sample cannot generalize about quality.

Encoder savings are subtler than replacing N2N^2 with (N/4)2(N/4)^2. For ViT-B/16 with a 224 image there are 196 patches; hiding 75% leaves 49 visible and one CLS, or 50 tokens versus 197. With width D=768D=768, MLP expansion 4 and one MAC equal to two FLOPs, products QKTQK^T and AVAV per block decrease by a factor (50/197)2≈0,0644(50/197)^2\approx0,0644 (approximately 0.0644). Projections and MLP scale linearly with tokens: including both, the approximate block count drops from 2,907,909,120 to 715,468,800 FLOPs, or 24.6% of the original. These counts omit normalization, softmax, embedding, decoder and backward; they are not total training speedup.

DINO: a teacher following the student

DINO self-distillation constructs views of an image and trains the student to predict the teacher’s distribution on another view. The teacher receives global crops; the student receives global and local crops. The loss excludes pairs formed from the same global crop, so each term is not a trivial comparison of a view with itself. The teacher receives no gradients from that loss: its parameters are updated by exponential moving average from the student.

If ztz_t and zsz_s are teacher and student logits, cc is the center and Tt,Ts>0T_t,T_s>0 are temperatures, their distributions are p=softmax⁡((zt−c)/Tt)p=\operatorname{softmax}((z_t-c)/T_t) and q=softmax⁡(zs/Ts)q=\operatorname{softmax}(z_s/T_s). A view pair contributes −∑kpklog⁡qk-\sum_k p_k\log q_k. The center is updated by a moving average of teacher logits; centering and sharpening change the dynamics, but are not a general mathematical guarantee against all collapse.

To see this, hold pp fixed when differentiating with respect to student logits: ∂L/∂zs,k=(qk−pk)/Ts\partial L/\partial z_{s,k}=(q_k-p_k)/T_s. The gradient is zero when q=pq=p, not for an arbitrary student. If all inputs produce teacher logits equal to the center, pp is uniform for any positive temperature; a uniform student also matches the teacher. That configuration remains a fixed point of the objective: lowering temperature does not turn an exactly uniform distribution into a nonuniform one.

With two global crops and six local crops, the teacher produces two distributions and the student eight; excluding the two same-crop pairs leaves 14 cross terms. In the DINO ablation, ViT-S/16 pretrained for 300 epochs obtains 67.9% with k-NN and 72.5% with a linear probe using two global views; adding six local views gives 72.7% and 75.9%. These numbers compare those configurations and their protocol, not prove more crops always help.

InteractiveCentering, temperature and collapse

This is a deterministic toy model: four inputs with three free logits each. There are no images, crops or neural network. Curves come from the equations below, not real DINO training.

Teacher entropies, in nats

1.1000120Model step
  • Mean H per input
  • H of the mean distribution

Mean teacher-to-student KL, in nats

0.2400120Model step

The vertical KL scale adapts to the trajectory maximum, with a minimum of 0.0001 nats when that maximum is very small; entropies use a fixed 0 to ln(3) scale. The vertical line marks the selected step.

Teacher distributions at step 120; each row corresponds to a synthetic input and sums to one except for rounding:

InputOutput 1Output 2Output 3
10.99960.00040.0000
20.00001.00000.0000
30.00020.00000.9998
40.00040.00040.9992

Low per-sample entropy may describe confident predictions; if marginal entropy is also low, all may concentrate on the same output. A high marginal and high per-sample entropy may correspond to uniform outputs. Their difference measures statistical variation of outputs across inputs, not semantic meaning. Zero KL only says student and teacher agree per input; it does not prove collapse.

Shared initialization, in input order: [1.8, 0.1, -0.2]; [1.65, 0.35, -0.1]; [1.65, -0.05, 0.15]; [1.7, 0.05, -0.05]. With centering enabled, p = softmax((t − c)/τ); otherwise c = 0. If temperature is disabled, τ = 1; if enabled, τ = 0.20. The student uses q = softmax(s/0.5).

At each step the student updates each logit as s ← s − 0.5(q − p)/(4 × 0.5), the gradient of mean cross-entropy with p fixed. Then t ← 0.96t + 0.04 new s and, when enabled, c ← 0.9c + 0.10 mean(previous t). The initial center is zero. This EMA applies to individual logits: in DINO the EMA applies to teacher-network parameters and its inputs are different views. The mechanisms can help in a particular recipe but do not guarantee avoidance of all collapse.

0.20
120
Mean per-sample entropy0.0032 nats
Marginal entropy1.0399 nats
Entropy difference1.0367 nats
Teacher-to-student KL0.01856 nats
An explicit logit model lets you compare entropies and divergence without attributing its trajectories to real training.

It is also insufficient to observe small KL divergence between teacher and student. Both could agree on a different distribution for each image. To study the representation, compare mean per-image entropy with entropy of the mean distribution across images, and observe variation between examples. A confident head that always assigns the same class has low entropy both per image and marginally; a constant uniform output has both high. These summaries diagnose output patterns, not guarantee that features capture useful semantics.

Attention and useful representation

In DINO experiments, some ViT attention heads reveal regions corresponding to objects. Emergent attention segmentation requires specifying image, head, resolution and threshold. An attention map is not automatically a causal explanation or calibrated semantic mask. If calculating IoU, state the reference mask and binarization procedure; choosing head and threshold on test biases evaluation.

As a descriptive analysis, DINO Figure 4 reports Pascal VOC 2012 validation Jaccard indices for ViT-S/16 of 22.0% with random weights, 27.3% with supervision and 45.9% with DINO. The figure text says 60% of attention mass is retained and shows the best head on the images; the appendix, however, repeats those values and says 80%. This source discrepancy prevents confidently attributing the table’s threshold. Choosing a head on the same data also limits interpretation of the visualizations.

InteractiveAttention that appears to segment
Oxford-IIIT Pet image

CLS attention to the 196 patches is sorted and the shortest prefix reaching the requested mass selected. IoU compares that patch mask against the animal trimap and excludes ambiguous pixels. Sample: data/train-00000-of-00003.parquet:965.

The head and threshold are exploratory on one image, so IoU is not a performance estimate. Models have different sizes and pretraining; the comparison does not isolate the self-supervised objective. High attention is not a causal explanation either.

Photograph data/train-00000-of-00003.parquet:965, original SHA-256 bc4860dbafa13328438ec7d7484f13b971d2beb09cecf035d47aa3d1ae979058: Oxford-IIIT Pet, Parkhi, Vedaldi, Zisserman and Jawahar, CC BY-SA 4.0; rights belong to the original owners. Selected model: facebook/dino-vits16, revision abe3b354cb6a9b6f146096b14a4a9d7eecbcb4bd. Fixed weights: DINO ViT-S/16 and supervised ViT-B/16.

ViT weights
1
60
CLS attention to itself5.55 %
Retained patch mass60.85 %
Selected patches12 / 196
Animal IoU on this image23.11 %
Compare DINO and supervised ViT heads, select an attention mass and contrast its patch mask with a real trimap.

This figure’s IoU is calculated at pixel level after expanding selected patches and excluding the trimap’s ambiguous band. Choosing a head and threshold on these images is exploratory, not an evaluation of generalization. The two checkpoints differ in both architecture and training, so their differences do not isolate the DINO objective’s effect.

To evaluate frozen features, a linear probe trains a head without updating the encoder. A k-NN evaluation normalizes features, finds neighbors in a separate training base and combines their labels; results depend on kk, temperature, representation and preprocessing. Tune hyperparameters on validation, not test. Linear probing, k-NN and fine-tuning measure related but distinct properties, so they do not necessarily rank all methods alike.

iBOT combines self-distillation with prediction on masked patches using a teacher as an online tokenizer. For the patch objective, student and teacher receive the same global crop, but only the student’s patches are hidden; the class token is also distilled across global views. It is not simply MAE with a different label. In iBOT Tables 1 and 2, ViT-B/16 pretrained on ImageNet-1K obtains 77.1% with k-NN, 79.5% with a linear probe and 84.0% after fine-tuning. The paper states 400 training epochs, counted as 1,600 effective epochs when summing views. These measures are not interchangeable, and comparing with another method requires matching protocols. These ideas connect to the visual encoders studied in the next lesson.

Labs

Visualize published checkpoints

This cell reproduces the two figures’ data with PyTorch, Pillow, numpy, pyarrow, huggingface_hub and transformers. It downloads pinned checkpoints and an Oxford-IIIT Pet split into the usual caches. The first run uses the first image; for the second, set ORYON_OTHER_SAMPLE=1 and change ORYON_VISUAL_SSL_DIR to retain both outputs. Attention distributions and the mask are calculated in the same geometry; neither images nor their masks train the model.

[ ]MAE and pretrained checkpoint attentionLocal GPU
"""Comparación visual de MAE, DINO y ViT supervisado sobre Oxford-IIIT Pet.

Descarga los tres checkpoints fijados en la caché común de Hugging Face.
Los mapas de atención no son explicaciones causales y la IoU es descriptiva
para una imagen de la validación corta de m16-l19. Para la segunda imagen de
la galería, ejecuta de nuevo con ORYON_OTHER_SAMPLE=1 y otra carpeta de salida.
No se selecciona el umbral mediante test.
"""
import base64
import hashlib
import io
import json
import os
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
from PIL import Image
from huggingface_hub import hf_hub_download
import torch
import transformers
from transformers import AutoImageProcessor, AutoModel, AutoModelForPreTraining

torch.set_num_threads(1)
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
OUT = Path(os.environ.get('ORYON_VISUAL_SSL_DIR', 'oryon-ssl-visual'))
DATASET = 'dpdl-benchmark/oxford_iiit_pet'
DATA_REVISION = '18515194612b584bf54692372ac035ef773a5b41'
FILE = 'data/train-00000-of-00003.parquet'
FILE_HASH = '473606455eb66b1ee9b2a8675e41bf8c7494370fc27eccc5eae5890f882b7442'
ROW = 965
MODELS = {
    'mae': ('facebook/vit-mae-base', '25b184bea5538bf5c4c852c79d221195fdd2778d'),
    'dino': ('facebook/dino-vits16', 'abe3b354cb6a9b6f146096b14a4a9d7eecbcb4bd'),
    'supervisado': ('google/vit-base-patch16-224', '3f49326eb077187dfe1c2a2bb15fbd74e6ab91e3'),
}


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


def data_url(image, format='PNG'):
    buf = io.BytesIO()
    image.save(buf, format=format, **({'quality': 85} if format == 'JPEG' else {}))
    return f'data:image/{format.lower()};base64,' + base64.b64encode(buf.getvalue()).decode('ascii')


def sample():
    path = hf_hub_download(repo_id=DATASET, repo_type='dataset', revision=DATA_REVISION, filename=FILE)
    if digest(path) != FILE_HASH:
        raise ValueError('El parquet no coincide con el hash fijado')
    table = pq.ParquetFile(path)
    # Reconstruye la validación corta vigente de m16-l19, no la partición completa.
    order = np.random.default_rng(16190).permutation(table.metadata.num_rows)
    row_index = next(int(value) for value in order[32:40] if value != ROW) if os.environ.get('ORYON_OTHER_SAMPLE') == '1' else ROW
    if row_index not in order[32:40]:
        raise ValueError('La fila no pertenece a la validación corta de m16-l19')
    offset = 0
    for batch in table.iter_batches(batch_size=16, columns=['image', 'segmentation_mask']):
        if offset <= row_index < offset + batch.num_rows:
            item = batch.slice(row_index-offset, 1).to_pylist()[0]
            blob = item['image']['bytes']
            image = Image.open(io.BytesIO(blob)).convert('RGB').resize((224, 224), Image.Resampling.BILINEAR)
            mask = Image.open(io.BytesIO(item['segmentation_mask']['bytes'])).resize((224, 224), Image.Resampling.NEAREST)
            truth = np.asarray(mask, dtype=np.uint8)
            if not set(np.unique(truth)) <= {1, 2, 3}:
                raise ValueError('La máscara no es un trimap 1/2/3')
            return image, mask, hashlib.sha256(blob).hexdigest(), row_index
        offset += batch.num_rows
    raise ValueError('No existe la fila seleccionada')


def model_inputs(model_id, revision, image):
    processor = AutoImageProcessor.from_pretrained(model_id, revision=revision)
    if getattr(processor, 'do_center_crop', False):
        raise ValueError('La referencia no contempla un recorte adicional de la imagen')
    pixels = processor(images=image, return_tensors='pt')['pixel_values'].to(DEVICE)
    if tuple(pixels.shape) != (1, 3, 224, 224):
        raise ValueError('Tamaño inesperado tras el preprocesado')
    return processor, pixels


def reconstructions(image):
    model_id, revision = MODELS['mae']
    processor, pixels = model_inputs(model_id, revision, image)
    model = AutoModelForPreTraining.from_pretrained(model_id, revision=revision).to(DEVICE).eval()
    if model.config.norm_pix_loss:
        raise ValueError('Esta visualización espera un checkpoint de píxeles sin normalizar por parche')
    patch_count = model.vit.embeddings.patch_embeddings.num_patches
    generator = torch.Generator(device=DEVICE.type).manual_seed(162351)
    noise = torch.rand((1, patch_count), generator=generator, device=DEVICE)
    mean = torch.tensor(processor.image_mean, device=DEVICE).view(1, 3, 1, 1)
    std = torch.tensor(processor.image_std, device=DEVICE).view(1, 3, 1, 1)
    original = (pixels * std + mean).clamp(0, 1)
    rows = []
    with torch.no_grad():
        for ratio in (0., .05, .25, .5, .75, .95):
            if ratio == 0.:
                # Sin parches ocultos la pérdida media está indefinida. Todos
                # los píxeles mostrados proceden de la entrada visible.
                panel = torch.cat([original, original, original], dim=3)
                pixels_uint8 = (panel[0].permute(1, 2, 0).cpu().numpy() * 255).round().astype(np.uint8)
                rows.append({'ratio': ratio, 'hidden_patches': 0, 'total_patches': patch_count,
                             'normalized_mse': None, 'image': data_url(Image.fromarray(pixels_uint8), 'JPEG')})
                continue
            model.config.mask_ratio = ratio
            result = model(pixel_values=pixels, noise=noise)
            if not torch.isfinite(result.loss) or not torch.isfinite(result.logits).all():
                raise ValueError('Salida MAE no finita')
            prediction = model.unpatchify(result.logits)
            mask = result.mask.reshape(1, 1, 14, 14).repeat_interleave(16, 2).repeat_interleave(16, 3)
            decoded = (prediction * std + mean).clamp(0, 1)
            visual = torch.where(mask.bool(), decoded, original)
            masked = torch.where(mask.bool(), .5, original)
            panel = torch.cat([original, masked, visual], dim=3)
            pixels_uint8 = (panel[0].permute(1, 2, 0).cpu().numpy() * 255).round().astype(np.uint8)
            rows.append({'ratio': ratio, 'hidden_patches': int(result.mask.sum()),
                         'total_patches': patch_count, 'normalized_mse': float(result.loss),
                         'image': data_url(Image.fromarray(pixels_uint8), 'JPEG')})
    del model
    if DEVICE.type == 'cuda': torch.cuda.empty_cache()
    return rows


def attention(model_key, image):
    model_id, revision = MODELS[model_key]
    _, pixels = model_inputs(model_id, revision, image)
    model = AutoModel.from_pretrained(model_id, revision=revision, attn_implementation='eager', add_pooling_layer=False).to(DEVICE).eval()
    with torch.no_grad():
        outputs = model(pixel_values=pixels, output_attentions=True)
        if not outputs.attentions:
            raise ValueError('El modelo no devolvió atención por cabeza')
        weights = outputs.attentions[-1][0, :, 0].detach().cpu()
    if weights.shape[-1] != 197 or not torch.isfinite(weights).all():
        raise ValueError('Se esperaba CLS y 196 parches finitos')
    if not torch.allclose(weights.sum(dim=1), torch.ones(weights.shape[0]), atol=1e-5):
        raise ValueError('Las distribuciones de atención no suman uno')
    data = {'config': model_key, 'model': model_id, 'revision': revision,
            'head_cls_mass': weights[:, 0].tolist(),
            'head_patch_attention': weights[:, 1:].reshape(-1, 14, 14).tolist()}
    del model, outputs
    if DEVICE.type == 'cuda': torch.cuda.empty_cache()
    return data


def main():
    image, truth, image_hash, row_index = sample()
    patches = np.asarray(truth).reshape(14, 16, 14, 16).transpose(0, 2, 1, 3).reshape(196, 256)
    patch_counts = np.stack(((patches == 1).sum(axis=1), (patches != 3).sum(axis=1)), axis=1).tolist()
    result = {'dataset': DATASET, 'dataset_revision': DATA_REVISION, 'source': f'{FILE}:{row_index}',
              'source_sha256': image_hash, 'original': data_url(image, 'JPEG'), 'truth': data_url(truth),
              'mask_values': {'animal': 1, 'background': 2, 'ambiguous_ignored': 3},
              'truth_patch_counts': patch_counts,
              'software': {'torch': str(torch.__version__), 'transformers': transformers.__version__, 'numpy': np.__version__},
              'models': {key: {'id': value[0], 'revision': value[1]} for key, value in MODELS.items()},
              'protocol': 'Una imagen de la validación corta de m16-l19; sin ajuste de cabeza ni umbral. La comparación es descriptiva y '
                          'los modelos difieren en tamaño, datos de preentrenamiento y objetivo.'}
    result['reconstructions'] = reconstructions(image)
    result['attention'] = [attention(key, image) for key in ('dino', 'supervisado')]
    OUT.mkdir(parents=True, exist_ok=True)
    (OUT / 'visual-results.json').write_text(json.dumps(result, ensure_ascii=False), encoding='utf-8')
    print('Inferencias guardadas en', 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.

MAE from scratch

The first cell needs PyTorch, numpy, pyarrow, Pillow and huggingface_hub. It uses CIFAR-10: labels stratify splits and are reserved for supervised evaluation, but do not enter pretraining loss. The encoder receives CLS and only visible patches; this simplified decoder discards CLS. Loss uses only hidden patches normalized with population variance, while the original code uses variance correction. It then compares linear probing and fine-tuning, selecting on validation and leaving test exploratory.

The RGB panel denormalizes predictions with the true mean and standard deviation of hidden patches: this is a visualization using reference information, not an autonomous reconstruction from visible patches. The pipeline was checked with ORYON_VERIFY_SHORT=1, which limits data and uses two steps per stage; this test does not demonstrate convergence.

[ ]MAE with hidden patchesLocal GPU
"""MAE educativo en CIFAR-10 con sonda lineal y ajuste fino.

Requiere torch, numpy, pyarrow, Pillow y huggingface_hub. La primera ejecución
descarga CIFAR-10 a la caché común. ORYON_VERIFY_SHORT=1 limita datos y pasos.
Las posiciones aprendidas y el tamaño reducido son adaptaciones, no el MAE del
artículo. Se usan etiquetas para estratificar los splits, pero no en la pérdida
del preentrenamiento. El decoder no recibe CLS; la varianza por parche es
poblacional, a diferencia del cálculo con corrección del código original.
Fuente del método:
https://arxiv.org/abs/2111.06377 .
"""
import io
import json
import os
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
from PIL import Image
from huggingface_hub import hf_hub_download
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, TensorDataset

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_MAE_DIR', 'oryon-mae'))


def group_indices(split, seed):
    path = hf_hub_download(repo_id='uoft-cs/cifar10', repo_type='dataset', revision='0b27149',
                           filename=f'plain_text/{split}-00000-of-00001.parquet')
    labels = np.concatenate([b.column(0).to_numpy() for b in
                             pq.ParquetFile(path).iter_batches(batch_size=1024, columns=['label'])]).astype(np.int64)
    rng = np.random.default_rng(seed)
    return path, labels, [rng.permutation(np.flatnonzero(labels == i)) for i in range(10)]


def load_selected(path, labels, indices):
    images = np.empty((len(indices), 3, 32, 32), dtype=np.uint8)
    positions = {int(index): j for j, index in enumerate(indices)}
    found = np.zeros(len(indices), dtype=bool)
    offset = 0
    for batch in pq.ParquetFile(path).iter_batches(batch_size=256, columns=['img']):
        for j in range(batch.num_rows):
            pos = positions.get(offset + j)
            if pos is not None:
                with Image.open(io.BytesIO(batch.column(0)[j].as_py()['bytes'])) as image:
                    images[pos] = np.asarray(image.convert('RGB'), dtype=np.uint8).transpose(2, 0, 1)
                found[pos] = True
        offset += batch.num_rows
    if not found.all():
        raise ValueError('Faltan imágenes del subconjunto')
    return torch.from_numpy(images), torch.from_numpy(labels[indices].copy())


def datasets():
    train_path, labels, train_groups = group_indices('train', 16070)
    test_path, test_labels, test_groups = group_indices('test', 16074)
    ntrain, valid_start, nvalid, ntest = (8, 100, 2, 2) if SHORT else (4500, 4500, 500, 1000)
    ids_train = np.concatenate([g[:ntrain] for g in train_groups])
    ids_valid = np.concatenate([g[valid_start:valid_start+nvalid] for g in train_groups])
    ids_test = np.concatenate([g[60:60+ntest] if SHORT else g[:ntest] for g in test_groups])
    if set(ids_train) & set(ids_valid):
        raise ValueError('Train y validación se solapan')
    train = load_selected(train_path, labels, ids_train)
    valid = load_selected(train_path, labels, ids_valid)
    test = load_selected(test_path, test_labels, ids_test)
    return train, valid, test, {'train': ids_train.tolist(), 'valid': ids_valid.tolist(), 'test': ids_test.tolist()}


def patchify(x, patch=4):
    b, c, h, w = x.shape
    if h != w or h % patch:
        raise ValueError('La imagen debe ser cuadrada y divisible por el parche')
    side = h // patch
    return x.reshape(b, c, side, patch, side, patch).permute(0, 2, 4, 1, 3, 5).reshape(b, side * side, c * patch * patch)


def unpatchify(x, patch=4):
    b, n, d = x.shape
    side = int(n ** .5)
    if side * side != n or d != 3 * patch * patch:
        raise ValueError('Número o dimensión de parches incompatible')
    return x.reshape(b, side, side, 3, patch, patch).permute(0, 3, 1, 4, 2, 5).reshape(b, 3, side * patch, side * patch)


class Stack(nn.Module):
    def __init__(self, dim, depth, heads):
        super().__init__()
        self.layers = nn.ModuleList([nn.TransformerEncoderLayer(dim, heads, 4 * dim, dropout=0.,
                          activation='gelu', batch_first=True, norm_first=True, layer_norm_eps=1e-6)
                          for _ in range(depth)])
        self.norm = nn.LayerNorm(dim, eps=1e-6)

    def forward(self, x):
        for layer in self.layers:
            x = layer(x)
        return self.norm(x)


class MAE(nn.Module):
    def __init__(self, patch=4, dim=192, decoder_dim=96, ratio=.75):
        super().__init__()
        self.patch, self.ratio, self.n = patch, ratio, (32 // patch) ** 2
        self.embed = nn.Linear(3 * patch * patch, dim)
        self.pos = nn.Parameter(torch.zeros(1, self.n, dim))
        self.cls = nn.Parameter(torch.zeros(1, 1, dim))
        self.enc = Stack(dim, 4, 3)
        self.to_decoder = nn.Linear(dim, decoder_dim)
        self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_dim))
        self.decoder_pos = nn.Parameter(torch.zeros(1, self.n, decoder_dim))
        self.dec = Stack(decoder_dim, 2, 3)
        self.predict = nn.Linear(decoder_dim, 3 * patch * patch)
        for parameter in (self.pos, self.cls, self.mask_token, self.decoder_pos):
            nn.init.trunc_normal_(parameter, std=.02)

    def encode_all(self, images):
        tokens = self.embed(patchify(images, self.patch)) + self.pos
        return self.enc(torch.cat((self.cls.expand(len(images), -1, -1), tokens), dim=1))[:, 0]

    def forward(self, images, generator):
        targets = patchify(images, self.patch)
        b, n, _ = targets.shape
        keep = int(n * (1 - self.ratio))
        if not 0 < keep < n:
            raise ValueError('La máscara debe dejar parches visibles y ocultos')
        order = torch.rand((b, n), device=images.device, generator=generator).argsort(dim=1)
        restore = order.argsort(dim=1)
        ids = order[:, :keep]
        embeddings = self.embed(targets) + self.pos
        visible = torch.gather(embeddings, 1, ids.unsqueeze(-1).expand(-1, -1, embeddings.shape[-1]))
        encoded = self.enc(torch.cat((self.cls.expand(b, -1, -1), visible), dim=1))[:, 1:]
        decoded = self.to_decoder(encoded)
        tokens = torch.cat((decoded, self.mask_token.expand(b, n - keep, -1)), dim=1)
        tokens = torch.gather(tokens, 1, restore.unsqueeze(-1).expand(-1, -1, tokens.shape[-1]))
        prediction = self.predict(self.dec(tokens + self.decoder_pos))
        mask = torch.ones((b, n), dtype=torch.bool, device=images.device)
        mask.scatter_(1, ids, False)
        mean = targets.mean(dim=-1, keepdim=True)
        std = (targets.var(dim=-1, keepdim=True, unbiased=False) + 1e-6).sqrt()
        normalized = (targets - mean) / std
        per_patch = (prediction - normalized).square().mean(dim=-1)
        loss = per_patch[mask].mean()
        return loss, prediction, mask, mean, std


def loader(data, batch, seed, shuffle):
    return DataLoader(TensorDataset(*data), batch_size=batch, shuffle=shuffle,
                      generator=torch.Generator().manual_seed(seed), num_workers=0)


@torch.no_grad()
def reconstruction_loss(model, data, seed):
    model.eval()
    rng = torch.Generator(device=DEVICE.type).manual_seed(seed)
    weighted, count = 0., 0
    for x, _ in loader(data, 16 if SHORT else 128, seed, False):
        x = x.to(DEVICE).float() / 255.
        loss, _, _, _, _ = model(x, rng)
        if not torch.isfinite(loss):
            raise FloatingPointError('Pérdida de reconstrucción no finita')
        weighted += float(loss) * len(x)
        count += len(x)
    return weighted / count


@torch.no_grad()
def classification_accuracy(model, head, data):
    model.eval(); head.eval()
    correct, count = 0, 0
    for x, y in loader(data, 16 if SHORT else 128, 0, False):
        logits = head(model.encode_all(x.to(DEVICE).float() / 255.))
        if not torch.isfinite(logits).all():
            raise FloatingPointError('Logits de la sonda no finitos')
        correct += int((logits.argmax(-1).cpu() == y).sum())
        count += len(y)
    return correct / count


def evaluate_classifier(model, initial, train, valid, test, finetune):
    model.load_state_dict(initial)
    model.requires_grad_(finetune)
    torch.manual_seed(16236)
    head = nn.Linear(192, 10).to(DEVICE)
    parameters = list(head.parameters())
    if finetune:
        parameters += list(model.embed.parameters()) + [model.pos, model.cls] + list(model.enc.parameters())
    optimizer = torch.optim.AdamW(parameters, lr=1e-4 if finetune else 1e-3, weight_decay=.01)
    best, best_model, best_head, history = -1., None, None, []
    steps = 0
    for epoch in range(1 if SHORT else (20 if finetune else 10)):
        model.train(finetune); head.train()
        for x, y in loader(train, 8 if SHORT else 128, 16237 + epoch, True):
            x, y = x.to(DEVICE).float() / 255., y.to(DEVICE)
            with torch.set_grad_enabled(finetune):
                features = model.encode_all(x)
            logits = head(features)
            loss = F.cross_entropy(logits, y)
            if not torch.isfinite(loss):
                raise FloatingPointError('Pérdida supervisada no finita')
            optimizer.zero_grad(set_to_none=True); loss.backward()
            if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in parameters):
                raise FloatingPointError('Gradiente no finito')
            optimizer.step(); steps += 1
            if SHORT and steps >= 2:
                break
        val = classification_accuracy(model, head, valid)
        history.append({'epoch': epoch + 1, 'steps': steps, 'validation_accuracy': val})
        if val > best:
            best = val
            best_model = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
            best_head = {k: v.detach().cpu().clone() for k, v in head.state_dict().items()}
    model.load_state_dict(best_model); head.load_state_dict(best_head)
    return {'finetune': finetune, 'history': history,
            'test_exploratory': classification_accuracy(model, head, test)}


def main():
    train, valid, test, splits = datasets()
    torch.manual_seed(16230)
    model = MAE().to(DEVICE)
    probe = torch.rand((2, 3, 32, 32), device=DEVICE)
    torch.testing.assert_close(unpatchify(patchify(probe)), probe)
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=.05)
    rng = torch.Generator(device=DEVICE.type).manual_seed(16231)
    best, best_state, history, steps = float('inf'), None, [], 0
    for epoch in range(1 if SHORT else 100):
        model.train()
        loss_sum, seen = 0., 0
        for x, _ in loader(train, 8 if SHORT else 128, 16232 + epoch, True):
            x = x.to(DEVICE).float() / 255.
            loss, _, mask, _, _ = model(x, rng)
            if not torch.isfinite(loss) or not bool((mask.sum(1) == 48).all()):
                raise ValueError('Pérdida no finita o cantidad incorrecta de máscaras')
            optimizer.zero_grad(set_to_none=True); loss.backward()
            if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in model.parameters()):
                raise FloatingPointError('Gradiente MAE no finito')
            optimizer.step(); steps += 1
            loss_sum += float(loss.detach()) * len(x); seen += len(x)
            if SHORT and steps >= 2:
                break
        val = reconstruction_loss(model, valid, 16233)
        history.append({'epoch': epoch + 1, 'steps': steps, 'train_loss': loss_sum / seen, 'validation_loss': val})
        print('MAE', history[-1])
        if val < best:
            best = val
            best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
    model.load_state_dict(best_state)
    test_loss = reconstruction_loss(model, test, 16234)
    OUT.mkdir(parents=True, exist_ok=True)
    with torch.no_grad():
        image = test[0][0:1].to(DEVICE).float() / 255.
        patches = patchify(image)
        # La desnormalización usa media/desviación del parche real, solo para
        # visualizar: no es una reconstrucción RGB autónoma a partir de visibles.
        reconstructions = []
        for ratio in (.05, .25, .5, .75, .95):
            model.ratio = ratio
            loss, pred, mask, mean, std = model(image, torch.Generator(device=DEVICE.type).manual_seed(16235))
            restored = torch.where(mask.unsqueeze(-1), pred * std + mean, patches)
            hidden = torch.where(mask.unsqueeze(-1), torch.full_like(patches, .5), patches)
            panel = torch.cat((image, unpatchify(hidden), unpatchify(restored).clamp(0, 1)), dim=-1)
            filename = f'reconstruccion-{int(ratio * 100):02d}.png'
            Image.fromarray((panel[0].permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8)).save(OUT / filename)
            reconstructions.append({'ratio': ratio, 'hidden_patches': int(mask.sum()),
                                    'total_patches': mask.shape[1], 'normalized_mse': float(loss), 'image': filename})
        model.ratio = .75
    linear = evaluate_classifier(model, best_state, train, valid, test, False)
    fine = evaluate_classifier(model, best_state, train, valid, test, True)
    result = {'short': SHORT, 'dataset': 'uoft-cs/cifar10@0b27149', 'split_seed': [16070, 16074],
              'indices': splits, 'mask_ratio': .75, 'history': history, 'test_reconstruction_exploratory': test_loss,
              'linear_probe': linear, 'finetune': fine, 'reconstructions': reconstructions,
              'note': 'Prueba corta no concluyente; test exploratorio. Imagen RGB desnormalizada con estadísticas reales del parche oculto.'}
    (OUT / 'results.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
    print('Sonda:', linear, 'ajuste fino:', fine, '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.

DINO at small scale

This cell needs PyTorch, numpy, pyarrow, Pillow and huggingface_hub. It uses a custom small ViT on STL-10’s labeled training set: labels stratify splits but do not enter self-supervised loss. It does not use the 100,000 unlabeled images or reproduce DINO’s complete ImageNet recipe. Validation and test are separate and test is exploratory; indices and hashes are saved.

The student processes two global and two local views; the EMA teacher processes only global views. Loss omits same-view pairs. Center and temperature are compared without assuming they prevent collapse. k-NN votes with exponential cosine weights and temperature 0.07; the linear probe is selected by validation. Maps are CLS token attention, not causal explanations. The checked run with ORYON_VERIFY_SHORT=1 limits data and performs two steps per configuration; it verifies the pipeline without demonstrating convergence.

[ ]DINO with multiple views and EMA teacherLocal GPU
"""DINO educativo en STL-10: multivistas, EMA, centrado, k-NN y sonda lineal.

Requiere PyTorch, torchvision, numpy, pyarrow, Pillow y huggingface_hub. Usa solo
el train etiquetado de STL-10, usando las etiquetas para estratificar los splits
pero no en la pérdida de preentrenamiento;
no usa sus 100 000 imágenes sin etiqueta ni reproduce el protocolo ImageNet de
DINO. El k-NN usa voto exponencial del coseno con temperatura declarada.
Reservamos validación y test. ORYON_VERIFY_SHORT=1 verifica el circuito
con pocos ejemplos/pasos y no permite juzgar convergencia o colapso.
Fuente: https://arxiv.org/abs/2104.14294 .
"""
import base64
import copy
import hashlib
import io
import json
import os
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
from PIL import Image
from huggingface_hub import hf_hub_download
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, TensorDataset

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_DINO_DIR', 'oryon-dino'))
REPO = 'mteb/stl10'
REVISION = '2da456fe65204f88c2cb5e5ff17f85f442ef3eaa'
HASHES = {'train': 'b450f19e41454731be0bcddc7093fcf9793fe9b64ea795e6ef18ca77f34c353d',
          'test': '298b23e983c755dfba2c69dec181340221deb1a5ad6651990c7c5c559fb892be'}


def file_sha(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 file_and_labels(split):
    path = hf_hub_download(repo_id=REPO, repo_type='dataset', revision=REVISION,
                           filename=f'data/{split}-00000-of-00001.parquet')
    digest = file_sha(path)
    if digest != HASHES[split]:
        raise ValueError(f'El SHA-256 de {split} no coincide con el publicado')
    labels = np.concatenate([batch.column(0).to_numpy() for batch in
               pq.ParquetFile(path).iter_batches(batch_size=1024, columns=['label'])]).astype(np.int64)
    return path, labels


def load_images(path, labels, indices):
    images = np.empty((len(indices), 3, 96, 96), dtype=np.uint8)
    digests = [None] * len(indices)
    slots = {int(idx): i for i, idx in enumerate(indices)}
    offset = 0
    for batch in pq.ParquetFile(path).iter_batches(batch_size=128, columns=['image']):
        for j in range(batch.num_rows):
            pos = slots.get(offset + j)
            if pos is not None:
                blob = batch.column(0)[j].as_py()['bytes']
                if blob is None:
                    raise ValueError('Imagen sin bytes')
                digests[pos] = hashlib.sha256(blob).hexdigest()
                with Image.open(io.BytesIO(blob)) as image:
                    pixels = np.asarray(image.convert('RGB'), dtype=np.uint8)
                    if pixels.shape != (96, 96, 3):
                        raise ValueError(f'Tamaño STL inesperado: {pixels.shape}')
                    images[pos] = pixels.transpose(2, 0, 1)
        offset += batch.num_rows
    if any(value is None for value in digests):
        raise ValueError('Faltan imágenes')
    return (torch.from_numpy(images), torch.from_numpy(labels[indices].copy())), digests


def dataset():
    train_path, labels = file_and_labels('train')
    test_path, test_labels = file_and_labels('test')
    rng = np.random.default_rng(16240)
    groups = [rng.permutation(np.flatnonzero(labels == c)) for c in range(10)]
    rng_test = np.random.default_rng(16241)
    test_groups = [rng_test.permutation(np.flatnonzero(test_labels == c)) for c in range(10)]
    ntrain, nvalid, ntest = (4, 2, 2) if SHORT else (450, 50, 800)
    ids_train = np.concatenate([g[:ntrain] for g in groups])
    ids_valid = np.concatenate([g[450:450+nvalid] for g in groups])
    ids_test = np.concatenate([g[:ntest] for g in test_groups])
    if set(ids_train) & set(ids_valid):
        raise ValueError('Train y validación se solapan')
    train, train_hash = load_images(train_path, labels, ids_train)
    valid, valid_hash = load_images(train_path, labels, ids_valid)
    test, test_hash = load_images(test_path, test_labels, ids_test)
    if set(train_hash) & set(valid_hash) or set(train_hash) & set(test_hash) or set(valid_hash) & set(test_hash):
        raise ValueError('Imágenes con bytes idénticos entre particiones')
    meta = {'train': ids_train.tolist(), 'valid': ids_valid.tolist(), 'test': ids_test.tolist(),
            'image_sha256': {'train': train_hash, 'valid': valid_hash, 'test': test_hash},
            'split_seed': [16240, 16241], 'parquet_sha256': HASHES}
    return train, valid, test, meta


def loader(data, batch, seed, shuffle):
    return DataLoader(TensorDataset(*data), batch_size=batch, shuffle=shuffle,
                      generator=torch.Generator().manual_seed(seed), num_workers=0)


class Attention(nn.Module):
    def __init__(self, dim=192, heads=3):
        super().__init__()
        self.heads, self.d = heads, dim // heads
        self.qkv = nn.Linear(dim, 3 * dim)
        self.proj = nn.Linear(dim, dim)
        self.last = None
        self.capture = False

    def forward(self, x):
        b, n, dim = x.shape
        qkv = self.qkv(x).reshape(b, n, 3, self.heads, self.d).permute(2, 0, 3, 1, 4)
        q, k, v = qkv.unbind(0)
        attn = ((q * self.d ** -.5) @ k.transpose(-1, -2)).softmax(-1)
        if self.capture:
            self.last = attn.detach()
        return self.proj((attn @ v).transpose(1, 2).reshape(b, n, dim))


class Block(nn.Module):
    def __init__(self, dim=192, heads=3):
        super().__init__()
        self.norm1, self.norm2 = nn.LayerNorm(dim, eps=1e-6), nn.LayerNorm(dim, eps=1e-6)
        self.attn = Attention(dim, heads)
        self.mlp = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))

    def forward(self, x):
        x = x + self.attn(self.norm1(x))
        return x + self.mlp(self.norm2(x))


class TinyDINO(nn.Module):
    def __init__(self):
        super().__init__()
        self.embed = nn.Conv2d(3, 192, 8, stride=8)
        self.cls = nn.Parameter(torch.zeros(1, 1, 192))
        self.pos = nn.Parameter(torch.zeros(1, 65, 192))
        self.blocks = nn.ModuleList([Block() for _ in range(4)])
        self.norm = nn.LayerNorm(192, eps=1e-6)
        self.head = nn.Sequential(nn.Linear(192, 512), nn.GELU(), nn.Linear(512, 256))
        nn.init.trunc_normal_(self.cls, std=.02)
        nn.init.trunc_normal_(self.pos, std=.02)

    def features(self, x):
        x = self.embed(x)
        b, d, h, w = x.shape
        positions = self.pos[:, 1:].transpose(1, 2).reshape(1, d, 8, 8)
        if (h, w) != (8, 8):
            positions = F.interpolate(positions, size=(h, w), mode='bicubic', align_corners=False)
        x = x.flatten(2).transpose(1, 2) + positions.flatten(2).transpose(1, 2)
        x = torch.cat((self.cls.expand(b, -1, -1) + self.pos[:, :1], x), dim=1)
        for block in self.blocks:
            x = block(x)
        return self.norm(x)[:, 0]

    def forward(self, x):
        return self.head(self.features(x))


def make_view(images, out_size, min_side, max_side, generator):
    # Recorte aleatorio por imagen, volteo y resize: dos vistas globales y dos locales.
    views = []
    for image in images:
        side = int(torch.randint(min_side, max_side + 1, (), generator=generator))
        y = int(torch.randint(0, 96 - side + 1, (), generator=generator))
        x = int(torch.randint(0, 96 - side + 1, (), generator=generator))
        crop = image[:, y:y+side, x:x+side].unsqueeze(0)
        if bool(torch.rand((), generator=generator) < .5):
            crop = crop.flip(-1)
        views.append(F.interpolate(crop, size=(out_size, out_size), mode='bilinear', align_corners=False))
    return torch.cat(views, dim=0) * 2 - 1


def dino_loss(student_outputs, teacher_outputs, center, teacher_temp, student_temp=.1):
    with torch.no_grad():
        targets = [((output - center) / teacher_temp).softmax(-1) for output in teacher_outputs]
    losses = []
    for teacher_idx, target in enumerate(targets):
        for student_idx, logits in enumerate(student_outputs):
            if student_idx != teacher_idx:
                losses.append(-(target * (logits / student_temp).log_softmax(-1)).sum(-1).mean())
    if len(losses) != 6:
        raise AssertionError('Se esperaban seis pares de vistas diferentes')
    return torch.stack(losses).mean(), targets


@torch.no_grad()
def update_teacher(student, teacher, momentum):
    for source, target in zip(student.parameters(), teacher.parameters()):
        target.mul_(momentum).add_(source, alpha=1 - momentum)


@torch.no_grad()
def embeddings(model, data):
    model.eval()
    features, labels = [], []
    for x, y in loader(data, 16 if SHORT else 64, 0, False):
        x = F.interpolate(x.to(DEVICE).float() / 255., (64, 64), mode='bilinear', align_corners=False) * 2 - 1
        z = model.features(x)
        if not torch.isfinite(z).all():
            raise FloatingPointError('Representación no finita')
        features.append(z.cpu()); labels.append(y)
    return torch.cat(features), torch.cat(labels)


def knn(train_features, train_labels, query_features, query_labels, k=5, temperature=.07):
    if not 1 <= k <= len(train_features) or not 0 < temperature < float('inf'):
        raise ValueError('Número de vecinos o temperatura inválidos')

    def unit_features(features):
        features = features.to(DEVICE)
        norms = torch.linalg.vector_norm(features, dim=1, keepdim=True)
        if not torch.isfinite(norms).all() or bool((norms == 0).any()):
            raise ValueError('El coseno necesita vectores finitos de norma no nula')
        return features / norms

    train_features = unit_features(train_features)
    train_labels = train_labels.to(DEVICE)
    correct = 0
    for start in range(0, len(query_features), 128):
        queries = unit_features(query_features[start:start+128])
        scores = queries @ train_features.T
        similarities, neighbours = scores.topk(k, dim=1)
        # Restar el máximo por consulta no cambia el voto ganador y evita overflow.
        weights = ((similarities - similarities.max(dim=1, keepdim=True).values) / temperature).exp()
        votes = (F.one_hot(train_labels[neighbours], num_classes=10) * weights.unsqueeze(-1)).sum(dim=1)
        correct += int((votes.argmax(dim=1).cpu() == query_labels[start:start+128]).sum())
    return correct / len(query_features)


def probe(train_features, train_labels, valid_features, valid_labels, test_features, test_labels):
    torch.manual_seed(16247)
    head = nn.Linear(train_features.shape[1], 10).to(DEVICE)
    optimizer = torch.optim.AdamW(head.parameters(), lr=1e-3)
    best, state, history, steps = -1., None, [], 0
    for epoch in range(1 if SHORT else 30):
        for x, y in loader((train_features, train_labels), 8 if SHORT else 128, 16248 + epoch, True):
            loss = F.cross_entropy(head(x.to(DEVICE)), y.to(DEVICE))
            if not torch.isfinite(loss):
                raise FloatingPointError('Pérdida de sonda no finita')
            optimizer.zero_grad(set_to_none=True); loss.backward(); optimizer.step()
            steps += 1
            if SHORT and steps >= 2:
                break
        with torch.no_grad():
            val = float((head(valid_features.to(DEVICE)).argmax(-1).cpu() == valid_labels).float().mean())
        history.append({'epoch': epoch + 1, 'steps': steps, 'validation_accuracy': val})
        if val > best:
            best = val
            state = {key: value.detach().cpu().clone() for key, value in head.state_dict().items()}
    head.load_state_dict(state)
    with torch.no_grad():
        test = float((head(test_features.to(DEVICE)).argmax(-1).cpu() == test_labels).float().mean())
    return {'history': history, 'test_exploratory': test}


def attention_example(model, data, sample_id):
    model.eval()
    block = model.blocks[-1]
    block.attn.capture = True
    x = F.interpolate(data[0][:1].to(DEVICE).float() / 255., (64, 64), mode='bilinear', align_corners=False) * 2 - 1
    with torch.no_grad():
        model.features(x)
    # CLS como consulta y 64 parches como claves, sin renormalizar: registrar
    # también la masa dirigida al propio CLS para que las sumas sean trazables.
    attn = block.attn.last[0, :, 0].cpu()
    block.attn.capture = False; block.attn.last = None
    image = Image.fromarray(data[0][0].permute(1, 2, 0).numpy())
    buffer = io.BytesIO(); image.save(buffer, format='PNG')
    return {'source_test_index': sample_id, 'image': 'data:image/png;base64,' + base64.b64encode(buffer.getvalue()).decode('ascii'),
            'head_cls_mass': attn[:, 0].tolist(), 'head_patch_attention': attn[:, 1:].reshape(3, 8, 8).tolist(),
            'note': 'Atención no equivale por sí sola a una explicación causal.'}


def run_configuration(name, use_center, teacher_temp, train, valid, test, test_id):
    torch.manual_seed(16242)
    student = TinyDINO().to(DEVICE)
    teacher = copy.deepcopy(student).to(DEVICE).eval().requires_grad_(False)
    optimizer = torch.optim.AdamW(student.parameters(), lr=5e-4, weight_decay=.04)
    center = torch.zeros((1, 256), device=DEVICE)
    # Las decisiones de recorte se toman en CPU para evitar una sincronización
    # CUDA por cada coordenada extraída con int() o bool().
    rng = torch.Generator().manual_seed(16243)
    history, steps = [], 0
    for epoch in range(1 if SHORT else 100):
        student.train()
        total, count, entropy = 0., 0, 0.
        for images, _ in loader(train, 4 if SHORT else 64, 16244 + epoch, True):
            images = images.to(DEVICE).float() / 255.
            views = [make_view(images, 64, 48, 96, rng), make_view(images, 64, 48, 96, rng),
                     make_view(images, 32, 24, 48, rng), make_view(images, 32, 24, 48, rng)]
            with torch.no_grad():
                teacher_logits = [teacher(view) for view in views[:2]]
            student_logits = [student(view) for view in views]
            loss, targets = dino_loss(student_logits, teacher_logits, center if use_center else 0., teacher_temp)
            if not torch.isfinite(loss):
                raise FloatingPointError('Pérdida DINO no finita')
            optimizer.zero_grad(set_to_none=True); loss.backward()
            if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in student.parameters()):
                raise FloatingPointError('Gradiente DINO no finito')
            optimizer.step()
            update_teacher(student, teacher, .996)
            with torch.no_grad():
                center.mul_(.9).add_(torch.cat(teacher_logits).mean(dim=0, keepdim=True), alpha=.1)
                entropy += float(torch.stack([-(t * t.clamp_min(1e-12).log()).sum(-1).mean() for t in targets]).mean()) * len(images)
            total += float(loss.detach()) * len(images); count += len(images); steps += 1
            if SHORT and steps >= 2:
                break
        history.append({'epoch': epoch + 1, 'steps': steps, 'loss': total / count, 'teacher_entropy': entropy / count})
        print(name, history[-1])
    # Se usa el último checkpoint, criterio prefijado sin seleccionar por test.
    x_train, y_train = embeddings(teacher, train)
    x_valid, y_valid = embeddings(teacher, valid)
    x_test, y_test = embeddings(teacher, test)
    result = {'config': name, 'use_center': use_center, 'teacher_temperature': teacher_temp,
              'teacher_ema': .996, 'center_ema': .9, 'student_temperature': .1, 'history': history,
              'representation_std': float(x_valid.std(dim=0, unbiased=False).mean()),
              'knn_k': 5, 'knn_temperature': .07, 'knn_validation': knn(x_train, y_train, x_valid, y_valid),
              'knn_test_exploratory': knn(x_train, y_train, x_test, y_test),
              'linear_probe': probe(x_train, y_train, x_valid, y_valid, x_test, y_test),
              'attention': attention_example(teacher, test, test_id)}
    return result


def main():
    train, valid, test, splits = dataset()
    OUT.mkdir(parents=True, exist_ok=True)
    result = {'short': SHORT, 'dataset': REPO, 'revision': REVISION, 'splits': splits,
              'protocol': 'Etiquetas usadas para estratificar splits, no en pérdida de autoaprendizaje; '
                          'etiquetas solo para k-NN y sonda. Último checkpoint del profesor, '
                          'sonda seleccionada por validación; test exploratorio. Dos vistas '
                          'globales y dos locales; recorte/volteo, sin copiar receta completa DINO.',
              'limitation': 'Sin los 100.000 ejemplos STL sin etiqueta. El centro y la temperatura '
                            'no garantizan evitar colapso; atención no es causalidad.', 'runs': []}
    for name, use_center, temperature in [('base', True, .04), ('sin_centro', False, .04),
                                           ('temperatura_alta', True, .1)]:
        result['runs'].append(run_configuration(name, use_center, temperature, train, valid, test, splits['test'][0]))
        (OUT / 'results.json').write_text(json.dumps(result, ensure_ascii=False), encoding='utf-8')
        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

NumericWhat does the encoder save?
A ViT-B/16 receives 224×224 pixels and one CLS. With 75% of its 196 patches hidden, what fraction of encoder block cost remains when counting QKV, output, QKᵀ, AV and MLP with D=768 and expansion 4? Omit other operations and the decoder.
ProofA constant teacher
Prove: The teacher emits a fixed distribution p and the student q=softmax(z/T), with T>0. Reason about cross-entropy and collapse.
0
Do not propagate gradients through p.

Step 1 of 3. What is the gradient with respect to logit z_k?

CodeHide and restore order
Implement random_masking(x, ratio, noise=None, seed=0). x has shape (B,N,D) with positive dimensions, and 0 ≤ ratio ≤ 1. Generate uniform noise of shape (B,N) with default_rng(seed) when not supplied; if supplied, use it to check the algorithm. Stably sort each row by ascending noise and retain int(N·(1−ratio)) tokens. Return visible tokens, mask and ids_restore: the mask is 0 for visible and 1 for hidden tokens in original order; ids_restore inverts each row's permutation. Reject out-of-range ratio, nonfinite noise or incorrect noise shape. Endpoints 0 and 1 must work, though mean loss over hidden tokens alone requires separately handling ratio=0.
import numpy as np

def random_masking(x, ratio, noise=None, seed=0):
  pass
Shift+Enter to run
CodeEvaluate a frozen representation
Implement knn_eval(train_feats, train_labels, test_feats, k, T), returning one label per query. Features are finite nonempty matrices with equal dimension; training labels are a vector of the same length and may be nonconsecutive integers. Normalize each row to obtain cosines and reject zero norms, nonpositive or nonfinite T and k outside 1..N. Sort neighbors by descending similarity, retaining original order for ties. Each neighbor votes for its label with weight exp(similarity/T); stabilize the exponential by subtracting the maximum per query. If two classes tie in votes, choose the smaller label. Do not use query labels.
import numpy as np

def knn_eval(train_feats, train_labels, test_feats, k, T):
  pass
Shift+Enter to run
QuizCompare objectives without mixing evaluations
An MAE encoder outperforms DINO after fine-tuning in one experiment, while DINO obtains a better linear probe. What conclusion do these results permit?
QuizDoes small KL imply collapse?
KL between teacher and student is zero for each image. What can be concluded?
Key idea
MAE and DINO build different signals from unlabeled images. Evaluating them requires separating the pretraining objective, frozen representation and behavior after fine-tuning.