Download export_compact.py from Hanshik/mythos-from-scratch: direct link, hf CLI and curl.
- Browser
- Download file 3.71 kB
-
https://huggingface.co/Hanshik/mythos-from-scratch/resolve/main/export_compact.py
- Command line
-
hf download hf://Hanshik/mythos-from-scratch/export_compact.py
-
curl -L -o export_compact.py https://huggingface.co/Hanshik/mythos-from-scratch/resolve/main/export_compact.py
3.71 kB
| """Compact Final Model Exporter (FP16 / BF16 / INT8 .safetensors) for Mythos-From-Scratch. | |
| Reduces final model size by 50% (fp16/bf16) or 75% (int8) and strips optimizer states | |
| so your finished model takes minimal GB on disk and Hugging Face Hub. | |
| """ | |
| import argparse | |
| import os | |
| import shutil | |
| import torch | |
| from safetensors.torch import load_file, save_file | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| def dir_size_mb(path: str) -> float: | |
| total = 0 | |
| for root, _, files in os.walk(path): | |
| for f in files: | |
| total += os.path.getsize(os.path.join(root, f)) | |
| return total / (1024 * 1024) | |
| def quantize_state_dict_int8(state_dict: dict) -> dict: | |
| """Per-row symmetric INT8 weight quantization stored cleanly in .safetensors.""" | |
| q_dict = {} | |
| for k, v in state_dict.items(): | |
| t = v.detach().cpu() | |
| if t.is_floating_point() and t.dim() >= 2 and t.numel() >= 1024: | |
| max_abs = t.abs().amax(dim=-1, keepdim=True).clamp(min=1e-8) | |
| scale = (max_abs / 127.0).to(torch.float16) | |
| q = torch.round(t / scale.float()).clamp(-127, 127).to(torch.int8) | |
| q_dict[f"{k}.__int8__"] = q.contiguous() | |
| q_dict[f"{k}.__scale__"] = scale.contiguous() | |
| else: | |
| q_dict[k] = (t.to(torch.float16) if t.is_floating_point() else t).contiguous() | |
| return q_dict | |
| def export_compact(src_dir: str, out_dir: str, precision: str = "fp16"): | |
| os.makedirs(out_dir, exist_ok=True) | |
| tok = AutoTokenizer.from_pretrained(src_dir) | |
| model = AutoModelForCausalLM.from_pretrained(src_dir, trust_remote_code=True) | |
| if precision in ("fp16", "bf16"): | |
| dtype = torch.float16 if precision == "fp16" else torch.bfloat16 | |
| model = model.to(dtype=dtype) | |
| model.save_pretrained(out_dir, safe_serialization=True) | |
| tok.save_pretrained(out_dir) | |
| elif precision == "int8": | |
| model.config.save_pretrained(out_dir) | |
| tok.save_pretrained(out_dir) | |
| q_sd = quantize_state_dict_int8(model.state_dict()) | |
| save_file(q_sd, os.path.join(out_dir, "model_int8.safetensors")) | |
| else: | |
| raise ValueError(f"Unsupported precision: {precision}") | |
| # Copy architecture code (skip trainer_state.pt / optimizer pickles) | |
| for fname in ("configuration_mythos.py", "modeling_mythos.py", "modeling_mythos_omni.py"): | |
| p = os.path.join(src_dir, fname) | |
| if os.path.exists(p): | |
| shutil.copy2(p, os.path.join(out_dir, fname)) | |
| # Compress omni_heads.safetensors to fp16 if present | |
| omni_st = os.path.join(src_dir, "omni_heads.safetensors") | |
| if os.path.exists(omni_st): | |
| heads = load_file(omni_st, device="cpu") | |
| comp_heads = { | |
| k: (v.to(torch.float16) if v.is_floating_point() else v).contiguous() | |
| for k, v in heads.items() | |
| } | |
| save_file(comp_heads, os.path.join(out_dir, "omni_heads.safetensors")) | |
| before_mb = dir_size_mb(src_dir) | |
| after_mb = dir_size_mb(out_dir) | |
| print(f"Compact export ({precision}) complete!") | |
| print(f" Before ({src_dir}): {before_mb:.1f} MB ({before_mb / 1024:.2f} GB)") | |
| print(f" After ({out_dir}): {after_mb:.1f} MB ({after_mb / 1024:.2f} GB)") | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="Export Mythos as a compact fp16/bf16/int8 .safetensors model.") | |
| parser.add_argument("--src_dir", type=str, default="./mythos_pretrained") | |
| parser.add_argument("--out_dir", type=str, default="./mythos_final_compact") | |
| parser.add_argument("--precision", type=str, default="fp16", choices=["fp16", "bf16", "int8"]) | |
| args = parser.parse_args() | |
| export_compact(args.src_dir, args.out_dir, precision=args.precision) | |