|
| 1 | +"""Map the full module tree of any PyTorch model to a machine-readable JSON. |
| 2 | +
|
| 3 | +Every nn.Module in the tree is a valid hook point. This module: |
| 4 | +1. Walks the full named_modules() graph |
| 5 | +2. Probes each module with a dummy forward to get output shapes |
| 6 | +3. Dumps a JSON file describing every extractable point |
| 7 | +
|
| 8 | +Usage: |
| 9 | + from pu.arch_map import map_architecture |
| 10 | + arch = map_architecture(model, dummy_input) |
| 11 | + # arch is a list of dicts, each with: |
| 12 | + # name, class, output_shape, num_params, depth, is_leaf |
| 13 | +""" |
| 14 | + |
| 15 | +import json |
| 16 | +from pathlib import Path |
| 17 | + |
| 18 | +import torch |
| 19 | +import torch.nn as nn |
| 20 | + |
| 21 | + |
| 22 | +def map_architecture(model, dummy_input, device="cuda"): |
| 23 | + """Walk the full module tree and probe output shapes. |
| 24 | +
|
| 25 | + Args: |
| 26 | + model: Any nn.Module (already on device, in eval mode). |
| 27 | + dummy_input: A tensor that can be passed to model(dummy_input). |
| 28 | + For CLIP, pass pixel_values; for VLMs, pass a dict. |
| 29 | + device: Device string. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + List of dicts, one per named module (excluding root). |
| 33 | + """ |
| 34 | + shapes = {} |
| 35 | + hooks = [] |
| 36 | + |
| 37 | + def _make_hook(name): |
| 38 | + def hook(module, input, output): |
| 39 | + if isinstance(output, tuple): |
| 40 | + t = output[0] |
| 41 | + elif isinstance(output, dict): |
| 42 | + # Some modules return dicts (e.g., BaseModelOutput) |
| 43 | + t = next(iter(output.values())) if output else None |
| 44 | + else: |
| 45 | + t = output |
| 46 | + if isinstance(t, torch.Tensor): |
| 47 | + shapes[name] = list(t.shape) |
| 48 | + else: |
| 49 | + shapes[name] = None |
| 50 | + return hook |
| 51 | + |
| 52 | + # Register hooks on every module |
| 53 | + for name, mod in model.named_modules(): |
| 54 | + if name: |
| 55 | + h = mod.register_forward_hook(_make_hook(name)) |
| 56 | + hooks.append(h) |
| 57 | + |
| 58 | + # Forward pass to capture all shapes |
| 59 | + with torch.no_grad(): |
| 60 | + try: |
| 61 | + if isinstance(dummy_input, dict): |
| 62 | + model(**dummy_input) |
| 63 | + else: |
| 64 | + model(dummy_input) |
| 65 | + except Exception as e: |
| 66 | + print(f"Warning: forward pass raised {e.__class__.__name__}: {e}") |
| 67 | + |
| 68 | + # Remove all hooks |
| 69 | + for h in hooks: |
| 70 | + h.remove() |
| 71 | + |
| 72 | + # Build architecture map |
| 73 | + arch = [] |
| 74 | + for name, mod in model.named_modules(): |
| 75 | + if not name: |
| 76 | + continue |
| 77 | + # Count depth by dots |
| 78 | + depth = name.count(".") + 1 |
| 79 | + # Is leaf = has no children |
| 80 | + is_leaf = len(list(mod.children())) == 0 |
| 81 | + # Parameter count (non-recursive to avoid double counting) |
| 82 | + num_params = sum(p.numel() for p in mod.parameters(recurse=False)) |
| 83 | + |
| 84 | + entry = { |
| 85 | + "name": name, |
| 86 | + "class": mod.__class__.__name__, |
| 87 | + "output_shape": shapes.get(name), |
| 88 | + "num_params": num_params, |
| 89 | + "depth": depth, |
| 90 | + "is_leaf": is_leaf, |
| 91 | + } |
| 92 | + arch.append(entry) |
| 93 | + |
| 94 | + return arch |
| 95 | + |
| 96 | + |
| 97 | +def map_all_models(output_dir="data/architectures", batch_size=2, image_size=224): |
| 98 | + """Map architectures for all registered models and save as JSON files. |
| 99 | +
|
| 100 | + Loads each model, runs a dummy forward, and saves the full module tree. |
| 101 | + """ |
| 102 | + from pu.models import get_adapter |
| 103 | + from pu.experiments_layerwise import MODEL_MAP |
| 104 | + |
| 105 | + output_dir = Path(output_dir) |
| 106 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 107 | + |
| 108 | + dummy_img = torch.randn(batch_size, 3, image_size, image_size) |
| 109 | + |
| 110 | + for alias, (sizes, model_names) in MODEL_MAP.items(): |
| 111 | + # Just map the first (smallest) size |
| 112 | + size, model_name = sizes[0], model_names[0] |
| 113 | + out_path = output_dir / f"{alias}_{size}.json" |
| 114 | + |
| 115 | + if out_path.exists(): |
| 116 | + print(f"[skip] {out_path} already exists") |
| 117 | + continue |
| 118 | + |
| 119 | + print(f"\n[{alias} {size}] Loading {model_name}...") |
| 120 | + try: |
| 121 | + adapter_cls = get_adapter(alias) |
| 122 | + adapter = adapter_cls(model_name, size, alias=alias) |
| 123 | + adapter.load() |
| 124 | + except Exception as e: |
| 125 | + print(f" [error] Could not load: {e}") |
| 126 | + continue |
| 127 | + |
| 128 | + model = adapter.model |
| 129 | + device = next(model.parameters()).device |
| 130 | + |
| 131 | + # Determine the right input for this model type |
| 132 | + if alias in ("clip",): |
| 133 | + dummy = dummy_img.to(device) |
| 134 | + # CLIP needs pixel_values kwarg for full model, but we map vision_model |
| 135 | + model_to_map = model.vision_model |
| 136 | + dummy_for_map = dummy |
| 137 | + else: |
| 138 | + model_to_map = model |
| 139 | + dummy_for_map = dummy_img.to(device) |
| 140 | + |
| 141 | + print(f" Mapping {sum(1 for _ in model_to_map.named_modules()) - 1} modules...") |
| 142 | + arch = map_architecture(model_to_map, dummy_for_map, device=str(device)) |
| 143 | + |
| 144 | + with open(out_path, "w") as f: |
| 145 | + json.dump({ |
| 146 | + "model_alias": alias, |
| 147 | + "model_size": size, |
| 148 | + "model_name": model_name, |
| 149 | + "num_modules": len(arch), |
| 150 | + "num_leaf_modules": sum(1 for a in arch if a["is_leaf"]), |
| 151 | + "total_params": sum(a["num_params"] for a in arch), |
| 152 | + "modules": arch, |
| 153 | + }, f, indent=2) |
| 154 | + |
| 155 | + print(f" Saved to {out_path} ({len(arch)} modules)") |
| 156 | + |
| 157 | + # Cleanup |
| 158 | + del adapter, model, model_to_map |
| 159 | + import gc |
| 160 | + gc.collect() |
| 161 | + if torch.cuda.is_available(): |
| 162 | + torch.cuda.empty_cache() |
| 163 | + |
| 164 | + |
| 165 | +if __name__ == "__main__": |
| 166 | + map_all_models() |
0 commit comments