Download src/discerna/model/weights.py from CrazyH0rse/Discerna-v1-475M: direct link, hf CLI and curl.
- Browser
- Download file 5.21 kB
-
https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/model/weights.py
- Command line
-
hf download hf://CrazyH0rse/Discerna-v1-475M/src/discerna/model/weights.py
-
curl -L -o weights.py https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/model/weights.py
5.21 kB
| """Loading and saving Discerna models: a model folder holds `config.json` (architecture, tokenizer, | |
| calibration, limits, provenance), `model.safetensors` and the tokenizer files. | |
| `build(spec)` recreates the architecture, so a folder is just config + weights. Loading checks that | |
| the weights cover the model exactly: no missing tensors and no unexpected ones, so a model never | |
| runs with silently random weights. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| import torch | |
| from safetensors.torch import load as load_bytes | |
| from safetensors.torch import save_file | |
| from discerna.model.calibration import BucketTemperature | |
| from discerna.model.codec import MarkerCodec | |
| from discerna.model.decision_model import DecisionModel | |
| from discerna.model.head import MarkerHead | |
| from discerna.model.modalities.vision import Siglip2TiledVision | |
| from discerna.model.trunk import Lfm2BidirTrunk, TrunkConfig | |
| FORMAT = "discerna/1" | |
| SPEC_FILE, WEIGHTS_FILE = "config.json", "model.safetensors" | |
| def load_file(path) -> dict[str, torch.Tensor]: | |
| """A safetensors file's tensors, read in one sequential pass (fast on local disks and network mounts).""" | |
| with open(path, "rb") as f: | |
| return load_bytes(f.read()) | |
| def load_strict(module: torch.nn.Module, state: dict[str, torch.Tensor]) -> None: | |
| expected = set(module.state_dict()) | |
| missing, unexpected = sorted(expected - state.keys()), sorted(state.keys() - expected) | |
| if missing or unexpected: | |
| raise ValueError(f"the weights do not match the model: missing {missing[:5]} ({len(missing)}), " | |
| f"unexpected {unexpected[:5]} ({len(unexpected)})") | |
| for name, tensor in module.state_dict().items(): | |
| if tensor.shape != state[name].shape: | |
| raise ValueError(f"{name}: model {tuple(tensor.shape)} vs weights {tuple(state[name].shape)}") | |
| module.load_state_dict(state, strict=True) | |
| def tokenizer(path: str | Path): | |
| """The tokenizer stored in a model folder (a tokenizer.json; no remote code).""" | |
| from transformers import AutoTokenizer | |
| return AutoTokenizer.from_pretrained(str(path), trust_remote_code=False) | |
| def build(spec: dict, tok=None, root: str | Path | None = None) -> DecisionModel: | |
| """A freshly initialized model with the architecture `spec` describes (weights are not loaded). | |
| The tokenizer is `tok`, or the one the spec points to inside the model folder `root`.""" | |
| if spec.get("format") != FORMAT: | |
| raise ValueError(f"not a {FORMAT} model: format {spec.get('format')!r}") | |
| if spec.get("adapters"): | |
| raise ValueError("this model has unmerged adapters; Discerna releases ship merged weights") | |
| if tok is None: | |
| where = (spec.get("tokenizer") or {}).get("path") | |
| if where is None or root is None: | |
| raise ValueError("no tokenizer: pass one, or load the model from its folder") | |
| tok = tokenizer(Path(root) / where) | |
| trunk = Lfm2BidirTrunk(TrunkConfig.from_dict(spec["trunk"])) | |
| d = trunk.hidden_size | |
| head = spec["head"] | |
| if head.get("type", "marker") != "marker": | |
| raise ValueError(f"unknown head type {head['type']!r}") | |
| vision = None | |
| if spec.get("vision"): | |
| v = spec["vision"] | |
| if v.get("type", "siglip2_tiled") != "siglip2_tiled": | |
| raise ValueError(f"unknown vision type {v['type']!r}") | |
| vision = Siglip2TiledVision(v["vision_config"], v["projector_hidden"], d) | |
| cal = spec.get("calibrator") or {} | |
| limits = spec.get("limits") or {} | |
| return DecisionModel(trunk=trunk, head=MarkerHead(d, head.get("layers", 2)), codec=MarkerCodec(tok), | |
| vision=vision, | |
| calibrator=BucketTemperature(cal.get("temperatures"), cal.get("calibrate_media", False)), | |
| max_length=limits.get("max_length", 16384), | |
| image_text_length=limits.get("image_text_length", 896), | |
| max_tokens=limits.get("max_tokens", 65536), spec=json.loads(json.dumps(spec))) | |
| def from_checkpoint(path: str | Path, tok=None) -> DecisionModel: | |
| """A model folder (config.json + model.safetensors + tokenizer files) as a ready model.""" | |
| path = Path(path) | |
| model = build(json.loads((path / SPEC_FILE).read_text()), tok, root=path) | |
| load_strict(model, load_file(str(path / WEIGHTS_FILE))) | |
| return model | |
| def save_checkpoint(model: DecisionModel, out_dir: str | Path) -> Path: | |
| """Config + weights (the tokenizer files are copied separately: `model.codec.tok.save_pretrained`).""" | |
| out = Path(out_dir) | |
| out.mkdir(parents=True, exist_ok=True) | |
| spec = json.loads(json.dumps(model.spec)) | |
| spec["calibrator"] = {"temperatures": model.calibrator.temperatures, | |
| "calibrate_media": model.calibrator.calibrate_media} | |
| spec["limits"] = {"max_length": model.max_length, "image_text_length": model.image_text_length, | |
| "max_tokens": model.max_tokens} | |
| state = {k: v.detach().contiguous().cpu() for k, v in model.state_dict().items()} | |
| save_file(state, str(out / WEIGHTS_FILE), metadata={"format": FORMAT}) | |
| (out / SPEC_FILE).write_text(json.dumps(spec, indent=1)) | |
| return out | |