Download export.py from clecho52/NikeLLM: direct link, hf CLI and curl.
- Browser
- Download file 2.2 kB
-
https://huggingface.co/clecho52/NikeLLM/resolve/main/export.py
- Command line
-
hf download hf://clecho52/NikeLLM/export.py
-
curl -L -o export.py https://huggingface.co/clecho52/NikeLLM/resolve/main/export.py
2.2 kB
| """Export only inference weights and checkpoint metadata; never unpickle arbitrary objects.""" | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| from dataclasses import asdict | |
| import torch | |
| from safetensors.torch import save_file | |
| from model import Config, VOCAB | |
| def export(checkpoint, out, dtype='float32'): | |
| saved = torch.load(checkpoint, map_location='cpu', weights_only=True) | |
| weights = saved['model'] | |
| cfg = Config(**saved['config']) | |
| cfg.gated_middle = any(k.startswith('network.gates.') for k in weights) | |
| cfg.activation_checkpointing = False | |
| args = saved['args'] | |
| loops = args.get('middle_loops') | |
| if loops is None: | |
| loops = min(2, args.get('max_middle_loops') or 0) | |
| metadata = saved.get('tokenizer_info') | |
| vocab = weights['embedding.weight'].shape[0] | |
| if metadata is None and vocab != VOCAB: | |
| raise ValueError('Extended vocabulary requires original tokenizer_info; recover it before export.') | |
| if metadata is not None and vocab != VOCAB + len(metadata['added_tokens']): | |
| raise ValueError('Tokenizer/embedding size mismatch') | |
| config = dict(model=asdict(cfg), vocab_size=vocab, context_length=args['seq_len'], | |
| middle_loops=loops, delimiter=args.get('sft_delimiter', '###'), | |
| parameters=sum(v.numel() for v in weights.values()), | |
| training_step=saved.get('step'), training_tokens=saved.get('tokens'), | |
| weight_dtype=dtype) | |
| out = Path(out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| save_file({k: v.to(getattr(torch, dtype)).contiguous() for k,v in weights.items()}, str(out/'model.safetensors'), metadata={'format':'pt'}) | |
| for name, value in [('config.json',config), ('tokenizer_info.json',metadata)]: | |
| (out/name).write_text(json.dumps(value, ensure_ascii=False, indent=2)+'\n', encoding='utf-8') | |
| print(json.dumps(config, indent=2)) | |
| if __name__ == '__main__': | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument('checkpoint'); p.add_argument('--out', default='.') | |
| p.add_argument('--dtype', choices=['float32','bfloat16','float16'], default='float32') | |
| a = p.parse_args(); export(a.checkpoint,a.out,a.dtype) | |