Transfer learning: reusing pretrained networks
Compare linear probing, partial and full fine-tuning and LP-FT, manage BatchNorm state and evaluate transfer across domains with independent splits.
After this lesson you can
- Explain feature transferability and compare frozen and adapted representations.
- Implement discriminative learning-rate groups without duplicated parameters.
- Describe LP-FT and distinguish feature distortion from other explanations.
- Control BatchNorm parameters and running statistics during fine-tuning.
- Design domain-aware transfer comparisons with separate evaluation.
Before you start
A new problem, an existing representation
You have a few labeled images and need to classify objects that were not training classes. A pretrained CNN can turn each image into a vector already capturing edges, textures and more complex combinations. You can train a small classifier on those vectors or tune part of the network. The choice depends on data, domain shift, budget and how the system will be evaluated.
Transfer learning reuses knowledge learned on a source task or distribution for another target task. It does not assume identical labels. Adaptation must also respect model preprocessing and keep training, validation and test separate. A test image already used to choose a strategy ceases to be an independent evaluation of that choice.
What transfers and where to cut
Feature transferability asks how much a source-learned representation helps a target task under a given protocol. Early layers of many CNNs respond to edges and local patterns; deep layers adapt to pretraining classes and objective. This hierarchy is an empirical tendency, not a guarantee that every early channel is generic or every deep channel useless outside the source.
Yosinski and colleagues divided ImageNet’s 1000 classes into two 500-class tasks, with approximately 645,000 examples each, and transferred varying numbers of layers from an eight-layer CNN. They compared random class splits with a natural-versus-artificial class split. In the random split, the baseline for one 500-class task achieved 62.5% top-1; when freezing and rebuilding the top of the same task, the drop was especially visible when cutting at intermediate layers. When transferring between tasks, the first two layers retained approximately baseline performance, while layers 4 through 7 showed a larger drop.
The authors identified two distinct mechanisms: specialization of deep features and optimization difficulty when separating jointly adapted layers. Distinguishing them requires comparison not only with a network trained from scratch, but also transfer between networks on the same task. Their conclusions describe those architectures and tasks; they do not establish a universal optimal depth for a current ResNet-50.
Freeze, tune and allocate rates
Fine-tuning strategies range from keeping the extractor fixed to updating it fully. With a linear probe, stays fixed and only and are tuned: . The probe measures linear separability under its own data, regularization and optimization; it does not measure all information a nonlinear classifier might extract. A k-NN on the same features tests another decision rule and requires specifying distance, normalization and chosen on validation.
Freezing early stages and tuning later ones reduces trainable parameters and adapts features near output. Full tuning offers more degrees of freedom and greater risk of overfitting or modifying useful features. With discriminative rates, assign a lower rate to earlier stages and higher to the head. For stages ordered input to output, one convention is with and ; state whether the head receives or another rate. Warmup can gradually increase those rates initially without changing their proportion.
Choose parameter groups without duplicates and check both those updated and those remaining frozen. Changing requires_grad does not automatically enable evaluation mode for stateful layers. It is also not equivalent to extracting features once when random augmentations are present: a fixed cache keeps only views calculated when built.
Probe first, then fine-tune
The LP-FT recipe first trains a linear probe with the extractor frozen, then uses that head to start full fine-tuning. For cross-entropy with probabilities and one-hot label , the gradient with respect to representation is . With a random head, its orientation influences the gradient reaching the extractor from the first step; if the entire network updates, a useful feature can change while the head is still adapting. An already trained probe changes that initial condition but guarantees neither zero extractor gradient nor out-of-distribution improvement for every task.
In Kumar and colleagues, analysis of a two-layer linear network shows a distortion mechanism under specific assumptions. Their tables 1 and 2 give mean ID accuracy of 82.9% for probing and 85.1% for fine-tuning, and mean OOD accuracy of 66.2% and 59.3% respectively; LP-FT reaches 68.9% OOD. ID and OOD means are calculated over six and ten evaluations respectively, not the same rows. These are results of that study: inspect each dataset and do not turn the average into a promise for every domain shift.
BatchNorm is more than a pair of parameters
Managing BatchNorm during tuning requires separating two decisions. and are parameters that can be trained or frozen; running means and variances are state updated in training mode. Setting parameters to requires_grad=False does not stop statistics changing. Conversely, with track_running_stats=True and buffers available, putting a BatchNorm layer in eval() uses stored statistics but does not automatically freeze and . If track_running_stats=False, it uses batch statistics in evaluation too, as PyTorch specifies.
With small batches, estimates can be noisy and depend on batch composition. One option is to retain pretrained statistics: after every global call to model.train(), put selected BatchNorm layers back in eval(). Another is updating statistics with target-domain training data, without labels if appropriate, then evaluating with those statistics fixed; do not calibrate them on test if you want separate evaluation. With usual momentum, running statistics update via an exponential mean and depend on order and momentum value: one pass does not automatically calculate the exact global mean. GroupNorm avoids batch running statistics, but replacing BatchNorm in a pretrained model changes the function and does not automatically preserve behavior. Compare results rather than assuming equivalence.
Better on source, better after transfer?
Kornblith and colleagues compared 16 networks across 12 classification datasets. Among networks retrained under a common protocol, they calculated Pearson correlation of logit-transformed accuracies averaged across datasets: 0.99 for fixed features and 0.96 for fine-tuning. With public checkpoints and fixed features, appendix B reports 0.37. The same study shows that pretraining regularization details can harm fixed features and some fine-grained tasks receive little benefit. Aggregate correlation does not guarantee every model’s ranking on a new dataset.
Big Transfer studies large-scale supervised pretraining and an adaptation recipe under different data regimes. In contrast, He and colleagues found that for their COCO detection and segmentation tasks, training from random initialization can match pretrained models if iterations increase. These experiments are not contradictory: tasks, data, models and budgets differ. Measure both final quality and compute needed to reach it.
Labs
Four strategies on Flowers-102
This cell downloads official ResNet50_Weights.IMAGENET1K_V2 weights and a pinned-revision Flowers-102 mirror to common caches. It uses those weights’ preprocessing and respects mirror splits, except identical files discarded with priority for training, then validation and finally test. The full check found four duplicate copies in test; all four had the same label as the first occurrence. Code records hashes and indices and stops on incompatible labels. This check does not detect recodings or prove independence from pretraining. Kornblith and colleagues, appendix H, detected one Flowers duplicate in training and none in test with their detector: that result does not guarantee there are no others.
Compare a linear head, full tuning, partial tuning with discriminative rates and LP-FT. After model.train(), BatchNorm layers return to eval() to retain statistics; affine parameters of trainable stages still receive gradients. Selection uses validation loss and the selected checkpoint is evaluated on test. PCA is fitted once to pretrained features of training images; it projects the same validation images at each checkpoint. It does not measure causality or OOD generalization.
By default the reader runs three seeds and 800 steps per strategy. With ORYON_VERIFY_SHORT=1, verification uses one seed, 20 steps and 204/102/102 training, validation and test images. In that run all four strategies gave 3.92% on test after selecting each checkpoint on validation. Models have not converged: that equality does not prove equivalence. Since several strategies are inspected, both selection and test readings are exploratory; reserve another set for confirmatory evaluation of a later choice.
"""Cuatro estrategias de transferencia con ResNet-50 en Flowers-102.
Requiere torch, torchvision, numpy, pyarrow, Pillow y huggingface_hub; CUDA.
El espejo no es el origen oficial: se fija la revisión y se preservan sus
divisiones train/validation/test. Pueden existir duplicados u otras relaciones
con ImageNet; no se demuestra independencia del preentrenamiento.
ORYON_VERIFY_SHORT=1 reduce datos, pasos y semillas para verificar el circuito.
No presupone convergencia ni que una estrategia gane. ORYON_TRANSFER_OUTPUT
controla el JSON, cuyos valores salen de esta ejecución.
"""
import gc
import hashlib
import io
import json
import os
import time
from pathlib import Path
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
import numpy as np
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
from PIL import Image
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.models import ResNet50_Weights, resnet50
torch.set_num_threads(1)
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark = False
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
amp = device.type == 'cuda' and torch.cuda.is_bf16_supported()
seed_list = [16141] if short else [16141, 16142, 16143]
steps = 20 if short else 800
batch_size = 4 if short else 16
revision = '06fcc9a13ee3f84cc7f36fa0eef10df2c7f8750f'
repo = 'Donghyun99/Oxford-Flower-102'
files = {'train': 'data/train-00000-of-00001-95813d8dab877ff5.parquet',
'validation': 'data/validation-00000-of-00001-a2ccf8138610462c.parquet',
'test': 'data/test-00000-of-00001-1cc6f065cd5391ec.parquet'}
weights = ResNet50_Weights.IMAGENET1K_V2
preprocess = weights.transforms()
def read_split(split, per_class=None):
path = hf_hub_download(repo_id=repo, repo_type='dataset', filename=files[split], revision=revision)
parquet = pq.ParquetFile(path)
labels = np.concatenate([b.column(0).to_numpy() for b in parquet.iter_batches(batch_size=512, columns=['label'])]).astype(np.int64)
rng = np.random.default_rng({'train': 16140, 'validation': 16141, 'test': 16142}[split])
groups = [rng.permutation(np.flatnonzero(labels == k)) for k in range(102)]
if any(len(group) == 0 or (per_class is not None and len(group) < per_class) for group in groups):
raise ValueError('Faltan ejemplos de una clase en '+split)
indices = np.concatenate([group if per_class is None else group[:per_class] for group in groups])
positions = {int(idx): i for i, idx in enumerate(indices)}
images = [None]*len(indices)
offset = 0
for batch in parquet.iter_batches(batch_size=64, columns=['image']):
for j in range(batch.num_rows):
pos = positions.get(offset+j)
if pos is not None:
images[pos] = batch.column(0)[j].as_py()['bytes']
offset += batch.num_rows
if any(image is None for image in images):
raise RuntimeError('Faltan imágenes en '+split)
return {'split': split, 'images': images, 'labels': labels[indices], 'source_indices': indices.tolist()}
def deduplicate_splits(datasets, classes):
order = ('train', 'validation', 'test')
if set(datasets) != set(order) or classes <= 0:
raise ValueError('Se requieren train, validation y test y clases positivas')
seen = {}
cleaned = {}
removed = []
for split in order:
data = datasets[split]
images, labels, indices = data['images'], data['labels'], data['source_indices']
if len(images) != len(labels) or len(images) != len(indices):
raise ValueError('Imágenes, etiquetas e índices no están alineados en ' + split)
keep = []
for i, (image, label, source_index) in enumerate(zip(images, labels, indices)):
label = int(label)
if not 0 <= label < classes:
raise ValueError('Etiqueta fuera de rango en ' + split)
digest = hashlib.sha256(image).hexdigest()
current = {'split': split, 'source_index': int(source_index), 'label': label}
if digest in seen:
first = seen[digest]
if first['label'] != label:
raise ValueError(f'Hash {digest} con etiquetas incompatibles: {first} y {current}')
removed.append({'sha256': digest, 'kept': first.copy(), 'removed': current})
else:
seen[digest] = current
keep.append(i)
cleaned[split] = {**data, 'images': [images[i] for i in keep],
'labels': np.asarray(labels)[keep].copy(),
'source_indices': [int(indices[i]) for i in keep]}
present = set(map(int, cleaned[split]['labels']))
missing = sorted(set(range(classes)) - present)
if missing:
raise ValueError(f'Faltan clases en {split} tras deduplicar: {missing}')
audit = {'priority': list(order), 'policy': 'primera aparición por SHA-256',
'counts_before': {s: len(datasets[s]['images']) for s in order},
'counts_after': {s: len(cleaned[s]['images']) for s in order},
'removed': removed}
return cleaned, audit
def fetch(data, indices, flip_generator=None):
tensors = []
for idx in indices:
with Image.open(io.BytesIO(data['images'][int(idx)])) as image:
tensors.append(preprocess(image.convert('RGB')))
x = torch.stack(tensors)
if flip_generator is not None:
flip = torch.rand(len(x), generator=flip_generator) < .5
x = torch.where(flip[:, None, None, None], x.flip(-1), x)
y = torch.from_numpy(data['labels'][np.asarray(indices, dtype=np.int64)].copy())
return x.to(device, memory_format=torch.channels_last), y.to(device)
def features(model, x):
x = model.maxpool(model.relu(model.bn1(model.conv1(x))))
x = model.layer4(model.layer3(model.layer2(model.layer1(x))))
return torch.flatten(model.avgpool(x), 1)
def freeze_bn_stats(model):
for module in model.modules():
if isinstance(module, nn.modules.batchnorm._BatchNorm):
module.eval()
def configure(model, mode):
for parameter in model.parameters():
parameter.requires_grad = False
for parameter in model.fc.parameters():
parameter.requires_grad = True
if mode == 'all':
for parameter in model.parameters():
parameter.requires_grad = True
groups = [{'params': [p for name, p in model.named_parameters() if not name.startswith('fc.')], 'base_lr': 1e-4},
{'params': list(model.fc.parameters()), 'base_lr': 1e-2}]
elif mode == 'partial':
for stage in (model.layer3, model.layer4):
for parameter in stage.parameters():
parameter.requires_grad = True
groups = [{'params': list(model.layer3.parameters()), 'base_lr': 2e-5},
{'params': list(model.layer4.parameters()), 'base_lr': 1e-4},
{'params': list(model.fc.parameters()), 'base_lr': 1e-2}]
elif mode == 'linear':
groups = [{'params': list(model.fc.parameters()), 'base_lr': 1e-2}]
else:
raise ValueError(mode)
ids = [id(p) for group in groups for p in group['params']]
assert len(ids) == len(set(ids)) and set(ids) == {id(p) for p in model.parameters() if p.requires_grad}
for group in groups:
group['lr'] = group['base_lr']
return torch.optim.SGD(groups, momentum=.9, weight_decay=.0001)
def logits_and_features(model, data, indices):
model.eval()
outputs, vectors = [], []
with torch.no_grad():
for batch in np.array_split(np.asarray(indices, dtype=np.int64), max(1, (len(indices)+15)//16)):
if not len(batch):
continue
x, _ = fetch(data, batch)
with torch.autocast('cuda', dtype=torch.bfloat16, enabled=amp):
z = features(model, x)
outputs.append(model.fc(z).float().cpu())
vectors.append(z.float().cpu())
return torch.cat(outputs), torch.cat(vectors)
def evaluate(model, data):
logits, _ = logits_and_features(model, data, np.arange(len(data['images'])))
labels = torch.from_numpy(data['labels'])
if not bool(torch.isfinite(logits).all()):
return {'accuracy': None, 'loss': None}
loss = F.cross_entropy(logits, labels)
if not bool(torch.isfinite(loss)):
return {'accuracy': None, 'loss': None}
return {'accuracy': float((logits.argmax(1)==labels).float().mean()), 'loss': float(loss)}
def reference_projection(model, train, valid):
train_ids = np.linspace(0, len(train['images'])-1, min(24, len(train['images'])), dtype=int)
valid_ids = np.linspace(0, len(valid['images'])-1, min(24, len(valid['images'])), dtype=int)
_, train_features = logits_and_features(model, train, train_ids)
_, valid_features = logits_and_features(model, valid, valid_ids)
matrix = train_features.numpy().astype(np.float64)
mean = matrix.mean(0)
_, _, vh = np.linalg.svd(matrix-mean, full_matrices=False)
basis = vh[:2].T.copy()
for column in range(2):
pivot = int(np.argmax(np.abs(basis[:, column])))
if basis[pivot, column] < 0:
basis[:, column] *= -1
return {'mean': mean, 'basis': basis, 'valid_ids': valid_ids,
'valid_features': valid_features.numpy().astype(np.float64)}
def snapshot(model, valid, reference):
_, f = logits_and_features(model, valid, reference['valid_ids'])
x = f.numpy().astype(np.float64)
prior = reference['valid_features']
coords = (x-reference['mean']) @ reference['basis']
change = np.linalg.norm(x-prior)/max(np.linalg.norm(prior), 1e-12)
return {'coords': coords.tolist(), 'relative_feature_change': float(change)}
def run_strategy(strategy, seed, train, valid, test, reference):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
model = resnet50(weights=weights)
model.fc = nn.Linear(model.fc.in_features, 102)
model = model.to(device=device, memory_format=torch.channels_last)
mode = 'linear' if strategy in ('linear', 'lp_ft') else ('partial' if strategy == 'partial' else 'all')
optimizer = configure(model, mode)
batch_rng = torch.Generator().manual_seed(seed+1000)
flip_rng = torch.Generator().manual_seed(seed+2000)
checkpoints = {1, steps//4, steps//2, 3*steps//4, steps}
best_loss, best_state, best_step = float('inf'), None, None
lp_state, lp_loss, lp_step = None, float('inf'), None
history, failure = [], None
torch.cuda.synchronize()
t0 = time.perf_counter()
baseline_memory = torch.cuda.memory_allocated()
torch.cuda.reset_peak_memory_stats()
for step in range(1, steps+1):
if strategy == 'lp_ft' and step == steps//2+1:
if lp_state is None:
failure = {'step': step, 'reason': 'no hay checkpoint válido de la sonda lineal'}
break
model.load_state_dict(lp_state)
optimizer = configure(model, 'all')
mode = 'all'
best_loss, best_state, best_step = float('inf'), None, None
model.train()
freeze_bn_stats(model)
assert all(not module.training for module in model.modules() if isinstance(module, nn.modules.batchnorm._BatchNorm))
phase_step = step-(steps//2 if strategy == 'lp_ft' and mode == 'all' else 0)
warm = min(20, max(1, steps//20))
for group in optimizer.param_groups:
group['lr'] = group['base_lr']*min(1., phase_step/warm)
idx = torch.randint(0, len(train['images']), (batch_size,), generator=batch_rng).numpy()
x, y = fetch(train, idx, flip_rng)
optimizer.zero_grad(set_to_none=True)
with torch.autocast('cuda', dtype=torch.bfloat16, enabled=amp):
if mode == 'linear':
with torch.no_grad():
z = features(model, x)
output = model.fc(z)
else:
output = model(x)
loss = F.cross_entropy(output, y)
if not bool(torch.isfinite(loss)):
failure = {'step': step, 'reason': 'pérdida no finita'}
break
loss.backward()
grads = [p.grad for p in model.parameters() if p.requires_grad]
if any(g is None for g in grads) or not bool(torch.stack([torch.isfinite(g).all() for g in grads if g is not None]).all()):
failure = {'step': step, 'reason': 'gradiente ausente o no finito'}
break
optimizer.step()
if step in checkpoints:
metric = evaluate(model, valid)
if metric['accuracy'] is None:
failure = {'step': step, 'reason': 'validación no finita'}
break
row = {'step': step, 'phase': mode, 'batch_loss': float(loss.detach()), 'validation': metric,
'trainable_parameters': sum(p.numel() for p in model.parameters() if p.requires_grad),
'projection': snapshot(model, valid, reference)}
history.append(row)
if strategy == 'lp_ft' and mode == 'linear' and metric['loss'] < lp_loss:
lp_loss, lp_step = metric['loss'], step
lp_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
if (strategy != 'lp_ft' or mode == 'all') and metric['loss'] < best_loss:
best_loss, best_step = metric['loss'], step
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
torch.cuda.synchronize()
elapsed = time.perf_counter()-t0
peak = torch.cuda.max_memory_allocated()
result = {'strategy': strategy, 'seed': seed, 'history': history, 'failure': failure,
'best_step': best_step, 'lp_step': lp_step, 'wall_seconds_with_validation': elapsed,
'cuda_baseline_allocated_bytes': baseline_memory, 'cuda_peak_allocated_bytes': peak}
if failure is None and best_state is not None:
model.load_state_dict(best_state)
result['test_exploratory'] = evaluate(model, test)
optimizer.zero_grad(set_to_none=True)
optimizer.state.clear()
del model, optimizer, lp_state, best_state
gc.collect()
torch.cuda.empty_cache()
return result
def main():
if device.type != 'cuda':
raise RuntimeError('Este laboratorio requiere CUDA')
train = read_split('train', 2 if short else None)
valid = read_split('validation', 1 if short else None)
test = read_split('test', 1 if short else None)
clean, dedup = deduplicate_splits({'train': train, 'validation': valid, 'test': test}, 102)
train, valid, test = (clean[s] for s in ('train', 'validation', 'test'))
print('Deduplicación SHA-256:', dedup, flush=True)
# La PCA de referencia se ajusta exclusivamente a imágenes de entrenamiento.
base = resnet50(weights=weights)
base.fc = nn.Linear(base.fc.in_features, 102)
base = base.to(device=device, memory_format=torch.channels_last).eval()
reference = reference_projection(base, train, valid)
original = snapshot(base, valid, reference)
del base
gc.collect()
torch.cuda.empty_cache()
output = {'protocol': {'dataset': repo, 'revision': revision, 'short': short, 'steps': steps,
'batch_size': batch_size, 'seeds': seed_list, 'classes': 102,
'counts': {'train': len(train['images']), 'validation': len(valid['images']), 'test': len(test['images'])},
'deduplication': dedup,
'source_indices': {s: clean[s]['source_indices'] for s in clean},
'source_labels': {s: clean[s]['labels'].tolist() for s in clean},
'weights': 'ResNet50_Weights.IMAGENET1K_V2', 'weights_url': weights.url,
'preprocess': 'weights.transforms(): resize 232, crop central 224, normalización ImageNet',
'bn': 'todas las estadísticas en eval; gamma y beta siguen entrenables si se descongela su etapa',
'split_note': 'splits del espejo; deduplicación SHA-256 con prioridad train, validación y test; no detecta casi duplicados ni coincidencias con ImageNet',
'selection': 'menor pérdida de validación; LP-FT selecciona sonda y luego checkpoint de ajuste',
'pca': 'base fija ajustada a características preentrenadas de 24 imágenes de train; se proyectan imágenes de validación',
'test': 'exploratorio tras selección; no prueba rendimiento fuera de distribución',
'gpu': torch.cuda.get_device_name(device), 'torch': str(torch.__version__), 'cuda': str(torch.version.cuda),
'cudnn': torch.backends.cudnn.version(), 'amp_bfloat16': amp},
'reference': {'validation_source_indices': [valid['source_indices'][int(i)] for i in reference['valid_ids']],
'labels': valid['labels'][reference['valid_ids']].tolist(), 'initial': original},
'runs': []}
outpath = Path(os.environ.get('ORYON_TRANSFER_OUTPUT', 'm16-l14-transfer.json'))
for strategy in ('linear', 'all', 'partial', 'lp_ft'):
for seed in seed_list:
run = run_strategy(strategy, seed, train, valid, test, reference)
output['runs'].append(run)
outpath.write_text(json.dumps(output, ensure_ascii=False, indent=2, allow_nan=False), encoding='utf-8')
print(json.dumps(run, ensure_ascii=False), flush=True)
if __name__ == '__main__':
main()npm run lab and open the connection link.Probes and freeze sweep in two domains
The next cell extracts features from five stages of the pretrained model. For each stage it fits a linear probe with standardization statistics calculated only on training and compares cosine k-NN with k=5 fixed in advance. Probes do not update the extractor. A second experiment does tune it: freeze zero to four consecutive groups, with the first combining stem and layer1; four freezes the whole extractor. It uses the same batches and augmentations per seed across conditions, selects on validation and then evaluates test.
Pinned-revision mirror splits are respected except identical copies discarded under the same policy above; the full check found no exact duplicates in EuroSAT. Flowers has 102 classes; RGB EuroSAT has 10. Their accuracies do not form a common domain-distance scale. Geographic independence of EuroSAT tiles and absence of overlap or near-duplicates with ImageNet are also not guaranteed. Robust spatial evaluation requires splitting by location or scene when those metadata are available.
Short mode uses one seed, two training images per class and one per class for validation and test; it trains each probe for 40 steps and each sweep condition for 20. In that verification, the final-stage EuroSAT probe produced test loss 266.02: with only 20 training images and standardization fitted to them, the result is numerically finite but unstable. Test is repeatedly shown for stages and strategies, so it is exploratory. Full mode uses available splits and three seeds, without guaranteeing a winner or moving the optimum in any direction.
"""Sondas, k-NN y barrido de congelación de ResNet-50 en dos tareas.
Requiere torch, torchvision, numpy, pyarrow, Pillow y huggingface_hub.
Los espejos y pesos se descargan a sus cachés comunes. ORYON_VERIFY_SHORT=1
reduce el conjunto y los pasos: verifica el circuito, no mide convergencia.
Las divisiones son las de los espejos, no una garantía de independencia
geográfica en EuroSAT ni de ausencia de solapamiento con ImageNet. El cotejo
SHA-256 detecta bytes idénticos entre splits, no imágenes recodificadas.
Flowers tiene 102 clases y EuroSAT 10: sus accuracies no son una escala de
distancia entre dominios. La sonda de una etapa no es fine-tuning parcial.
Kornblith et al., apéndice H, detectan un duplicado de Flowers en train y
ninguno en test bajo su propio protocolo; eso no prueba ausencia de otros.
https://arxiv.org/html/1805.08974
"""
import gc
import hashlib
import io
import json
import os
from pathlib import Path
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
import numpy as np
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
from PIL import Image
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.models import ResNet50_Weights, resnet50
torch.set_num_threads(1)
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark = False
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
amp = device.type == 'cuda' and torch.cuda.is_bf16_supported()
weights = ResNet50_Weights.IMAGENET1K_V2
preprocess = weights.transforms()
seeds = [16151] if short else [16151, 16152, 16153]
steps = 40 if short else 800
batch_size = 4 if short else 16
specs = {
'flowers': {
'repo': 'Donghyun99/Oxford-Flower-102',
'revision': '06fcc9a13ee3f84cc7f36fa0eef10df2c7f8750f',
'classes': 102,
'files': {
'train': 'data/train-00000-of-00001-95813d8dab877ff5.parquet',
'validation': 'data/validation-00000-of-00001-a2ccf8138610462c.parquet',
'test': 'data/test-00000-of-00001-1cc6f065cd5391ec.parquet',
},
},
'eurosat': {
'repo': 'timm/eurosat-rgb',
'revision': '435287cde10a365a27b0f2e183dc96aa6c28f302',
'classes': 10,
'files': {s: f'data/{s}-00000-of-00001.parquet'
for s in ('train', 'validation', 'test')},
},
}
def read_split(spec, split):
path = hf_hub_download(repo_id=spec['repo'], repo_type='dataset',
filename=spec['files'][split], revision=spec['revision'])
parquet = pq.ParquetFile(path)
labels = np.concatenate([b.column(0).to_numpy() for b in
parquet.iter_batches(batch_size=512, columns=['label'])]).astype(np.int64)
rng = np.random.default_rng({'train': 16140, 'validation': 16141, 'test': 16142}[split])
groups = [rng.permutation(np.flatnonzero(labels == c)) for c in range(spec['classes'])]
n = (2 if split == 'train' else 1) if short else None
if any(len(g) == 0 or (n is not None and len(g) < n) for g in groups):
raise ValueError('Faltan ejemplos de alguna clase en ' + split)
indices = np.concatenate([g if n is None else g[:n] for g in groups])
positions = {int(idx): i for i, idx in enumerate(indices)}
images = [None] * len(indices)
offset = 0
for batch in parquet.iter_batches(batch_size=64, columns=['image']):
for j in range(batch.num_rows):
pos = positions.get(offset + j)
if pos is not None:
images[pos] = batch.column(0)[j].as_py()['bytes']
offset += batch.num_rows
if any(x is None for x in images):
raise RuntimeError('Faltan bytes de imágenes en ' + split)
return {'images': images, 'labels': labels[indices], 'source_indices': indices.tolist()}
def deduplicate_splits(datasets, classes):
order = ('train', 'validation', 'test')
if set(datasets) != set(order) or classes <= 0:
raise ValueError('Se requieren train, validation y test y clases positivas')
seen = {}
cleaned = {}
removed = []
for split in order:
data = datasets[split]
images, labels, indices = data['images'], data['labels'], data['source_indices']
if len(images) != len(labels) or len(images) != len(indices):
raise ValueError('Imágenes, etiquetas e índices no están alineados en ' + split)
keep = []
for i, (image, label, source_index) in enumerate(zip(images, labels, indices)):
label = int(label)
if not 0 <= label < classes:
raise ValueError('Etiqueta fuera de rango en ' + split)
digest = hashlib.sha256(image).hexdigest()
current = {'split': split, 'source_index': int(source_index), 'label': label}
if digest in seen:
first = seen[digest]
if first['label'] != label:
raise ValueError(f'Hash {digest} con etiquetas incompatibles: {first} y {current}')
removed.append({'sha256': digest, 'kept': first.copy(), 'removed': current})
else:
seen[digest] = current
keep.append(i)
cleaned[split] = {**data, 'images': [images[i] for i in keep],
'labels': np.asarray(labels)[keep].copy(),
'source_indices': [int(indices[i]) for i in keep]}
present = set(map(int, cleaned[split]['labels']))
missing = sorted(set(range(classes)) - present)
if missing:
raise ValueError(f'Faltan clases en {split} tras deduplicar: {missing}')
audit = {'priority': list(order), 'policy': 'primera aparición por SHA-256',
'counts_before': {s: len(datasets[s]['images']) for s in order},
'counts_after': {s: len(cleaned[s]['images']) for s in order},
'removed': removed}
return cleaned, audit
def extract(model, data):
# Las cinco etapas comparten una sola pasada. Pooling global sobre espacio.
captured = {}
layers = {'stem': model.maxpool, 'layer1': model.layer1, 'layer2': model.layer2,
'layer3': model.layer3, 'layer4': model.layer4}
def hook(name):
def capture(_module, _inputs, output):
captured[name] = output.detach().float().mean(dim=(2, 3)).cpu()
return capture
handles = [module.register_forward_hook(hook(name)) for name, module in layers.items()]
chunks = {name: [] for name in layers}
try:
for start in range(0, len(data['images']), batch_size):
tensors = []
for raw in data['images'][start:start + batch_size]:
with Image.open(io.BytesIO(raw)) as image:
tensors.append(preprocess(image.convert('RGB')))
x = torch.stack(tensors).to(device)
with torch.no_grad(), torch.autocast(device_type=device.type, enabled=amp, dtype=torch.bfloat16):
model(x)
for name in chunks:
chunks[name].append(captured.pop(name))
finally:
for handle in handles:
handle.remove()
return {name: torch.cat(parts) for name, parts in chunks.items()}
def eval_probe(layer, x, y, classes):
total_loss, correct = 0., 0
with torch.no_grad():
for start in range(0, len(x), 256):
logits = layer(x[start:start + 256].to(device))
target = y[start:start + 256].to(device)
if not bool(torch.isfinite(logits).all()):
return None
batch_loss = F.cross_entropy(logits, target, reduction='sum')
if not bool(torch.isfinite(batch_loss)):
return None
total_loss += batch_loss.item()
correct += (logits.argmax(1) == target).sum().item()
return {'loss': total_loss / len(y), 'accuracy': correct / len(y), 'n': len(y)}
def fit_probe(train, valid, test, labels, classes, seed):
# La escala se aprende exclusivamente del conjunto de entrenamiento.
mean = train.mean(0, keepdim=True)
scale = train.std(0, unbiased=False, keepdim=True).clamp_min(1e-6)
x = [(z - mean) / scale for z in (train, valid, test)]
y = [torch.from_numpy(labels[s].copy()).long() for s in ('train', 'validation', 'test')]
torch.manual_seed(seed)
layer = nn.Linear(train.shape[1], classes).to(device)
optimizer = torch.optim.AdamW(layer.parameters(), lr=.001, weight_decay=.01)
generator = torch.Generator().manual_seed(seed + 10000)
checkpoints = sorted(set([1, steps // 4, steps // 2, 3 * steps // 4, steps]))
history, best, best_state, failure = [], None, None, None
for step in range(1, steps + 1):
idx = torch.randint(len(x[0]), (min(64, len(x[0])),), generator=generator)
logits = layer(x[0][idx].to(device))
loss = F.cross_entropy(logits, y[0][idx].to(device))
optimizer.zero_grad(set_to_none=True)
if not bool(torch.isfinite(loss)):
failure = {'step': step, 'reason': 'pérdida de entrenamiento no finita'}
break
loss.backward()
if any(p.grad is None or not bool(torch.isfinite(p.grad).all()) for p in layer.parameters()):
failure = {'step': step, 'reason': 'gradiente ausente o no finito'}
break
optimizer.step()
if step in checkpoints:
validation = eval_probe(layer, x[1], y[1], classes)
if validation is None:
failure = {'step': step, 'reason': 'validación no finita'}
break
history.append({'step': step, 'validation': validation})
if best is None or validation['loss'] < best['loss']:
best = {'step': step, **validation}
best_state = {k: v.detach().cpu().clone() for k, v in layer.state_dict().items()}
result = {'seed': seed, 'history': history, 'selected_validation': best, 'failure': failure}
if best_state is not None and failure is None:
layer.load_state_dict(best_state)
result['test_after_selection'] = eval_probe(layer, x[2], y[2], classes)
if result['test_after_selection'] is None:
result['test_failure'] = 'test no finito tras seleccionar por validación'
return result
def knn(train, query, labels, targets, classes, k=5):
# Coseno sin ajustar sobre el test; k fijo. Votos empatados: clase menor.
train = F.normalize(train.to(device), dim=1)
query = F.normalize(query.to(device), dim=1)
labels = torch.from_numpy(labels.copy()).long().to(device)
predictions = []
with torch.no_grad():
for start in range(0, len(query), 128):
q = query[start:start + 128]
values = torch.full((len(q), k), -float('inf'), device=device)
indices = torch.zeros((len(q), k), dtype=torch.long, device=device)
for pos in range(0, len(train), 1024):
similarities = q @ train[pos:pos + 1024].T
candidate_values = torch.cat((values, similarities), dim=1)
candidate_indices = torch.cat((indices, torch.arange(pos, pos + similarities.shape[1], device=device).expand(len(q), -1)), dim=1)
values, chosen = candidate_values.topk(k, dim=1)
indices = candidate_indices.gather(1, chosen)
votes = (labels[indices, None] == torch.arange(classes, device=device)).sum(dim=1)
predictions.append(votes.argmax(1).cpu())
predictions = torch.cat(predictions)
return {'accuracy': (predictions == torch.from_numpy(targets.copy())).float().mean().item(),
'n': len(targets), 'k': k}
def batches(data, indices, generator=None):
images = []
for idx in indices:
with Image.open(io.BytesIO(data['images'][int(idx)])) as image:
images.append(preprocess(image.convert('RGB')))
x = torch.stack(images)
if generator is not None:
flipped = torch.rand(len(x), generator=generator) < .5
x = torch.where(flipped[:, None, None, None], x.flip(-1), x)
y = torch.from_numpy(data['labels'][np.asarray(indices, dtype=np.int64)].copy()).long()
return x.to(device), y.to(device)
def evaluate_transfer(model, data):
model.eval()
loss, correct = 0., 0
with torch.no_grad():
for start in range(0, len(data['images']), batch_size):
idx = range(start, min(start + batch_size, len(data['images'])))
x, y = batches(data, idx)
with torch.autocast(device_type=device.type, enabled=amp, dtype=torch.bfloat16):
logits = model(x)
if not bool(torch.isfinite(logits).all()):
return None
loss += F.cross_entropy(logits.float(), y, reduction='sum').item()
correct += (logits.argmax(1) == y).sum().item()
n = len(data['images'])
return {'loss': loss / n, 'accuracy': correct / n, 'n': n}
def freeze_sweep(data, classes, frozen, seed):
# Cuatro grupos consecutivos: (tallo + layer1), layer2, layer3, layer4.
# frozen=0 ajusta toda la red; frozen=4 entrena solo la cabeza.
torch.manual_seed(seed)
model = resnet50(weights=weights)
model.fc = nn.Linear(model.fc.in_features, classes)
groups = ((model.conv1, model.bn1, model.layer1), (model.layer2,),
(model.layer3,), (model.layer4,))
for group in groups[:frozen]:
for module in group:
for parameter in module.parameters():
parameter.requires_grad_(False)
model = model.to(device)
backbone = [p for n, p in model.named_parameters() if not n.startswith('fc.') and p.requires_grad]
params = [{'params': model.fc.parameters(), 'lr': .01}]
if backbone:
params.append({'params': backbone, 'lr': .0001})
optimizer = torch.optim.SGD(params, momentum=.9, weight_decay=.0001)
batch_rng = torch.Generator().manual_seed(seed + 20000)
flip_rng = torch.Generator().manual_seed(seed + 30000)
sweep_steps = 20 if short else 800
checkpoints = sorted(set((1, sweep_steps // 4, sweep_steps // 2, 3 * sweep_steps // 4, sweep_steps)))
history, best, state, failure = [], None, None, None
for step in range(1, sweep_steps + 1):
model.train()
# Las estadísticas móviles no se recalculan; los parámetros afines
# siguen entrenables si su bloque no está congelado.
for module in model.modules():
if isinstance(module, nn.modules.batchnorm._BatchNorm):
module.eval()
idx = torch.randint(len(data['train']['images']), (batch_size,), generator=batch_rng).numpy()
x, y = batches(data['train'], idx, flip_rng)
optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type=device.type, enabled=amp, dtype=torch.bfloat16):
loss = F.cross_entropy(model(x), y)
if not bool(torch.isfinite(loss)):
failure = {'step': step, 'reason': 'pérdida no finita'}
break
loss.backward()
grads = [p.grad for p in model.parameters() if p.requires_grad]
if any(g is None or not bool(torch.isfinite(g).all()) for g in grads):
failure = {'step': step, 'reason': 'gradiente ausente o no finito'}
break
optimizer.step()
if step in checkpoints:
metric = evaluate_transfer(model, data['validation'])
if metric is None:
failure = {'step': step, 'reason': 'validación no finita'}
break
history.append({'step': step, 'validation': metric})
if best is None or metric['loss'] < best['loss']:
best = {'step': step, **metric}
state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
result = {'frozen_groups': frozen, 'seed': seed, 'history': history, 'failure': failure,
'trainable_parameters': sum(p.numel() for p in model.parameters() if p.requires_grad),
'selected_validation': best}
if state is not None and failure is None:
model.load_state_dict(state)
result['test_after_selection'] = evaluate_transfer(model, data['test'])
del model, optimizer, state
gc.collect()
if device.type == 'cuda':
torch.cuda.empty_cache()
return result
def main():
model = resnet50(weights=weights).to(device).eval()
for p in model.parameters():
p.requires_grad_(False)
output = {'protocol': {
'weights': 'ResNet50_Weights.IMAGENET1K_V2',
'preprocess': 'weights.transforms(): resize 232, center crop 224, normalización ImageNet',
'short': short, 'probe_steps': steps, 'probe_seeds': seeds,
'knn': 'coseno de activaciones sin estandarizar, k=5 fijo, voto uniforme',
'probe': 'AdamW; activaciones estandarizadas con estadísticas de train; selección por pérdida de validación',
'freeze_sweep': '0 a 4 grupos congelados: (tallo+layer1), layer2, layer3, layer4; 4 congela todo el extractor. SGD, LR cabeza 0,01 y extractor 0,0001; estadísticas BN fijas; misma semilla, lotes y flip entre condiciones; selección por pérdida de validación.',
'freeze_sweep_steps': 20 if short else 800,
'split_seeds': {'train': 16140, 'validation': 16141, 'test': 16142},
'gpu': torch.cuda.get_device_name(0) if device.type == 'cuda' else 'CPU',
'torch': str(torch.__version__), 'cuda': torch.version.cuda,
'test': 'Exploratorio: se muestran varias etapas y semillas; no seleccionar arquitectura ni hiperparámetros con test.',
'warning': 'Tareas con distinto número de clases; no interpretarlas como una distancia OOD. El cotejo SHA-256 no detecta imágenes recodificadas. Los splits de EuroSAT pueden compartir contexto geográfico y no prueban independencia de ImageNet.',
}, 'datasets': {}}
path = Path(os.environ.get('ORYON_PROBES_OUTPUT', 'layer_probes.json'))
for name, spec in specs.items():
datasets = {s: read_split(spec, s) for s in ('train', 'validation', 'test')}
datasets, dedup = deduplicate_splits(datasets, spec['classes'])
print('Deduplicación SHA-256 de', name, ':', dedup, flush=True)
labels = {s: data['labels'] for s, data in datasets.items()}
extracted = {s: extract(model, data) for s, data in datasets.items()}
result = {'repo': spec['repo'], 'revision': spec['revision'], 'classes': spec['classes'],
'counts': {s: len(data['labels']) for s, data in datasets.items()},
'source_indices': {s: data['source_indices'] for s, data in datasets.items()},
'source_labels': {s: data['labels'].tolist() for s, data in datasets.items()},
'deduplication': dedup, 'stages': []}
output['datasets'][name] = result
for stage in ('stem', 'layer1', 'layer2', 'layer3', 'layer4'):
a, b, c = (extracted[s][stage] for s in ('train', 'validation', 'test'))
record = {'stage': stage, 'channels': a.shape[1],
'knn_validation': knn(a, b, labels['train'], labels['validation'], spec['classes']),
'knn_test': knn(a, c, labels['train'], labels['test'], spec['classes']),
'probes': [fit_probe(a, b, c, labels, spec['classes'], seed) for seed in seeds]}
result['stages'].append(record)
path.write_text(json.dumps(output, ensure_ascii=False, indent=2, allow_nan=False), encoding='utf-8')
print(name, stage, 'kNN valid/test', record['knn_validation']['accuracy'], record['knn_test']['accuracy'],
'sondas', [{'test': p.get('test_after_selection'), 'fallo': p['failure'],
'fallo_test': p.get('test_failure')} for p in record['probes']], flush=True)
result['freeze_sweep'] = []
for frozen in range(5):
for seed in seeds:
run = freeze_sweep(datasets, spec['classes'], frozen, seed)
result['freeze_sweep'].append(run)
path.write_text(json.dumps(output, ensure_ascii=False, indent=2, allow_nan=False), encoding='utf-8')
print(name, 'grupos congelados', frozen, 'semilla', seed,
'validación seleccionada', run['selected_validation'],
'test exploratorio', run.get('test_after_selection'),
'fallo', run['failure'], flush=True)
del datasets, extracted
gc.collect()
if device.type == 'cuda':
torch.cuda.empty_cache()
path.write_text(json.dumps(output, ensure_ascii=False, indent=2, allow_nan=False), encoding='utf-8')
print('Resultados:', path)
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
def layerwise_lr_groups(model, base_lr, decay):
passTorchVision documentation publishes parameter count for its original ResNet-50. Check the head replacement:
original = 25557032
old_head = 1000 * (2048 + 1)
new_head = 37 * (2048 + 1)
print('Sonda:', new_head)
print('Modelo completo con cabeza nueva:', original - old_head + new_head)