add Python source: model, tokenizer, checkpoint, data, train, train_more, infer + config
dfeab58 verified Download scripts/checkpoint.py from Fantominsight/Polina-Lumen-NumDetective: direct link, hf CLI and curl.
- Browser
- Download file 7.35 kB
-
https://huggingface.co/Fantominsight/Polina-Lumen-NumDetective/resolve/main/scripts/checkpoint.py
- Command line
-
hf download hf://Fantominsight/Polina-Lumen-NumDetective/scripts/checkpoint.py
-
curl -L -o checkpoint.py https://huggingface.co/Fantominsight/Polina-Lumen-NumDetective/resolve/main/scripts/checkpoint.py
7.35 kB
| 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. | |
| """ |