Download TransUNet_Setup/check_encoder_moved.py from AI-555/TransUnet_Phase1_Optuned: direct link, hf CLI and curl.
- Browser
- Download file 4.04 kB
-
https://huggingface.co/datasets/AI-555/TransUnet_Phase1_Optuned/resolve/main/TransUNet_Setup/check_encoder_moved.py
- Command line
-
hf download hf://datasets/AI-555/TransUnet_Phase1_Optuned/TransUNet_Setup/check_encoder_moved.py
-
curl -L -o check_encoder_moved.py https://huggingface.co/datasets/AI-555/TransUnet_Phase1_Optuned/resolve/main/TransUNet_Setup/check_encoder_moved.py
4.04 kB
| """RunPod diagnostic — did TransUNet's ViT encoder actually train, or stay at ImageNet init? | |
| Run on the pod (where the .npz, the TransUNet repo, and the trained best.pt all exist): | |
| python check_encoder_moved.py \ | |
| --repo /workspace/TransUNet \ | |
| --npz /workspace/model/vit_checkpoint/imagenet21k/R50+ViT-B_16.npz \ | |
| --ckpt /workspace/runs/TransUNet_Phase1/repeated_holdout/stratified_holdout_v1/phase_001/pct_100/repeat_01/strategy_2/final/checkpoints/best.pt \ | |
| --img 128 | |
| Prints, per encoder tensor and overall, the relative change ||trained - imagenet_init|| / ||imagenet_init||. | |
| If the mean change is a meaningful fraction (>~1%) and most tensors moved, the 105M encoder trained. | |
| If it's ~0 everywhere, the encoder was effectively frozen (that would explain parity with small models). | |
| """ | |
| import argparse, sys, os, copy, numpy as np, torch | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--repo", required=True) | |
| ap.add_argument("--npz", required=True) | |
| ap.add_argument("--ckpt", required=True) | |
| ap.add_argument("--img", type=int, default=128) | |
| a = ap.parse_args() | |
| sys.path.insert(0, a.repo) | |
| from networks.vit_seg_modeling import VisionTransformer, CONFIGS | |
| cfg = copy.deepcopy(CONFIGS["R50-ViT-B_16"]) | |
| cfg.n_classes = 1; cfg.n_skip = 3; cfg.classifier = "seg" | |
| cfg.patches.grid = (a.img // 16, a.img // 16) | |
| vit = VisionTransformer(cfg, img_size=a.img, num_classes=1) | |
| # (1) ImageNet init | |
| vit.load_from(weights=np.load(a.npz, allow_pickle=False)) | |
| init = {k: v.detach().float().clone() for k, v in vit.transformer.state_dict().items()} | |
| # (2) trained weights from best.pt -> map "smp_model.encoder.transformer.*" -> "transformer.*" | |
| ck = torch.load(a.ckpt, map_location="cpu", weights_only=False) | |
| sd = ck["model_state_dict"] if "model_state_dict" in ck else ck | |
| trained_transformer = {} | |
| for k, v in sd.items(): | |
| if k.startswith("smp_model.encoder.transformer."): | |
| trained_transformer[k.replace("smp_model.encoder.transformer.", "")] = v | |
| if not trained_transformer: | |
| print("!! No 'smp_model.encoder.transformer.*' keys in checkpoint. Keys sample:") | |
| print([k for k in list(sd)[:10]]); return | |
| missing, unexpected = vit.transformer.load_state_dict(trained_transformer, strict=False) | |
| print(f"loaded trained transformer tensors={len(trained_transformer)} (missing={len(missing)} unexpected={len(unexpected)})") | |
| trained = {k: v.detach().float().clone() for k, v in vit.transformer.state_dict().items()} | |
| # (3) compare | |
| rows = [] | |
| for k in init: | |
| if init[k].numel() == 0 or "num_batches_tracked" in k: | |
| continue | |
| num = (trained[k] - init[k]).norm().item() | |
| den = init[k].norm().item() + 1e-12 | |
| rows.append((k, num / den, init[k].numel())) | |
| rel = np.array([r[1] for r in rows]); npar = np.array([r[2] for r in rows]) | |
| wmean = float((rel * npar).sum() / npar.sum()) # param-weighted mean rel change | |
| print("\n=== ENCODER MOVEMENT (relative change from ImageNet init) ===") | |
| print(f"tensors compared : {len(rows)}") | |
| print(f"param-weighted mean : {wmean*100:.3f}%") | |
| print(f"median tensor change : {np.median(rel)*100:.3f}%") | |
| print(f"max tensor change : {rel.max()*100:.3f}%") | |
| print(f"tensors moved >1% : {int((rel>0.01).sum())}/{len(rows)}") | |
| print(f"tensors basically 0 : {int((rel<1e-4).sum())}/{len(rows)} (<0.01% change)") | |
| print("\nexamples:") | |
| for name in ["embeddings.position_embeddings", | |
| "embeddings.hybrid_model.root.conv.weight", | |
| "encoder.layer.0.attn.query.weight", | |
| "encoder.layer.11.ffn.fc1.weight"]: | |
| m = {r[0]: r[1] for r in rows}.get(name) | |
| if m is not None: print(f" {name:52s} {m*100:7.3f}%") | |
| print("\nVERDICT:", "ENCODER TRAINED (capacity used)" if wmean > 0.005 | |
| else "ENCODER BARELY MOVED (effectively frozen -> tuning target)") | |
| if __name__ == "__main__": | |
| main() | |