File size: 7,346 Bytes
dfeab58 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | import json
import os
from dataclasses import asdict
from datetime import datetime
from typing import Dict, Optional, Tuple
import torch
import yaml
from safetensors.torch import load_file, save_file
from model import DigitGPT, GPTConfig, count_params
from tokenizer import TOKENIZER_NAME, DigitTokenizer
MODEL_DIR = "./model"
WEIGHTS_NAME = "model.safetensors"
CONFIG_NAME = "config.json"
TRAIN_CONFIG_NAME = "training_config.yaml"
METRICS_NAME = "metrics.json"
README_NAME = "README.md"
RUNS_DIR = "runs"
FORMAT_VERSION = 1
BUNDLE_FILES = {
"weights": WEIGHTS_NAME,
"manifest": CONFIG_NAME,
"tokenizer": TOKENIZER_NAME,
"training_config": TRAIN_CONFIG_NAME,
}
def build_model_config(cfg: Dict) -> GPTConfig:
data, model = cfg["data"], cfg["model"]
return GPTConfig(
vocab_size=int(model["vocab_size"]),
pad_id=int(model["pad_id"]),
eos_id=int(model["eos_id"]),
d_model=int(model["d_model"]),
n_layers=int(model["n_layers"]),
n_heads=int(model["n_heads"]),
d_ff=int(model["d_ff"]),
dropout=float(model["dropout"]),
bias=bool(model["bias"]),
max_seq_len=int(model["max_seq_len"]),
patch_size=int(model["patch_size"]),
img_h=int(data["img_h"]),
img_w=int(data["img_w_per_digit"]) * int(data["max_digits"]),
)
def build_model(cfg: Dict) -> DigitGPT:
mcfg = build_model_config(cfg)
return DigitGPT(mcfg, img_h=mcfg.img_h, img_w=mcfg.img_w)
def resolve_model_dir(path: Optional[str] = None) -> str:
return os.path.abspath(path or MODEL_DIR)
def missing_bundle_files(model_dir: str) -> list:
return [name for name in BUNDLE_FILES.values() if not os.path.isfile(os.path.join(model_dir, name))]
def save_bundle(
model: torch.nn.Module,
tokenizer: DigitTokenizer,
cfg: Dict,
model_dir: str = MODEL_DIR,
metrics: Optional[Dict] = None,
stage: str = "final",
snapshot: bool = True,
) -> str:
model_dir = resolve_model_dir(model_dir)
os.makedirs(model_dir, exist_ok=True)
os.makedirs(os.path.join(model_dir, RUNS_DIR), exist_ok=True)
state_dict = {k: v.detach().cpu().contiguous().clone() for k, v in model.state_dict().items()}
save_file(state_dict, os.path.join(model_dir, WEIGHTS_NAME))
tokenizer.save(os.path.join(model_dir, TOKENIZER_NAME))
mcfg: GPTConfig = model.config
manifest = {
"format_version": FORMAT_VERSION,
"created_at": datetime.now().isoformat(timespec="seconds"),
"stage": stage,
"arch": type(model).__name__,
"params": count_params(model),
"model": asdict(mcfg),
"data": {
"img_h": int(cfg["data"]["img_h"]),
"img_w": mcfg.img_w,
"img_w_per_digit": int(cfg["data"]["img_w_per_digit"]),
"patch_size": mcfg.patch_size,
"n_patches": (mcfg.img_h // mcfg.patch_size) * (mcfg.img_w // mcfg.patch_size),
"min_digits": int(cfg["data"]["min_digits"]),
"max_digits": int(cfg["data"]["max_digits"]),
"grayscale_range": [0.0, 1.0],
},
"generation": dict(cfg.get("generation", {})),
"tokenizer": {"pad_id": tokenizer.pad_id, "eos_id": tokenizer.eos_id, "vocab_size": tokenizer.vocab_size},
}
with open(os.path.join(model_dir, CONFIG_NAME), "w", encoding="utf-8") as f:
json.dump(manifest, f, ensure_ascii=False, indent=2)
with open(os.path.join(model_dir, TRAIN_CONFIG_NAME), "w", encoding="utf-8") as f:
yaml.safe_dump(cfg, f, allow_unicode=True, sort_keys=False)
if metrics is not None:
with open(os.path.join(model_dir, METRICS_NAME), "w", encoding="utf-8") as f:
json.dump(metrics, f, ensure_ascii=False, indent=2)
with open(os.path.join(model_dir, README_NAME), "w", encoding="utf-8") as f:
f.write(bundle_readme(manifest, tokenizer, cfg))
if snapshot:
save_file(state_dict, os.path.join(model_dir, RUNS_DIR, f"{stage}_{manifest['created_at'].replace(':', '')}.safetensors"))
return model_dir
def load_manifest(model_dir: str) -> Dict:
path = os.path.join(model_dir, CONFIG_NAME)
if not os.path.isfile(path):
raise FileNotFoundError(f"manifest not found: {path}")
with open(path, "r", encoding="utf-8") as f:
manifest = json.load(f)
version = int(manifest.get("format_version", 0))
if version != FORMAT_VERSION:
raise ValueError(f"unsupported bundle format_version={version}, expected {FORMAT_VERSION}")
return manifest
def load_bundle(
model_dir: str = MODEL_DIR,
device: str = "cpu",
dtype: Optional[torch.dtype] = None,
) -> Tuple[DigitGPT, DigitTokenizer, Dict]:
model_dir = resolve_model_dir(model_dir)
missing = missing_bundle_files(model_dir)
if missing:
raise FileNotFoundError(
f"incomplete bundle in {model_dir}: missing {', '.join(missing)} (run train.py or train_more.py first)"
)
manifest = load_manifest(model_dir)
tokenizer = DigitTokenizer.load(os.path.join(model_dir, TOKENIZER_NAME))
mcfg_dict = dict(manifest["model"])
mcfg = GPTConfig(**{k: v for k, v in mcfg_dict.items() if k in GPTConfig.__dataclass_fields__})
data = manifest["data"]
model = DigitGPT(mcfg, img_h=mcfg.img_h, img_w=mcfg.img_w)
state_dict = load_file(os.path.join(model_dir, WEIGHTS_NAME))
try:
model.load_state_dict(state_dict, strict=True)
except RuntimeError as e:
raise RuntimeError(
f"weights in {model_dir} do not match config.json (arch or vocab changed). "
f"Retrain, or restore the matching config.yaml. Original error: {e}"
) from e
if dtype is not None:
model = model.to(dtype)
return model.to(torch.device(device)).eval(), tokenizer, manifest
def bundle_readme(manifest: Dict, tokenizer: DigitTokenizer, cfg: Dict) -> str:
d = manifest["data"]
g = manifest["generation"]
m = manifest["model"]
return f"""# {cfg.get('project_name', 'mnist-multidigit-gpt')} - model bundle
Self-contained runnable bundle. `infer.py` only needs this directory.
- `created_at`: {manifest['created_at']}
- `stage`: {manifest['stage']}
- `params`: {manifest['params']:,} ({manifest['params'] / 1e6:.2f}M)
- `arch`: {m['n_layers']}L / d{m['d_model']} / {m['n_heads']}H / dff{m['d_ff']}
- `image`: {d['img_h']}x{d['img_w']} grayscale in [{d['grayscale_range'][0]}, {d['grayscale_range'][1]}], patch {d['patch_size']} ({d['n_patches']} patches)
- `digits`: {d['min_digits']}-{d['max_digits']}, vocab {tokenizer.vocab_size} (`0`-`9`, `{tokenizer.pad_token}`={tokenizer.pad_id}, `{tokenizer.eos_token}`={tokenizer.eos_id})
- `generation`: greedy={g.get('greedy')}, temperature={g.get('temperature')}, max_len={g.get('max_len')}
## Files
- `{WEIGHTS_NAME}` - weights (safetensors)
- `{CONFIG_NAME}` - architecture + data spec (single source of truth for loading)
- `{TOKENIZER_NAME}` - vocab and special token ids
- `{TRAIN_CONFIG_NAME}` - full training config this bundle came from
- `{METRICS_NAME}` - last metrics, when present
- `{RUNS_DIR}/` - per-stage weight snapshots
## Run
```bash
python infer.py <image.png>
```
`infer.py` loads this directory by default, resizes/pads the image to
{d['img_h']}x{d['img_w']} itself, so any aspect/size works.
""" |