Download load_model.py from MethodWhite/materia-v2-1b: direct link, hf CLI and curl.
- Browser
- Download file 2.18 kB
-
https://huggingface.co/MethodWhite/materia-v2-1b/resolve/main/load_model.py
- Command line
-
hf download hf://MethodWhite/materia-v2-1b/load_model.py
-
curl -L -o load_model.py https://huggingface.co/MethodWhite/materia-v2-1b/resolve/main/load_model.py
2.18 kB
| #!/usr/bin/env python3 | |
| """Load MethodWhite/materia-v2-1b with nothing but this folder. | |
| pip install -r requirements.txt | |
| python load_model.py | |
| python load_model.py "The capital of France is" | |
| Rules: | |
| - `model.safetensors` holds bf16 weights. | |
| - `config.json` holds the geometry; the architecture code is `modeling_materia.py` | |
| in this same folder, so no other repository is needed. | |
| """ | |
| import json | |
| import os | |
| import sys | |
| import torch | |
| from safetensors.torch import load_file | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| from modeling_materia import MateriaV2Fast # noqa: E402 | |
| def load(folder=HERE, device=None): | |
| cfg = json.load(open(os.path.join(folder, "config.json"))) | |
| geo = dict(cfg["geometry"]) | |
| model = MateriaV2Fast(cycles=1, sparsity=0.0, | |
| train_ctx=cfg.get("train_ctx"), **geo) | |
| state = load_file(os.path.join(folder, "model.safetensors")) | |
| missing, unexpected = model.load_state_dict(state, strict=False) | |
| if unexpected: | |
| raise SystemExit(f"unexpected keys: {unexpected[:5]}") | |
| device = device or ("cuda" if torch.cuda.is_available() else "cpu") | |
| model.to(device).eval() | |
| from transformers import AutoTokenizer | |
| tok = AutoTokenizer.from_pretrained("gpt2") | |
| print(f"cargado: {model.n_params()/1e9:.3f}B params en {device}") | |
| return model, tok, cfg | |
| def generate(model, tok, prompt, max_new_tokens=32, ctx=1024): | |
| """Greedy loop. MATERIA has no KV cache, so cost grows quadratically.""" | |
| ids = tok(prompt, return_tensors="pt", | |
| add_special_tokens=False).input_ids.to(model.embed.weight.device) | |
| for _ in range(max_new_tokens): | |
| logits, _ = model(ids[:, -ctx:]) | |
| ids = torch.cat([ids, logits[:, -1, :].argmax(-1, keepdim=True)], dim=1) | |
| return tok.decode(ids[0, len(tok(prompt, add_special_tokens=False).input_ids):], | |
| skip_special_tokens=True) | |
| if __name__ == "__main__": | |
| model, tok, cfg = load() | |
| prompt = sys.argv[1] if len(sys.argv) > 1 else "The capital of France is" | |
| print(f"\nprompt: {prompt}") | |
| print(f"output: {generate(model, tok, prompt)}") | |