TSRDA / MTLCC /code /run_pipeline.py
Dhruv1000's picture
MTLCC: add Run-All notebook, 5 figures, requirements, notebook README; parametrise data path; report updates
578bb2b verified
Raw History Blame Contribute Delete
18.7 kB
"""MTLCC pipeline runner - Option 1 (core encoder) and Option 2 (full T-SRDA recipe).
Option 1: prep -> audit -> pretrain -> initial -> eval_initial
Option 2: ... -> refinement -> sam -> structured_pre -> structured_ft -> old_cnn -> new_cnn
-> cache_train -> fit_readouts -> val -> test
Same stage order, arguments and fixed ensemble recipe as the PASTIS supervisor pipeline;
only dataset-dependent values differ (see config.py). Completed stages are skipped
(marker files in <runs>/stage_done), so the script is safely re-runnable/resumable.
Usage: python run_pipeline.py <stage> [--smoke] | python run_pipeline.py option1|option2
"""
import argparse, gc, json, os, subprocess, sys, time
from pathlib import Path
import numpy as np
import torch
from torch.utils.data import DataLoader
import config as C
import foundation_transfer as F
import spatial_context_transfer as S
from dataset import (MTLCCTileDataset, crop_ij, pad_collate, pretrain_patch_ids,
train_patch_ids, val_patch_ids, test_patch_ids)
CODE = Path(__file__).resolve().parent
ROOT = CODE.parent
RUN = C.EXP_ROOT
OUT = RUN / 'outputs'
EXTERNAL = ROOT / 'external/tessera/ckpt/student_small.pt'
TESSERA_SHA = F.ENCODER_SHA
INPUT_PRE = RUN / 'checkpoints/pretrain/latest.utae.tar'
STAGE_DIRS = {k: RUN / k for k in ['initial', 'refinement', 'sam', 'structured_pre', 'structured_ft']}
CACHE = RUN / 'training_features'
FITTED = RUN / 'fitted_readouts'
DONE = RUN / 'stage_done'
NC = C.N_CLASSES
SIDE = C.PATCH_SIZE
OPTION1 = ['prep', 'audit', 'pretrain', 'initial', 'eval_initial']
OPTION2 = OPTION1 + ['refinement', 'sam', 'structured_pre', 'structured_ft', 'old_cnn', 'new_cnn',
'cache_train', 'fit_readouts', 'val', 'test']
def write(path, value):
path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + '.tmp'); tmp.write_text(json.dumps(value, indent=2) + '\n'); tmp.replace(path)
def component_paths():
return {'sam': STAGE_DIRS['sam'] / 'model_best_raw.tar',
'clusters': FITTED / 'class_cluster_centres.tar',
'old_cnn': RUN / 'original_temporal_cnn/32X32_full_seed3407/best.tar',
'new_cnn': RUN / '32X32_cnn_control_seed3407/best.tar',
'structured': STAGE_DIRS['structured_ft'] / 'model_best_raw.tar',
'original_gaussian': FITTED / 'original_gaussian.npz',
'tessera': EXTERNAL, 'optical_gaussian': FITTED / 'optical_gaussian.npz',
'spatial_context': FITTED}
def command(script, args):
print('Launching:', script.name, *map(str, args), flush=True)
env = os.environ.copy(); env['EXP_ROOT'] = str(RUN)
subprocess.run([sys.executable, '-u', str(script), *map(str, args)], cwd=str(script.parent), env=env, check=True)
def stage(name, operation, outputs, smoke=False):
marker = DONE / f'{name}{".smoke" if smoke else ""}.json'
if marker.exists() and all(Path(p).exists() for p in outputs):
print(f'[{name}] already complete - skipping', flush=True); return json.loads(marker.read_text())
t = time.monotonic(); operation()
for p in outputs:
if not Path(p).is_file(): raise FileNotFoundError(f'{name} did not produce {p}')
rec = {'stage': name, 'seconds': time.monotonic() - t, 'smoke': smoke}; write(marker, rec); return rec
def audit(smoke=False):
import dataset as D
roles = {'pretrain': pretrain_patch_ids(), 'train': train_patch_ids(), 'val': val_patch_ids(), 'test': test_patch_ids()}
hist = {}
for role in ['train', 'val', 'test']:
h = np.zeros(NC, np.int64)
for tid in sorted(set(roles[role])):
h += np.bincount(MTLCCTileDataset([tid], train=False)[0][1].numpy().ravel(), minlength=NC)
hist[role] = h.tolist()
res = {'roles': {k: {'entries': len(v), 'unique': len(set(v))} for k, v in roles.items()},
'class_pixel_counts': hist, 'classes': C.CLASS_NAMES, 'n_classes': NC,
'classes_missing_in_finetune_train': [i for i in range(1, NC) if hist['train'][i] == 0],
'overlap_pretrain_train': len(set(roles['pretrain']) & set(roles['train'])),
'overlap_train_val': len(set(roles['train']) & set(roles['val'])),
'overlap_train_test': len(set(roles['train']) & set(roles['test'])),
'overlap_val_test': len(set(roles['val']) & set(roles['test'])), 'seed': C.SEED}
write(OUT / 'dataset_audit.json', res); print(json.dumps(res, indent=1)); return res
def train_action(action, smoke=False):
ep = lambda full: 1 if smoke else full
limited = ['--limit_batches', 1] if smoke else []
if action == 'pretrain':
return stage(action, lambda: command(CODE / 'pretrain.py', ['--seed', 3407, '--resume', 'auto', '--epochs', ep(C.PRE_EPOCHS)] + limited), [INPUT_PRE], smoke)
common = ['--pretrain_pth', INPUT_PRE, '--seed', 3407, '--batch', 2, '--crop_size', C.PATCH_SIZE, '--fixed_crops',
'--mask_ce_invalid', '--wd', .02, '--label_smoothing', .05, '--ema_decay', .999, '--resume', 'auto']
if action == 'initial':
args = common + ['--out_dir', STAGE_DIRS[action], '--tag', 'mtlcc_initial_seed3407', '--epochs', ep(100), '--base_lr', 1e-4,
'--encoder_lr_mult', .5, '--warmup_epochs', 3, '--patience', 30] + limited
return stage(action, lambda: command(CODE / 'train_initial.py', args), [STAGE_DIRS[action] / 'model_best_raw.tar'], smoke)
if action in ['refinement', 'sam']:
source = STAGE_DIRS['initial' if action == 'refinement' else 'refinement'] / 'model_best_raw.tar'
script = 'train_refinement.py' if action == 'refinement' else 'train_sam.py'
args = common + ['--init_finetuned', source, '--out_dir', STAGE_DIRS[action], '--tag', f'mtlcc_{action}_seed3407',
'--epochs', ep(20), '--base_lr', 1e-5, '--encoder_lr_mult', .2 if action == 'refinement' else .5,
'--warmup_epochs', 0, '--patience', 0] + limited
if action == 'sam': args += ['--research', 'sam']
return stage(action, lambda: command(CODE / script, args), [STAGE_DIRS[action] / 'model_best_raw.tar'], smoke)
if action == 'structured_pre':
args = ['--pretrain_pth', INPUT_PRE, '--epochs', ep(3), '--policy', 'structured', '--out_dir', STAGE_DIRS[action]] + limited
return stage(action, lambda: command(CODE / 'train_structured_pretraining.py', args), [STAGE_DIRS[action] / 'encoder_32X32.tar'], smoke)
if action == 'structured_ft':
source = STAGE_DIRS['structured_pre'] / 'encoder_32X32.tar'
args = common.copy(); args[1] = source
args += ['--research', 'plain', '--distill_weight', 0, '--out_dir', STAGE_DIRS[action], '--tag', 'mtlcc_structured_seed3407',
'--epochs', ep(100), '--base_lr', 1e-4, '--encoder_lr_mult', .5, '--warmup_epochs', 3, '--patience', 0] + limited
return stage(action, lambda: command(CODE / 'train_plain.py', args), [STAGE_DIRS[action] / 'model_best_raw.tar'], smoke)
if action in ['old_cnn', 'new_cnn']:
script = 'train_original_cnn.py' if action == 'old_cnn' else 'train_temporal_cnn.py'
args = ['--seed', 3407, '--epochs', ep(100)]
if action == 'new_cnn': args += ['--kind', 'cnn_control']
return stage(action, lambda: command(CODE / script, args), [component_paths()[action]], smoke)
raise ValueError(action)
def eval_initial(smoke=False):
"""Option-1 evaluation of the fine-tuned core network (STCLN protocol + strict) on val and test."""
res = {}
for split in ['val', 'test']:
for which in ['raw', 'ema']:
ck = STAGE_DIRS['initial'] / f'model_best_{which}.tar'
if not ck.is_file(): continue
out = OUT / f'option1_{split}_{which}.json'
command(CODE / 'eval_mtlcc.py', ['--ckpt', ck, '--split', split, '--out', out])
res[f'{split}_{which}'] = json.loads(out.read_text())
write(OUT / 'option1_results.json', {k: {'stcln': v['stcln'] | {'per_class': None}, 'strict': v['strict']} for k, v in res.items()})
return res
def _selected_prediction_checkpoint():
return STAGE_DIRS['initial'] / 'model_best_raw.tar'
@torch.inference_mode()
def cache_training(smoke=False):
"""Training-only feature extraction (SAM encoder + frozen TESSERA), duplicates/order preserved."""
import tessera_student as student
from notebook_ensemble import spatial_network
from training_feature_clusters import DepthCollector
CACHE.mkdir(parents=True, exist_ok=True)
ids = train_patch_ids(); per = SIDE * SIDE; count = len(ids) * per
dl = DataLoader(MTLCCTileDataset(ids, train=False), batch_size=2, shuffle=False, num_workers=4, collate_fn=pad_collate)
sam = spatial_network(component_paths()['sam']).cuda(); collector = DepthCollector(sam.utae)
fw = np.lib.format.open_memmap(CACHE / 'original.npy', mode='w+', dtype=np.float16, shape=(count, 3, 512))
labels = np.empty(count, np.uint8); patches = np.empty(count, np.int64); crops = np.zeros(count, np.uint8)
offset = 0
try:
for bi, ((x, pos, days), y) in enumerate(dl):
x, pos = x.cuda(), pos.cuda(); collector.begin(x, pos)
with torch.autocast('cuda', dtype=torch.float16): sam.utae(x, pos)
f = collector.end(); n = len(f)
fw[offset:offset + n] = f; labels[offset:offset + n] = y.numpy().ravel()
patches[offset:offset + n] = np.repeat([int(t) for t in ids[2 * bi:2 * bi + len(x)]], per); offset += n
if bi % 10 == 0: print('SAM training feature batches', bi + 1, '/', len(dl), flush=True)
finally:
collector.close(); sam.cpu(); del sam; gc.collect(); torch.cuda.empty_cache()
assert offset == count
fw.flush(); del fw
np.save(CACHE / 'labels.npy', labels); np.save(CACHE / 'patch_ids.npy', patches); np.save(CACHE / 'crop_ids.npy', crops)
net = student.load_model(str(EXTERNAL), torch.device('cuda')).eval().requires_grad_(False)
fw = np.lib.format.open_memmap(CACHE / 'optical.npy', mode='w+', dtype=np.float16, shape=(count, 1, 256)); offset = 0
for bi, ((x, pos, days), y) in enumerate(dl):
for s in range(len(x)):
f = F.optical_features(net, F.prepare(x[s:s + 1].cuda(), pos[s:s + 1].cuda(), days[s:s + 1]))
n = len(f); fw[offset:offset + n] = f
assert np.array_equal(labels[offset:offset + n], y[s].numpy().ravel()); offset += n
if bi % 10 == 0: print('Frozen TESSERA training batches', bi + 1, '/', len(dl), flush=True)
assert offset == count
fw.flush(); net.cpu(); del net; gc.collect(); torch.cuda.empty_cache()
write(CACHE / 'manifest.json', {'entries': count, 'training_only': True, 'valid_entries': int((labels > 0).sum()),
'tessera_frozen': True, 'feature_cache_dtype': 'float16'})
def gaussian_fit(features, labels, output, temperature, spatial_context=False):
"""Uniform-prior shared-covariance Gaussian (shrinkage 0.1). Classes absent from the
fine-tuning training tiles get a -1e9 bias (probability 0): they cannot be learned."""
valid = labels > 0
y = labels[valid].astype(np.int64) - 1
x = np.asarray(features, np.float32)[valid]
mean = x.mean(0); std = x.std(0).clip(.01); z = (x - mean) / std
K = C.N_SCORED; present = np.array([np.any(y == c) for c in range(K)])
centers = np.zeros((K, z.shape[1]), np.float32)
for c in np.flatnonzero(present): centers[c] = z[y == c].mean(0)
residual = z - centers[y]; cov = residual.T @ residual / len(z)
if spatial_context:
cov = .9 * cov + .1 * np.trace(cov) / len(cov) * np.eye(len(cov))
values, vectors = np.linalg.eigh(cov); inverse = (vectors / values.clip(1e-6)) @ vectors.T
weight = (inverse @ centers.T).astype(np.float32); bias = (-.5 * np.sum(centers * (centers @ inverse), 1)).astype(np.float32)
else:
values, vectors = np.linalg.eigh(cov.astype(np.float64))
inverse = (vectors / (.9 * values + .1 * values.mean()).clip(1e-6)) @ vectors.T
weight = (inverse @ centers.T).astype(np.float32); bias = -.5 * (centers * weight.T).sum(1)
bias = np.where(present, bias, -1e9).astype(np.float32)
np.savez_compressed(output, mean=mean, std=std, weight=weight, bias=bias, temperature=temperature, type='linear', depth=0)
def fit_readouts():
from sklearn.cluster import KMeans
from torch.nn.functional import normalize
FITTED.mkdir(parents=True, exist_ok=True)
y = np.load(CACHE / 'labels.npy'); original = np.load(CACHE / 'original.npy', mmap_mode='r'); optical = np.load(CACHE / 'optical.npy', mmap_mode='r')
valid = y > 0
x = np.asarray(original[:, 0], np.float32)
sums = np.zeros(512, np.float64); squares = sums.copy(); indices = np.flatnonzero(valid)
for batch in np.array_split(indices, max(1, (len(indices) + 4095) // 4096)):
rows = x[batch].astype(np.float64); sums += rows.sum(0); squares += (rows * rows).sum(0)
mean = (sums / len(indices)).astype(np.float32)
std = np.sqrt(np.maximum(squares / len(indices) - (sums / len(indices)) ** 2, 0)).clip(.05).astype(np.float32)
pid = np.load(CACHE / 'patch_ids.npy'); cid = np.load(CACHE / 'crop_ids.npy'); per = SIDE * SIDE
unique = np.zeros(len(y), bool); seen = set()
for start in range(0, len(y), per):
key = (int(pid[start]), int(cid[start]))
if key not in seen: unique[start:start + per] = True; seen.add(key)
rng = np.random.default_rng(3407); reps = []
mt, st = torch.from_numpy(mean).cuda(), torch.from_numpy(std).cuda()
for cls in range(1, NC):
memory = []
for patch in np.unique(pid[unique & (y == cls)]):
ix = np.flatnonzero(unique & (pid == patch) & (y == cls))
memory.extend(rng.choice(ix, 32, replace=len(ix) < 32).tolist())
if not memory: # class absent from training tiles
reps.append(torch.zeros(3, 512)); continue
z = normalize((torch.from_numpy(x[np.array(memory)]).cuda() - mt) / st, dim=1)
centers = KMeans(n_clusters=3, n_init=3, random_state=3407).fit(z.cpu().numpy()).cluster_centers_
reps.append(normalize(torch.from_numpy(centers).cuda(), dim=1).cpu())
torch.save({'source': 'sam', 'depth': 0, 'kind': 'prototype', 'seed': 3407, 'mean': torch.from_numpy(mean), 'std': torch.from_numpy(std),
'state': torch.stack(reps), 'alpha': .5}, FITTED / 'class_cluster_centres.tar')
gaussian_fit(x, y, FITTED / 'original_gaussian.npz', 16.); del x, original
f = np.asarray(optical[:, 0], np.float32)
gaussian_fit(f, y, FITTED / 'optical_gaussian.npz', 4.)
gaussian_fit(S.descriptor(f, SIDE), y, FITTED / 'spatial5.npz', 4., spatial_context=True)
gaussian_fit(S.descriptor(f, SIDE, moments=True), y, FITTED / 'moments5.npz', 8., spatial_context=True)
tr = f[valid]
np.savez_compressed(FITTED / 'affinity_diffusion3.npz', affinity_mean=tr.mean(0), affinity_std=tr.std(0).clip(.01), radius=1, affinity_temperature=.25)
write(OUT / 'component_paths.json', {k: str(v) for k, v in component_paths().items()})
@torch.inference_mode()
def evaluate(split, smoke=False):
from notebook_ensemble import CompleteEnsemble
paths = component_paths(); context_dir = paths.pop('spatial_context')
model = CompleteEnsemble(paths); context = S.SpatialContextTransfer(context_dir)
ids = val_patch_ids() if split == 'val' else test_patch_ids()
dl = DataLoader(MTLCCTileDataset(ids, train=False), batch_size=2 if split == 'val' else 1, shuffle=False, num_workers=4, pin_memory=True, collate_fn=pad_collate)
cms = {}; processed = 0; started = time.monotonic()
try:
for bi, ((x, pos, days), y) in enumerate(dl):
if smoke and bi >= 1: break
x, pos = x.cuda(), pos.cuda(); processed += len(x)
parts = model.predict(x, pos, days, split, return_features=True)
p = context.predict(parts['final'], parts['optical_features'], SIDE)
outputs = {'reference_four_component': parts['reference'], 'historical_58_recipe': parts['final'], 'frozen_optical_gaussian': parts['optical'],
'spatial_mean_parent_recipe': p['spatial_baseline'], 'diffusion_recipe': p['validation_selected'],
'moments_ensemble_recipe': p['best_observed'], 'two_branch_ensemble_recipe': p['top2_ensemble']}
for name, prediction in outputs.items():
cms.setdefault(name, np.zeros((NC, NC), np.int64)); cms[name] += F.confusion(y.numpy().ravel(), prediction.argmax(-1).ravel())
if bi % 20 == 0: print(split, bi, len(dl), 'seconds', time.monotonic() - started, flush=True)
finally:
model.close()
result = {'split': split, 'complete': not smoke and processed == len(ids), 'tiles': processed, 'expected_tiles': len(ids),
'seconds': time.monotonic() - started, 'components': {n: F.metrics(cm) for n, cm in cms.items()}}
write(OUT / f'fresh_{split}_results{"_smoke" if smoke else ""}.json', result); return result
def main():
ap = argparse.ArgumentParser(); ap.add_argument('action'); ap.add_argument('--smoke', action='store_true'); a = ap.parse_args()
torch.set_num_threads(4); torch.manual_seed(3407)
torch.backends.cuda.matmul.allow_tf32 = True; torch.backends.cudnn.allow_tf32 = True
OUT.mkdir(parents=True, exist_ok=True)
if a.action in ('option1', 'option2'):
for s in (OPTION1 if a.action == 'option1' else OPTION2):
print(f'\n===== {s} =====', flush=True); subprocess.run([sys.executable, '-u', __file__, s] + (['--smoke'] if a.smoke else []), check=True)
return
if a.action == 'prep':
command(CODE / 'prep_data.py', []); r = {'stage': 'prep', 'band_stats': str(C.EXP_ROOT / 'cache/band_stats.json')}
elif a.action == 'audit': r = audit(a.smoke)
elif a.action == 'eval_initial': r = eval_initial(a.smoke)
elif a.action == 'cache_train': r = stage(a.action, lambda: cache_training(a.smoke), [CACHE / 'optical.npy', CACHE / 'labels.npy', CACHE / 'manifest.json'], a.smoke)
elif a.action == 'fit_readouts': r = stage(a.action, fit_readouts, [FITTED / n for n in ['class_cluster_centres.tar', 'original_gaussian.npz', 'optical_gaussian.npz', 'spatial5.npz', 'moments5.npz', 'affinity_diffusion3.npz']], a.smoke)
elif a.action in ('val', 'test'): r = evaluate(a.action, a.smoke)
else: r = train_action(a.action, a.smoke)
print(json.dumps(r, indent=1, default=str)[:2000], flush=True)
if __name__ == '__main__':
main()