Visual foundation models I: DINOv2, DINOv3 and universal dense features
Study reusable visual representations, DINOv2 and DINOv3, dense probes, registers and patch correspondences.
After this lesson you can
- Explain DINOv2 training, data curation and KoLeo regularization.
- Analyze patch representations, register tokens and dense features.
- Derive Gram anchoring and its invariance to feature rotations.
- Interpret visual probes and estimate storage under explicit evaluation protocols.
Before you start
- 16Self-distillation with no labelsiBOT: masked image modeling with online tokenizerEmergent segmentation in self-attentionVision Transformer2D position embeddings and resolution interpolationSemantic segmentation task and mIoUTransfer learning in vision
- 07Nearest-neighbor entropy and MI estimators
- 12Alignment and uniformityLinear probe and k-NN evaluation
- 20Foundation modelNeural scaling laws
- 21Knowledge distillation
- 02Gram matrix
One representation for several questions
A visual encoder can learn a representation during pretraining that is reused to classify an image, describe its regions or find correspondences. The idea of a visual foundation model is to use that representation across tasks instead of starting from scratch for each one. A linear probe freezes the encoder and trains a small head; it still requires task labels. “Frozen encoder” does not mean “unsupervised throughout evaluation.”
Model families differ in pretraining signal. DINOv2 and the DINOv3 visual backbone learn from images using self-supervised objectives; CLIP learns an aligned space from image-text pairs. A DINO visual encoder alone does not turn a phrase into a vector comparable with an image. DINOv3 also studies a later text-alignment stage, but that capability should not be attributed to every visual checkpoint. The choice depends on task, pretraining data and evaluation protocol.
The previous lesson covered DINO and iBOT. Here we follow the representation from a whole image to individual patches. Results depend on resolution, checkpoint, layer and preprocessing, not just family name.
DINOv2: data, objectives and distillation
The DINOv2 recipe combines a global DINO self-distillation loss, an iBOT masked-patch prediction loss and KoLeo spreading regularizer. It uses separate heads for global and local objectives and Sinkhorn-Knopp to normalize teacher assignments. After most pretraining it briefly adapts to 518×518 images to benefit spatial tasks. The large ViT-g/14 then serves as a fixed teacher to distill smaller models. Details are in DINOv2, sections 4 and 5.
Curation is also part of the experiment. The authors start with approximately 1.2 billion images (1.200 million in the source’s notation) after initial filters, remove duplicates and neighbors of validation and test sets, and retrieve examples near seed collections by visual similarity. The resulting LVD-142M is not a uniform web sample. In their Table 2, with ViT-g/14 and equal iteration counts, uncurated data versus LVD-142M yields 83.3 versus 85.8% ImageNet-1k top-1, 48.5 versus 47.7 ADE20k mIoU and 54.3 versus 64.6 Oxford-M mAP. Selection improves some metrics in that comparison, not all or necessarily any future distribution.
KoLeo illustrates why batch geometry matters. For normalized vectors , define and
Minimizing it penalizes excessively close neighbors. If two vectors coincide, the ideal loss diverges; an implementation with changes the value near zero and must state where it applies it. Local separation within a batch does not guarantee a globally uniform distribution or demonstrate absence of all collapse. In Table 3 of DINOv2, the ablation without and with KoLeo gives 55.6 and 63.9 Oxford-M mAP respectively. In another comparison, adding the masked objective changes ADE20k mIoU from 44.2 to 47.1. Those runs use equal iteration counts between variants, fewer than final training; these are not universal gains.
Looking inside patches
A ViT produces one vector per patch. To visualize their relationships, gather vectors from several images, center the set and project it onto the first three principal components. Painting those coordinates as RGB lets a shared basis compare colors across images. A principal component’s sign is arbitrary and color scaling also matters: fitting independent PCA to each image can change colors even when geometry is similar.
The initial images come from the short lab test, with DINOv2-S/14 at resolution 126 and a 9×9 patch grid. You can also load cell output with two images of your choosing. Similar color is a visual clue, not a label or guarantee of semantic equivalence.
A dense-feature probe retains each patch’s spatial vector instead of using only CLS. For segmentation, a linear layer can assign a class to each vector and then interpolate logits to mask resolution. Comparison requires fixing where the layer is extracted, how the image is resized, which pixels are ignored and whether IoU is accumulated over the full confusion matrix. Thin regions can be lost in the coarse grid even if the linear classifier is correct.
High norms and registers
In some ViTs a few patch tokens have much higher norms than the rest. In Vision Transformers Need Registers, the authors study a particular DINOv2 ViT-g/14 distribution and choose norm greater than 150 as the outlier criterion: under that protocol, 2.37% of tokens exceed the threshold. It is not a universal threshold. Their probes suggest those patches, often in redundant regions, retain less local information and may store more global information.
The authors hypothesize that the model reuses some background tokens for internal computation. In that DINOv2 family, outliers appeared in larger models after sufficient training; the same work also finds outliers in OpenCLIP and DeiT-III of B and L size. Do not conclude they can only appear in a giant model or that every high-norm point always has the same function.
Registers are additional learnable tokens that participate in the transformer and are separated from image tokens when obtaining dense features. They are not pixel masks and do not become output patches. Checkpoints with and without registers are separately trained models; adding arbitrary tokens to an existing model does not automatically reproduce the experiment. In the paper’s Table 2(a), for its DINOv2 ViT-L reproduction, frozen probes without and with registers obtain 84.3 and 84.8% ImageNet top-1, 46.6 and 47.9 ADE20k mIoU, and 0.378 and 0.366 NYUd RMSE. These compare those training runs and protocols, not guarantee improvement on every image.
In this short test, the twice-median rule detects no outlier patches in the eight images for either small model. This example therefore does not reproduce the disappearance of artifacts in the study with larger models. A strong attention map also does not by itself prove a token has an anomalous norm.
Norm depends on where you look. The official DINOv2 implementation exposes tokens before final normalization and normalized tokens afterward. Record which you use, separate CLS and registers, and do not normalize each vector to unit length before studying its norm. A CLS attention map and a norm map answer different questions.
DINOv3 and Gram anchoring
The DINOv3 report describes a curated LVD-1689M sample of 1.689 billion images within a larger data system. In its Table 2, the reference DINOv2 ViT-g teacher has 1.1 billion parameters, patch size 14 and dimension 1536; DINOv3 ViT-7B has about 6.7 billion, patch size 16 and dimension 4096. Both teachers in that table use 40 blocks and four registers; DINOv3 uses rotary positions. These figures describe those configurations, not every size in each family.
The authors observe that, in the large-model and prolonged-training regime they study, some global metrics improve while patch-feature consistency degrades. They distinguish that irregularity from high-norm outliers addressed with registers. To preserve spatial relationships they introduce Gram anchoring.
Let be student and Gram teacher features, each row normalized to unit norm. Their matrices and contain similarities between patch pairs. Equation 2 of the paper uses
The sum of squares penalizes changes in patch relationships without requiring each coordinate of to match the corresponding coordinate of . If an implementation averages the terms, its scale changes and the loss weight must be interpreted accordingly. Zero-norm rows need an explicit normalization convention.
An example shows invariance: if , then . Preserving Gram does not require preserving the feature basis or by itself prove a relationship is semantically correct. The Gram teacher starts from an earlier state with good dense properties and, in the described refinement, is periodically updated from the main EMA teacher. In Figure 9 of the report, its baseline and a variant with a 200,000-iteration Gram teacher and double-resolution features obtain 50.3 and 55.7 ADE20k mIoU, and 0.307 and 0.281 NYU RMSE respectively. Those numbers belong to that ablation and do not separately measure all DINOv3 changes.
In Table 3 of the same report, linear probes on DINOv2-g/14 and DINOv3-7B/16 obtain 49.5 and 55.9 ADE20k mIoU. For segmentation, 1,024 patch tokens are matched using 448×448 and 512×512 inputs respectively. Architecture, data and recipe also change: do not attribute the whole difference to Gram anchoring.
Correspondences and memory limits
One way to explore the representation is to choose a patch in one image, normalize its vector and find the maximum cosine among patches in another. The full map shows alternatives; the maximum always returns some neighbor, even if the object is occluded or has no counterpart. A plausible correspondence in one example is not an accuracy measurement. Quantifying it requires independent annotations, a rule for occlusions and a declared denominator.
Before saving a feature collection, count the bytes. In ViT-S/14 with 518×518 input there are patches (1,369) and channels. For 1,000 images in float16, patch maps alone occupy bytes (1,051,392,000), approximately 0.979 GiB. That isolated matrix fits in 8 GiB, but the count excludes weights, inputs, CLS, registers, activations and buffers: it does not prove the entire process fits on an 8 GB GPU.
Input size matters: DINOv2’s patch size is 14 and some implementations crop dimensions not divisible by 14. Align the mask transform with the image transform and use nearest-neighbor interpolation for discrete labels. For depth, distinguish a relative prediction from one in metric units and specify valid pixels, scale alignment and metric before comparing RMSE.
To use weights, pin the checkpoint, revision, preprocessing and library version. Official DINOv2 weights are published under Apache-2.0, while DINOv3 uses its own license and the repository indicates an access process for weights. Terms for other models in the same repository may differ. Check the specific artifact’s license before using or distributing it.
Depth Anything illustrates another stage: a pretrained visual encoder is combined with a decoder and training to estimate depth. Patch representations alone are not a calibrated metric measurement; the head, data and evaluation still matter.
Labs
Dense probes on DINOv2
The following cells require PyTorch, torchvision, transformers, huggingface_hub, safetensors, pyarrow, numpy and Pillow. The first verifies Pet’s revision and hashes and reproduces selection, deduplication and splits from lesson 19’s cell. It trains a linear probe on frozen patches from each DINOv2-S/14 and selects by validation mIoU; the shared test is exploratory. The trimap retains three classes and ignores 255. Resolution is 126 in short mode and 252 in full mode to be a multiple of 14.
The cell exports a joint PCA and features to search correspondences in two images; PCA colors are arbitrary and similarity does not guarantee semantic correspondence. If ORYON_UNET_CHECKPOINT points to the checkpoint produced by lesson 19’s cell, it compares both networks on the same test, masks and evaluation resolution; that U-Net was trained at 128 or 256. With ORYON_VERIFY_SHORT=1 there are only four steps per probe: the result does not demonstrate convergence. In a short run, exploratory mIoU was 0.245 without registers, 0.305 with registers and 0.210 for the short U-Net. Weights and training budgets change, so this sample does not establish a general model ranking.
To explore two of your own photographs, specify their local paths in ORYON_PAIR_IMAGE_A and ORYON_PAIR_IMAGE_B before running the first cell. Features are calculated locally and the generated results.json can be loaded into the PCA viewer. These images are used only for visualization, not probe training or evaluation; they are resized to a square like Pet images.
"""Sondas densas DINOv2-S en Oxford-IIIT Pet, mismo split que m16-l19.
Requiere torch, torchvision, transformers, huggingface_hub, safetensors,
pyarrow, numpy y Pillow. ORYON_VERIFY_SHORT=1 comprueba el recorrido con pocos
pasos y datos, sin medir convergencia. Los pesos y datos se descargan en sus
cachés comunes al ejecutar.
ORYON_UNET_CHECKPOINT opcional apunta al checkpoint que genera la celda l19
con ORYON_SEG_CHECKPOINT_DIR. Ambas redes se evalúan aquí con la misma máscara
y resolución múltiplo de 14; el U-Net de l19 se entrenó a otra resolución.
"""
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
from torch import nn
from torch.nn import functional as F
from torchvision.models import resnet34
from transformers import AutoModel
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
SIDE = 126 if SHORT else 252
OUT = Path(os.environ.get('ORYON_DINO_PET_DIR', 'dinov2-pet'))
REPO = 'dpdl-benchmark/oxford_iiit_pet'
REV = '18515194612b584bf54692372ac035ef773a5b41'
SHAS = {
'data/test-00000-of-00003.parquet':'cc4a6ca162c95b297116a4462ff7accf8a7f8ae3ce123d9be56d4c91c00380fa',
'data/test-00001-of-00003.parquet':'c5fb1c1cff8c27809d11f827819088464311a17bf325703a39334031b28af280',
'data/test-00002-of-00003.parquet':'65d370e76ca49a131ed874053ac372828303ef771ba4c961878faf4870217fda',
'data/train-00000-of-00003.parquet':'473606455eb66b1ee9b2a8675e41bf8c7494370fc27eccc5eae5890f882b7442',
'data/train-00001-of-00003.parquet':'3bc7e8a62a1756044d1ecc4750a246afda63d0e8ac8042f43789e661c87036a8',
'data/train-00002-of-00003.parquet':'c75713efefddd8e7d692e666eb76072e58db9649c7c2fdccfbae05fba2acd7a3',
}
MODELS = {
'sin_registros': ('facebook/dinov2-small', '150c8e7bb7cef2d30ec31b13a517af14840ee3f7',
'ae1e99fcefd534ed978cdeb8326f08030c96e28b7a81ffcbc98a857c84d14be1'),
'con_registros': ('facebook/dinov2-with-registers-small', 'fd1efe48917962b9a9ddd427df5f5695d685b100',
'78e7f952c5af83cf6da38f08ff52b062bbe00c1adf39c4c7e0361969f27abae7'),
}
MEAN = torch.tensor([.485, .456, .406]).view(3, 1, 1)
STD = torch.tensor([.229, .224, .225]).view(3, 1, 1)
def sha(path):
h = hashlib.sha256()
with open(path, 'rb') as stream:
for part in iter(lambda: stream.read(1024 * 1024), b''):
h.update(part)
return h.hexdigest()
def read_pet():
# Mismo orden de selección y deduplicación que la celda vigente de l19.
groups = {'train': [], 'validation': [], 'test': []}
seen, duplicates = {}, 0
for split in ('train', 'test'):
for shard in range(1 if SHORT else 3):
name = f'data/{split}-{shard:05d}-of-00003.parquet'
path = hf_hub_download(repo_id=REPO, repo_type='dataset', revision=REV, filename=name)
if sha(path) != SHAS[name]:
raise ValueError('SHA inesperado: ' + name)
table = pq.ParquetFile(path)
count = table.metadata.num_rows
order = np.random.default_rng(16190 + shard + (100 if split == 'test' else 0)).permutation(count)
if split == 'train':
if SHORT:
subsets = {'train': order[:32], 'validation': order[32:40]}
else:
cut = int(count * .8)
subsets = {'train': order[:cut], 'validation': order[cut:]}
else:
subsets = {'test': order[:8] if SHORT else order}
slots = {int(index): (kind, j) for kind, indices in subsets.items() for j, index in enumerate(indices)}
local = {kind: [None] * len(indices) for kind, indices in subsets.items()}
offset = 0
for batch in table.iter_batches(batch_size=16, columns=['image', 'segmentation_mask', 'label']):
rows = batch.to_pylist()
for j, row in enumerate(rows):
choice = slots.get(offset + j)
if choice is not None:
kind, pos = choice
local[kind][pos] = {'image': row['image']['bytes'], 'mask': row['segmentation_mask']['bytes'],
'label': int(row['label']), 'source': f'{split}/{shard}/{offset+j}'}
offset += len(rows)
for kind, rows in local.items():
if any(row is None for row in rows):
raise ValueError('Faltan filas de ' + kind)
for row in rows:
digest = hashlib.sha256(row['image']).hexdigest()
if digest in seen:
duplicates += 1
continue
seen[digest] = kind
row['sha256'] = digest
groups[kind].append(row)
if any(not values for values in groups.values()):
raise ValueError('Partición vacía')
hashes = [{r['sha256'] for r in groups[key]} for key in ('train', 'validation', 'test')]
if hashes[0] & hashes[1] or hashes[0] & hashes[2] or hashes[1] & hashes[2]:
raise ValueError('Fuga entre particiones')
return groups, duplicates
def image_and_mask(row):
with Image.open(io.BytesIO(row['image'])) as image:
pixels = np.asarray(image.convert('RGB').resize((SIDE, SIDE), Image.Resampling.BILINEAR), dtype=np.uint8).copy()
with Image.open(io.BytesIO(row['mask'])) as image:
mask = np.asarray(image.resize((SIDE, SIDE), Image.Resampling.NEAREST), dtype=np.int64).copy()
if not set(np.unique(mask)).issubset({1, 2, 3, 255}):
raise ValueError('Valores de trimap inesperados')
x = torch.from_numpy(pixels).permute(2, 0, 1).float() / 255.
y = torch.from_numpy(np.where(mask == 255, 255, mask - 1)).long()
return ((x - MEAN) / STD).to(DEVICE), y.to(DEVICE), pixels
def load_encoder(name):
repo, revision, expected = MODELS[name]
path = hf_hub_download(repo_id=repo, revision=revision, filename='model.safetensors')
if sha(path) != expected:
raise ValueError('SHA inesperado de pesos ' + name)
model = AutoModel.from_pretrained(repo, revision=revision, use_safetensors=True,
trust_remote_code=False).to(DEVICE).eval()
model.requires_grad_(False)
if model.config.patch_size != 14 or model.config.hidden_size != 384:
raise ValueError('No es el DINOv2-S/14 esperado')
return model
@torch.no_grad()
def dense(model, x):
output = model(pixel_values=x).last_hidden_state
prefix = 1 + int(getattr(model.config, 'num_register_tokens', 0))
patches = output[:, prefix:]
grid = SIDE // 14
if patches.shape[1:] != (grid * grid, 384):
raise ValueError(f'Número de tokens inesperado: {patches.shape}')
return patches.transpose(1, 2).reshape(len(x), 384, grid, grid)
def confusion(logits, target):
prediction = logits.argmax(1)
valid = target != 255
return torch.bincount((3 * target[valid] + prediction[valid]).flatten(), minlength=9).reshape(3, 3).cpu()
def metrics(matrix):
diagonal = matrix.diag().double()
union = matrix.sum(0) + matrix.sum(1) - diagonal
values = [float(diagonal[i] / union[i]) if union[i] else None for i in range(3)]
present = [value for value in values if value is not None]
return {'matrix': matrix.tolist(), 'iou': values, 'miou': sum(present) / len(present) if present else None}
@torch.no_grad()
def evaluate(encoder, head, rows):
head.eval()
matrix = torch.zeros((3, 3), dtype=torch.int64)
for row in rows:
x, y, _ = image_and_mask(row)
logits = F.interpolate(head(dense(encoder, x[None])), size=(SIDE, SIDE), mode='bilinear', align_corners=False)
if not torch.isfinite(logits).all():
raise FloatingPointError('Logits no finitos')
matrix += confusion(logits, y[None])
return metrics(matrix)
def train_probe(name, groups):
encoder = load_encoder(name)
torch.manual_seed(16250)
head = nn.Conv2d(384, 3, 1).to(DEVICE)
opt = torch.optim.AdamW(head.parameters(), lr=.001, weight_decay=.0001)
rng = np.random.default_rng(16251)
steps = 4 if SHORT else 1000
batch = 2 if SHORT else 8
points = sorted(set((1, steps // 2, steps)))
best, state, history = None, None, []
for step in range(1, steps + 1):
selected = [groups['train'][int(i)] for i in rng.integers(0, len(groups['train']), batch)]
pairs = [image_and_mask(row) for row in selected]
x, y = torch.stack([p[0] for p in pairs]), torch.stack([p[1] for p in pairs])
logits = F.interpolate(head(dense(encoder, x)), size=(SIDE, SIDE), mode='bilinear', align_corners=False)
loss = F.cross_entropy(logits, y, ignore_index=255)
if not torch.isfinite(loss):
raise FloatingPointError('Pérdida no finita')
opt.zero_grad(set_to_none=True); loss.backward()
if any(p.grad is None or not torch.isfinite(p.grad).all() for p in head.parameters()):
raise FloatingPointError('Gradiente no finito')
opt.step()
if step in points:
val = evaluate(encoder, head, groups['validation'])
history.append({'step': step, 'loss': float(loss.detach()), 'validation': val})
print(name, history[-1])
if val['miou'] is not None and (best is None or val['miou'] > best):
best = val['miou']
state = {k: v.detach().cpu().clone() for k, v in head.state_dict().items()}
if state is None:
raise ValueError('Sin checkpoint válido')
head.load_state_dict(state)
result = {'model': name, 'weights': MODELS[name], 'history': history,
'test_exploratory': evaluate(encoder, head, groups['test'])}
torch.save({'state_dict': state, 'model': name, 'side': SIDE}, OUT / f'probe-{name}.pt')
return encoder, head, result
def png_uri(image):
buffer = io.BytesIO()
Image.fromarray(image).save(buffer, format='PNG')
return 'data:image/png;base64,' + base64.b64encode(buffer.getvalue()).decode('ascii')
@torch.no_grad()
def example_pair(encoder, rows):
first = rows[0]
second = next((r for r in rows[1:] if r['label'] == first['label']), rows[1] if len(rows) > 1 else first)
paths = [os.environ.get('ORYON_PAIR_IMAGE_A'), os.environ.get('ORYON_PAIR_IMAGE_B')]
if any(paths) and not all(paths):
raise ValueError('Indica las dos rutas ORYON_PAIR_IMAGE_A y ORYON_PAIR_IMAGE_B')
examples, features = [], []
for index, row in enumerate((first, second)):
if all(paths):
path = Path(paths[index])
raw = path.read_bytes()
with Image.open(io.BytesIO(raw)) as image:
pixels = np.asarray(image.convert('RGB').resize((SIDE, SIDE), Image.Resampling.BILINEAR), dtype=np.uint8).copy()
x = torch.from_numpy(pixels).permute(2, 0, 1).float() / 255.
x = ((x - MEAN) / STD).to(DEVICE)
example = {'source': path.name, 'sha256': hashlib.sha256(raw).hexdigest(),
'label': None, 'image': png_uri(pixels), 'mask': None}
else:
x, mask, pixels = image_and_mask(row)
example = {'source': row['source'], 'label': row['label'], 'image': png_uri(pixels),
'mask': png_uri(mask.byte().cpu().numpy())}
z = dense(encoder, x[None])[0].permute(1, 2, 0).cpu()
features.append(z.reshape(-1, 384))
examples.append(example)
both = torch.cat(features)
center = both.mean(0, keepdim=True)
_, _, v = torch.linalg.svd(both - center, full_matrices=False)
projection = (both - center) @ v[:3].T
low, high = projection.min(0).values, projection.max(0).values
rgb = (projection - low) / (high - low).clamp_min(1e-8)
grid = SIDE // 14
# Cada PNG conserva los colores de la misma PCA conjunta y facilita su
# inspección sin volver a ajustar otra base en el visor.
pca_pixels = (rgb.reshape(2, grid, grid, 3) * 255).round().clamp(0, 255).byte().numpy()
normalized = F.normalize(torch.stack(features), dim=-1)
return {'items': examples, 'grid': grid, 'pca_rgb': rgb.reshape(2, grid, grid, 3).tolist(),
'pca_png': [png_uri(image) for image in pca_pixels],
'normalized_features': normalized.reshape(2, grid, grid, 384).tolist(),
'note': 'PCA conjunta; signos y colores son arbitrarios y correspondencia no implica corrección semántica.'}
class Encoder(nn.Module):
def __init__(self):
super().__init__()
self.base = resnet34(weights=None)
self.base.fc = nn.Identity()
def forward(self, x):
b = self.base
s = b.relu(b.bn1(b.conv1(x))); x = b.layer1(b.maxpool(s)); c3 = b.layer2(x)
c4 = b.layer3(c3)
return s, x, c3, c4, b.layer4(c4)
class Block(nn.Module):
def __init__(self, cin, cout):
super().__init__()
self.net = nn.Sequential(nn.Conv2d(cin, cout, 3, padding=1), nn.GroupNorm(8, cout), nn.ReLU(),
nn.Conv2d(cout, cout, 3, padding=1), nn.GroupNorm(8, cout), nn.ReLU())
def forward(self, x):
return self.net(x)
class UNet(nn.Module):
def __init__(self):
super().__init__()
self.encoder = Encoder()
self.blocks = nn.ModuleList([Block(512+256,256), Block(256+128,128), Block(128+64,64), Block(64+64,32)])
self.head = nn.Conv2d(32, 3, 1)
def forward(self, x):
stem, c2, c3, c4, c5 = self.encoder(x)
z = c5
for skip, block in zip((c4, c3, c2, stem), self.blocks):
z = F.interpolate(z, size=skip.shape[-2:], mode='bilinear', align_corners=False)
z = block(torch.cat((z, skip), dim=1))
return F.interpolate(self.head(z), size=x.shape[-2:], mode='bilinear', align_corners=False)
@torch.no_grad()
def compare_unet(path, rows):
checkpoint = torch.load(path, map_location='cpu', weights_only=True)
if checkpoint.get('name') != 'unet':
raise ValueError('El checkpoint no es la U-Net de l19')
model = UNet().to(DEVICE).eval()
model.load_state_dict(checkpoint['model'], strict=True)
matrix = torch.zeros((3, 3), dtype=torch.int64)
for row in rows:
x, y, _ = image_and_mask(row)
matrix += confusion(model(x[None]), y[None])
return {'checkpoint': str(path), 'step': checkpoint.get('step'), 'test_exploratory': metrics(matrix),
'note': 'Mismo split y resolución de evaluación; U-Net entrenada a otra resolución en l19.'}
def main():
torch.set_num_threads(1)
groups, duplicates = read_pet()
OUT.mkdir(parents=True, exist_ok=True)
result = {'short': SHORT, 'dataset': REPO, 'revision': REV, 'source_split_seed': 16190,
'data_sources': {k: [r['source'] for r in v] for k, v in groups.items()},
'data_hashes': {k: [r['sha256'] for r in v] for k, v in groups.items()},
'duplicates_excluded': duplicates, 'resolution': SIDE, 'steps': 4 if SHORT else 1000,
'protocol': 'Mismo split y deduplicación que l19, tres clases de trimap, 255 ignorado; '
'normalización ImageNet, sonda de 1×1 sobre parches congelados.',
'runs': []}
for name in MODELS:
encoder, head, run = train_probe(name, groups)
run['example_pair'] = example_pair(encoder, groups['validation'])
result['runs'].append(run)
(OUT / 'results.json').write_text(json.dumps(result, ensure_ascii=False), encoding='utf-8')
del encoder, head
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
unet_path = os.environ.get('ORYON_UNET_CHECKPOINT')
if unet_path:
result['unet'] = compare_unet(unet_path, groups['test'])
else:
result['unet'] = {'status': 'no evaluada: indica ORYON_UNET_CHECKPOINT de la celda l19'}
(OUT / 'results.json').write_text(json.dumps(result, ensure_ascii=False), encoding='utf-8')
print('Resultados guardados en', OUT.resolve())
if __name__ == '__main__':
main()npm run lab and open the connection link.The second cell uses CC0 synthetic views from DX.GL: one object each for training, validation and test. Relative depth comes from the 8-bit PNG, with quantization; it is standardized per image over the foreground and does not measure metric depth. Masks contain intermediate values at antialiased edges: the cell defines foreground as intensity greater than 127 before downsampling. Only three objects do not justify a broad generalization claim. ETag identifies the served version but is not a SHA; observed SHAs of each extracted file are saved.
To limit disk use, the reader checks size and ETag and requests only partial ZIP ranges; it fails if the server does not respect ranges or documented format. In a short check with four training, two validation and two test views and two steps, exploratory mean test MSE was 1.283 on standardized depths. The result verifies the pipeline, not convergence or generalization to other objects.
"""Sonda lineal de profundidad relativa sintética con DINOv2-S congelado.
Requiere torch, transformers, huggingface_hub, safetensors, Pillow y numpy.
Los datos CC0 de DX.GL se leen por rangos HTTP de tres ZIP, sin descargar
archivos enteros: un objeto para train, otro para validación y otro para test.
La fuente expone profundidad de 8 bits normalizada entre near y far; aquí se
estandariza por imagen en el primer plano. No es profundidad métrica ni NYU.
ORYON_VERIFY_SHORT=1 usa cuatro/dos/dos vistas y dos pasos, sin conclusiones.
Fuentes: https://huggingface.co/datasets/dxgl/multiview-datasets y
https://dx.gl/docs/api/ . Los ETag son identificadores opacos, no SHA-256.
"""
import base64
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import urllib.request
import zipfile
import numpy as np
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 transformers import AutoModel
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
SIDE = 126 if SHORT else 252
OUT = Path(os.environ.get('ORYON_DINO_DEPTH_DIR', 'dinov2-depth'))
MODEL = 'facebook/dinov2-small'
MODEL_REV = '150c8e7bb7cef2d30ec31b13a517af14840ee3f7'
MODEL_SHA = 'ae1e99fcefd534ed978cdeb8326f08030c96e28b7a81ffcbc98a857c84d14be1'
BASE = 'https://dx.gl/api/v/EJbs8npt2RVM/'
# HEAD observado: tamaño y ETag se comprueban antes de leer; ETag no es hash.
OBJECTS = {
'train': ('drill', 'A0dcsk7HHgAg', 147589317, '0202386e8da2d359a9c2f3ddd0892e18'),
'validation': ('cash_register', 'JfjLRexr6J7z', 173611897, 'a34a34cdfdd1ab6457c87611b0497d82'),
'test': ('fire_extinguisher', 'cLgyqM5mhQoq', 172418011, '11995fe932b467c569ad33a516b0b2fa'),
}
MEAN = torch.tensor([.485, .456, .406]).view(3, 1, 1)
STD = torch.tensor([.229, .224, .225]).view(3, 1, 1)
def sha(path):
h = hashlib.sha256()
with open(path, 'rb') as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
class RangeReader(io.RawIOBase):
"""Lectura de rangos exactos; falla si el servidor responde con ZIP entero."""
def __init__(self, url, size, etag):
self.url, self.size, self.etag, self.position = url, size, etag, 0
request = urllib.request.Request(url, method='HEAD', headers={'Accept-Encoding': 'identity',
'User-Agent': 'OryonLearn/1.0'})
with urllib.request.urlopen(request, timeout=30) as response:
if int(response.headers.get('Content-Length', -1)) != size:
raise ValueError('El tamaño del ZIP ha cambiado')
if response.headers.get('ETag', '').strip('"') != etag:
raise ValueError('El ETag del ZIP ha cambiado')
if response.headers.get('Accept-Ranges', '').lower() != 'bytes':
raise ValueError('El servidor no anuncia rangos por bytes')
def readable(self): return True
def seekable(self): return True
def tell(self): return self.position
def seek(self, offset, whence=io.SEEK_SET):
if whence not in (io.SEEK_SET, io.SEEK_CUR, io.SEEK_END):
raise ValueError('Modo de búsqueda desconocido')
pos = offset if whence == io.SEEK_SET else self.position + offset if whence == io.SEEK_CUR else self.size + offset
if not 0 <= pos <= self.size:
raise ValueError('Posición fuera del archivo')
self.position = pos
return pos
def read(self, size=-1):
if self.position >= self.size:
return b''
length = self.size - self.position if size < 0 else min(size, self.size - self.position)
if length > 16 * 1024 * 1024:
raise ValueError('Rango demasiado grande; no se descargará el ZIP entero')
if length <= 0:
return b''
start, end = self.position, self.position + length - 1
request = urllib.request.Request(self.url, headers={'Range': f'bytes={start}-{end}',
'If-Match': f'"{self.etag}"', 'Accept-Encoding': 'identity', 'User-Agent': 'OryonLearn/1.0'})
with urllib.request.urlopen(request, timeout=30) as response:
expected = f'bytes {start}-{end}/{self.size}'
if (response.status != 206 or response.headers.get('Content-Range') != expected
or response.headers.get('ETag', '').strip('"') != self.etag):
raise ValueError('El servidor no ha respetado el rango solicitado')
data = response.read(length + 1)
if len(data) != length:
raise ValueError('Respuesta de rango incompleta')
self.position += length
return data
def members(archive, folder):
result = {}
for name in archive.namelist():
path = PurePosixPath(name)
if len(path.parts) >= 2 and path.parts[-2] == folder and path.name.lower().endswith('.png'):
if path.name in result:
raise ValueError('Nombre de vista duplicado en ZIP')
result[path.name] = name
return result
def safe_member(archive, name):
info = archive.getinfo(name)
if info.file_size > 32 * 1024 * 1024 or info.compress_size > 16 * 1024 * 1024 or info.flag_bits & 1:
raise ValueError('Archivo comprimido demasiado grande o cifrado')
return archive.read(info)
def object_views(split):
name, identifier, size, etag = OBJECTS[split]
url = BASE + identifier + '/dataset'
count = (4 if split == 'train' else 2) if SHORT else (120 if split == 'train' else 32)
rows = []
with zipfile.ZipFile(RangeReader(url, size, etag)) as archive:
images, depths, masks = (members(archive, folder) for folder in ('images', 'depth', 'masks'))
common = sorted(set(images) & set(depths) & set(masks))
if len(common) < count:
raise ValueError(f'Faltan vistas RGB/profundidad/máscara para {name}')
# Muestreo equiespaciado por nombre, fijado sin consultar las predicciones.
indices = np.linspace(0, len(common) - 1, count, dtype=int)
for index in indices:
key = common[int(index)]
rgb_bytes, depth_bytes, mask_bytes = (safe_member(archive, mapping[key]) for mapping in (images, depths, masks))
with Image.open(io.BytesIO(rgb_bytes)) as image:
if image.format != 'PNG' or image.size != (1024, 1024):
raise ValueError(f'Formato o tamaño RGB inesperado: {image.format}, {image.size}')
rgba = image.convert('RGBA')
white = Image.new('RGBA', rgba.size, (255, 255, 255, 255))
pixels = np.asarray(Image.alpha_composite(white, rgba).convert('RGB').resize((SIDE, SIDE), Image.Resampling.BILINEAR), dtype=np.uint8).copy()
with Image.open(io.BytesIO(depth_bytes)) as depth:
if depth.format != 'PNG' or depth.mode != 'L' or depth.size != (1024, 1024):
raise ValueError(f'Profundidad de 8 bits inesperada: {depth.mode}')
d = np.asarray(depth.convert('L'), dtype=np.float32) / 255.
with Image.open(io.BytesIO(mask_bytes)) as mask:
if mask.format != 'PNG' or mask.size != (1024, 1024):
raise ValueError('Tamaño de máscara inesperado')
raw_mask = np.asarray(mask.convert('L'), dtype=np.uint8)
# Los bordes pueden tener cobertura parcial por antialias.
# Umbral explícito antes de remuestrear para decidir primer plano.
mask_image = raw_mask > 127
if d.shape != mask_image.shape:
raise ValueError('Profundidad y máscara desalineadas')
# Interpolar profundidad ponderada evita mezclar el fondo inválido.
m = torch.from_numpy(mask_image.astype(np.float32))[None, None]
z = torch.from_numpy(d)[None, None]
denom = F.interpolate(m, size=(SIDE, SIDE), mode='bilinear', align_corners=False)
target = F.interpolate(z * m, size=(SIDE, SIDE), mode='bilinear', align_corners=False) / denom.clamp_min(1e-8)
valid = denom[0, 0] > .99
values = target[0, 0][valid]
if len(values) < 100 or float(values.std(unbiased=False)) < .01:
raise ValueError('Profundidad o máscara insuficiente para estandarizar')
target = (target[0, 0] - values.mean()) / values.std(unbiased=False)
rgb = torch.from_numpy(pixels).permute(2, 0, 1).float() / 255.
rows.append({'x': (rgb - MEAN) / STD, 'target': target, 'valid': valid,
'view': key, 'hashes': [hashlib.sha256(v).hexdigest() for v in (rgb_bytes, depth_bytes, mask_bytes)]})
return rows, {'object': name, 'url': url, 'size': size, 'etag': etag,
'views': [row['view'] for row in rows], 'image_depth_mask_sha256': [row['hashes'] for row in rows]}
def load_model():
path = hf_hub_download(repo_id=MODEL, revision=MODEL_REV, filename='model.safetensors')
if sha(path) != MODEL_SHA:
raise ValueError('Hash inesperado de DINOv2')
model = AutoModel.from_pretrained(MODEL, revision=MODEL_REV, use_safetensors=True,
trust_remote_code=False).to(DEVICE).eval()
model.requires_grad_(False)
if model.config.patch_size != 14 or model.config.hidden_size != 384:
raise ValueError('Configuración DINOv2-S inesperada')
return model
@torch.no_grad()
def features(model, row):
output = model(pixel_values=row['x'][None].to(DEVICE)).last_hidden_state[:, 1:]
grid = SIDE // 14
if output.shape[1:] != (grid * grid, 384):
raise ValueError('Forma inesperada de parches')
return output.transpose(1, 2).reshape(1, 384, grid, grid)
def mse(pred, target, valid):
if not bool(valid.any()):
raise ValueError('Máscara vacía')
return (pred[valid] - target[valid]).square().mean()
@torch.no_grad()
def evaluate(model, head, rows):
total = 0.
for row in rows:
z = features(model, row)
prediction = F.interpolate(head(z), size=(SIDE, SIDE), mode='bilinear', align_corners=False)[0, 0]
loss = mse(prediction, row['target'].to(DEVICE), row['valid'].to(DEVICE))
if not torch.isfinite(loss):
raise FloatingPointError('Error de profundidad no finito')
total += float(loss)
return total / len(rows)
@torch.no_grad()
def preview(model, head, row):
z = features(model, row)
prediction = F.interpolate(head(z), size=(SIDE, SIDE), mode='bilinear', align_corners=False)[0, 0].cpu()
pixels = ((row['x'] * STD + MEAN).clamp(0, 1).permute(1, 2, 0).numpy() * 255).astype(np.uint8)
buffer = io.BytesIO()
Image.fromarray(pixels).save(buffer, format='PNG')
return {'view': row['view'], 'hashes': row['hashes'],
'image': 'data:image/png;base64,' + base64.b64encode(buffer.getvalue()).decode('ascii'),
'target_standardized': row['target'].tolist(), 'prediction': prediction.tolist(),
'valid': row['valid'].tolist(),
'note': 'Objetivo estandarizado con estadísticas del mapa real, solo en primer plano válido.'}
def main():
torch.set_num_threads(1)
train, train_meta = object_views('train')
valid, valid_meta = object_views('validation')
test, test_meta = object_views('test')
model = load_model()
torch.manual_seed(16255)
head = nn.Conv2d(384, 1, 1).to(DEVICE)
optimizer = torch.optim.AdamW(head.parameters(), lr=.001, weight_decay=.0001)
rng = np.random.default_rng(16256)
steps = 2 if SHORT else 1000
best, state, history = float('inf'), None, []
for step in range(1, steps + 1):
row = train[int(rng.integers(len(train)))]
z = features(model, row)
prediction = F.interpolate(head(z), size=(SIDE, SIDE), mode='bilinear', align_corners=False)[0, 0]
loss = mse(prediction, row['target'].to(DEVICE), row['valid'].to(DEVICE))
if not torch.isfinite(loss):
raise FloatingPointError('Pérdida no finita')
optimizer.zero_grad(set_to_none=True); loss.backward()
if any(p.grad is None or not torch.isfinite(p.grad).all() for p in head.parameters()):
raise FloatingPointError('Gradiente no finito')
optimizer.step()
if step in set((1, steps // 2, steps)):
val = evaluate(model, head, valid)
history.append({'step': step, 'train_loss': float(loss.detach()), 'validation_mse': val})
if val < best:
best = val
state = {k: v.detach().cpu().clone() for k, v in head.state_dict().items()}
print('Sonda de profundidad', history[-1])
if state is None:
raise ValueError('Sin sonda válida')
head.load_state_dict(state)
result = {'short': SHORT, 'model': MODEL, 'revision': MODEL_REV, 'model_sha256': MODEL_SHA,
'data': {'source': 'dxgl/multiview-datasets', 'license': 'CC0-1.0',
'train': train_meta, 'validation': valid_meta, 'test': test_meta},
'resolution': SIDE, 'history': history, 'test_mse_exploratory': evaluate(model, head, test),
'test_previews': [preview(model, head, row) for row in test[:2]],
'protocol': 'Profundidad 8 bits: negro cerca, blanco lejos; se estandariza por imagen '
'sobre primer plano, y se ignoran los bordes con mezcla de fondo. '
'Se selecciona por validación; cada partición es un objeto distinto.',
'limitations': 'Solo tres objetos sintéticos y profundidad cuantizada. ETag es identificador '
'opaco, no SHA; los SHA por archivo son observados, no cotejados contra un hash publicado. '
'No es NYU, no mide profundidad métrica ni generalización amplia.'}
OUT.mkdir(parents=True, exist_ok=True)
(OUT / 'results.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
print('Resultado:', (OUT / 'results.json').resolve())
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
if __name__ == '__main__':
main()npm run lab and open the connection link.Artifact detector
This cell measures each patch token’s L2 norm before final LayerNorm and compares it with the subsequent norm. It uses the same Pet validation images for both checkpoints and separates CLS, registers and patches. Twice the per-image median is a heuristic threshold fixed for this experiment; the code does not assume outliers appear or registers eliminate them.
If the first cell has already saved both probes in ORYON_DINO_PET_DIR, it compares their mIoU before and after zeroing flagged patches. This ablation changes the probe input distribution and does not demonstrate causality; annotated background also does not automatically equal redundancy. Checkpoints are different models, so their difference alone does not isolate the effect of registers. Some versions may not return attention weights; their absence is recorded in that case.
"""Normas antes de LayerNorm en DINOv2-S con y sin registros.
Requiere torch, transformers, huggingface_hub, safetensors, pyarrow, numpy y
Pillow. Los datos y pesos se descargan a cachés comunes al ejecutar. Usa el
mismo split de validación de la celda Pet de m16-l19 y compara muestras iguales.
Si hay sondas `probe-<modelo>.pt` en ORYON_DINO_PET_DIR, mide también una
ablación de tokens. ORYON_VERIFY_SHORT=1 solo verifica el circuito.
"""
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
from torch import nn
from torch.nn import functional as F
from transformers import AutoModel
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
SIDE = 126 if SHORT else 252
DIRECTORY = Path(os.environ.get('ORYON_DINO_PET_DIR', 'dinov2-pet'))
DATA_REPO = 'dpdl-benchmark/oxford_iiit_pet'
DATA_REV = '18515194612b584bf54692372ac035ef773a5b41'
TRAIN_SHAS = [
'473606455eb66b1ee9b2a8675e41bf8c7494370fc27eccc5eae5890f882b7442',
'3bc7e8a62a1756044d1ecc4750a246afda63d0e8ac8042f43789e661c87036a8',
'c75713efefddd8e7d692e666eb76072e58db9649c7c2fdccfbae05fba2acd7a3',
]
MODELS = {
'sin_registros': ('facebook/dinov2-small', '150c8e7bb7cef2d30ec31b13a517af14840ee3f7',
'ae1e99fcefd534ed978cdeb8326f08030c96e28b7a81ffcbc98a857c84d14be1'),
'con_registros': ('facebook/dinov2-with-registers-small', 'fd1efe48917962b9a9ddd427df5f5695d685b100',
'78e7f952c5af83cf6da38f08ff52b062bbe00c1adf39c4c7e0361969f27abae7'),
}
MEAN = torch.tensor([.485, .456, .406]).view(3, 1, 1)
STD = torch.tensor([.229, .224, .225]).view(3, 1, 1)
def sha(path):
h = hashlib.sha256()
with open(path, 'rb') as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
def validation_rows():
seen, validation = set(), []
# Como l19, procesa primero train y después validation en cada shard.
for shard in range(1 if SHORT else 3):
name = f'data/train-{shard:05d}-of-00003.parquet'
path = hf_hub_download(repo_id=DATA_REPO, repo_type='dataset', revision=DATA_REV, filename=name)
if sha(path) != TRAIN_SHAS[shard]:
raise ValueError('Hash de datos inesperado')
table = pq.ParquetFile(path)
count = table.metadata.num_rows
order = np.random.default_rng(16190 + shard).permutation(count)
if SHORT:
subsets = {'train': order[:32], 'validation': order[32:40]}
else:
cut = int(count * .8)
subsets = {'train': order[:cut], 'validation': order[cut:]}
slots = {int(index): (kind, j) for kind, indices in subsets.items() for j, index in enumerate(indices)}
local = {kind: [None] * len(indices) for kind, indices in subsets.items()}
offset = 0
for batch in table.iter_batches(batch_size=16, columns=['image', 'segmentation_mask']):
rows = batch.to_pylist()
for j, row in enumerate(rows):
choice = slots.get(offset + j)
if choice is not None:
kind, pos = choice
local[kind][pos] = {'image': row['image']['bytes'], 'mask': row['segmentation_mask']['bytes'],
'source': f'train/{shard}/{offset+j}'}
offset += len(rows)
for kind, rows in local.items():
if any(row is None for row in rows):
raise ValueError('Faltan filas seleccionadas')
for row in rows:
digest = hashlib.sha256(row['image']).hexdigest()
if digest in seen:
continue
seen.add(digest)
if kind == 'validation':
row['sha256'] = digest
validation.append(row)
# Subconjunto fijado por orden del split, no por sus valores de normas.
rows = validation[:8 if SHORT else 32]
if not rows:
raise ValueError('Sin imágenes de validación')
return rows
def preprocess(row):
with Image.open(io.BytesIO(row['image'])) as image:
pixels = np.asarray(image.convert('RGB').resize((SIDE, SIDE), Image.Resampling.BILINEAR), dtype=np.uint8).copy()
with Image.open(io.BytesIO(row['mask'])) as image:
mask = np.asarray(image.resize((SIDE, SIDE), Image.Resampling.NEAREST), dtype=np.int64).copy()
if not set(np.unique(mask)).issubset({1, 2, 3, 255}):
raise ValueError('Valores de trimap inesperados')
x = torch.from_numpy(pixels).permute(2, 0, 1).float() / 255.
y = torch.from_numpy(np.where(mask == 255, 255, mask - 1)).long()
return ((x - MEAN) / STD).to(DEVICE), y.to(DEVICE), pixels
def load_model(name):
repo, revision, expected = MODELS[name]
path = hf_hub_download(repo_id=repo, revision=revision, filename='model.safetensors')
if sha(path) != expected:
raise ValueError('Hash de modelo inesperado')
model = AutoModel.from_pretrained(repo, revision=revision, use_safetensors=True,
attn_implementation='eager', trust_remote_code=False).to(DEVICE).eval()
model.requires_grad_(False)
return model
def load_probe(name):
path = DIRECTORY / f'probe-{name}.pt'
if not path.exists():
return None
checkpoint = torch.load(path, map_location='cpu', weights_only=True)
if checkpoint.get('model') != name or checkpoint.get('side') != SIDE:
raise ValueError('Sonda incompatible con modelo o resolución')
head = nn.Conv2d(384, 3, 1).to(DEVICE).eval()
head.load_state_dict(checkpoint['state_dict'], strict=True)
return head
def confusion(logits, target):
valid = target != 255
predicted = logits.argmax(1)
return torch.bincount((3 * target[valid] + predicted[valid]).flatten(), minlength=9).reshape(3, 3).cpu()
def miou(matrix):
diag = matrix.diag().double()
union = matrix.sum(0) + matrix.sum(1) - diag
vals = [float(diag[i] / union[i]) for i in range(3) if union[i] > 0]
return sum(vals) / len(vals) if vals else None
def png_uri(image):
stream = io.BytesIO(); Image.fromarray(image).save(stream, format='PNG')
return 'data:image/png;base64,' + base64.b64encode(stream.getvalue()).decode('ascii')
@torch.no_grad()
def audit(name, rows):
model, head = load_model(name), load_probe(name)
prefix = 1 + int(getattr(model.config, 'num_register_tokens', 0))
side = SIDE // 14
prior, post, background, flagged = [], [], [], []
examples = []
original = torch.zeros((3, 3), dtype=torch.int64)
ablated = torch.zeros((3, 3), dtype=torch.int64)
for index, row in enumerate(rows):
x, y, pixels = preprocess(row)
captured = {}
def before_layernorm(_module, arguments):
captured['value'] = arguments[0].detach()
handle = model.layernorm.register_forward_pre_hook(before_layernorm)
try:
output = model(pixel_values=x[None], output_attentions=(index < 8))
finally:
handle.remove()
if 'value' not in captured:
raise ValueError('No se ha capturado la entrada de LayerNorm')
pre = captured['value'][:, prefix:]
post_features = output.last_hidden_state[:, prefix:]
if pre.shape[1:] != (side * side, 384) or post_features.shape != pre.shape:
raise ValueError('Forma inesperada de los tokens de parche')
pre_norm = pre.norm(dim=-1).reshape(side, side)
post_norm = post_features.norm(dim=-1).reshape(side, side)
threshold = 2 * pre_norm.median()
outliers = pre_norm > threshold
# Clase 1 es fondo tras el remapeo de la lección 19. Se promedia el
# porcentaje de píxeles de fondo por parche, ignorando 255.
valid = (y != 255).float()[None, None]
bg = (y == 1).float()[None, None]
valid_area = F.avg_pool2d(valid, 14, stride=14)[0, 0]
bg_area = F.avg_pool2d(bg, 14, stride=14)[0, 0] / valid_area.clamp_min(1e-8)
keep = valid_area > 0
prior.extend(pre_norm[keep].cpu().tolist())
post.extend(post_norm[keep].cpu().tolist())
background.extend(bg_area[keep].cpu().tolist())
flagged.extend(outliers[keep].cpu().tolist())
if head is not None:
features = post_features.transpose(1, 2).reshape(1, 384, side, side)
changed = features.masked_fill(outliers[None, None], 0.)
full = F.interpolate(head(features), size=(SIDE, SIDE), mode='bilinear', align_corners=False)
reduced = F.interpolate(head(changed), size=(SIDE, SIDE), mode='bilinear', align_corners=False)
original += confusion(full, y[None]); ablated += confusion(reduced, y[None])
if index < 8:
attention = None
if output.attentions:
last = output.attentions[-1]
if last is not None and last.ndim == 4 and last.shape[-1] == prefix + side * side:
attention = last[0, :, 0, prefix:].mean(0).reshape(side, side).cpu().tolist()
examples.append({'source': row['source'], 'sha256': row['sha256'], 'image': png_uri(pixels),
'pre_norm': pre_norm.cpu().tolist(), 'post_norm': post_norm.cpu().tolist(),
'outliers': outliers.cpu().tolist(), 'background_fraction': bg_area.cpu().tolist(),
'cls_to_patches_mean_heads': attention})
a = np.asarray(prior, dtype=np.float64)
b = np.asarray(post, dtype=np.float64)
bg = np.asarray(background, dtype=np.float64)
mask = np.asarray(flagged, dtype=bool)
if not len(a) or not np.isfinite(a).all() or not np.isfinite(b).all():
raise ValueError('Normas vacías o no finitas')
return {'model': name, 'weights': MODELS[name], 'examples': examples, 'tokens': len(a),
'pre_norm_quantiles': np.quantile(a, [0, .5, .9, .99, 1]).tolist(),
'post_norm_quantiles': np.quantile(b, [0, .5, .9, .99, 1]).tolist(),
'outlier_count': int(mask.sum()), 'threshold_rule': 'norma anterior a LN > 2 × mediana de la imagen',
'background_fraction_all': float(bg.mean()),
'background_fraction_outliers': float(bg[mask].mean()) if mask.any() else None,
'probe_ablation': {'original_miou': miou(original), 'zero_outliers_miou': miou(ablated),
'original_confusion': original.tolist(), 'zeroed_confusion': ablated.tolist(),
'note': 'Ablación fuera de distribución, no prueba causalidad.'}
if head is not None else {'status': 'sonda no disponible'},
'attention_note': 'Puede ser null si el backend no devuelve pesos; CLS y registros no son parches.'}
def main():
torch.set_num_threads(1)
rows = validation_rows()
DIRECTORY.mkdir(parents=True, exist_ok=True)
result = {'short': SHORT, 'data': DATA_REPO, 'revision': DATA_REV, 'resolution': SIDE,
'sources': [row['source'] for row in rows], 'runs': [],
'protocol': 'Norma L2 de tokens de parche ANTES de LayerNorm final; control después de LN. '
'Umbral heurístico prefijado por imagen, idéntico para ambos checkpoints. '
'Fondo según trimap, no equivalencia entre fondo y redundancia.',
'limitation': 'Son checkpoints distintos; la comparación no aísla registros. '
'No se presupone que existan outliers o desaparezcan. SHORT no concluye.'}
for name in MODELS:
result['runs'].append(audit(name, rows))
(DIRECTORY / 'register-audit.json').write_text(json.dumps(result, ensure_ascii=False), encoding='utf-8')
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
print('Guardado:', (DIRECTORY / 'register-audit.json').resolve())
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
Step 1 of 3. How is the product XQ transposed?
import numpy as np
def koleo_loss(z, eps=1e-8):
passimport numpy as np
def gram_anchoring_loss(student, anchor):
pass