#!/usr/bin/env python """Prepare the laya checkpoint for a low-memory run (run this once, before label_anger.py). 1. `models/laya-ml/multilingual` - the published `convaiinnovations/laya` repo, but only the `multilingual/*` subfolder (643 MB). laya's own loader accepts a local directory, so nothing else is downloaded and no Hub call happens at inference time. 2. `models/enc-bf16/model.safetensors` - the `encoder.*` tensors of that checkpoint, prefix stripped, in one file next to the encoder config. laya's `build_model` builds the encoder from `encoder/config.json` with `from_config`, i.e. it allocates a full random fp32 copy of the encoder (1.29 GB) that `Agent.__init__` then overwrites from `model.safetensors`. Loading the same tensors through `from_pretrained(..., low_cpu_mem_usage=True)` instead materialises each tensor exactly once, in bf16 - see laya_opt.py. Verified: the two paths end up with identical weights (laya's own strict `load_state_dict` overwrites every key), and logits match laya's stock `Agent.predict` to 4 decimal places (dev_probe.py). Usage: python prepare_checkpoint.py [--force] """ import argparse import json import os SRC_REPO = "convaiinnovations/laya" CKPT = "models/laya-ml/multilingual" ENC = "models/enc-bf16" def main(): ap = argparse.ArgumentParser() ap.add_argument("--force", action="store_true") args = ap.parse_args() import torch from safetensors import safe_open from safetensors.torch import save_file if args.force or not os.path.exists(os.path.join(CKPT, "model.safetensors")): from huggingface_hub import snapshot_download os.makedirs(CKPT.rsplit("/", 1)[0], exist_ok=True) snapshot_download(SRC_REPO, allow_patterns=["multilingual/*"], local_dir="models/laya-ml") print("[prep] checkpoint at", CKPT) else: print("[prep] checkpoint already present") os.makedirs(ENC, exist_ok=True) cfg = json.load(open(os.path.join(CKPT, "encoder", "config.json"))) json.dump(cfg, open(os.path.join(ENC, "config.json"), "w"), indent=2) out_path = os.path.join(ENC, "model.safetensors") if args.force or not os.path.exists(out_path): enc = {} with safe_open(os.path.join(CKPT, "model.safetensors"), framework="pt") as f: for k in f.keys(): if k.startswith("encoder."): enc[k[len("encoder."):]] = f.get_tensor(k) # already bf16 on disk save_file(enc, out_path, metadata={"format": "pt"}) n = sum(t.numel() for t in enc.values()) print("[prep] encoder copy: %d tensors, %.1fM params, %.0f MB -> %s" % (len(enc), n / 1e6, os.path.getsize(out_path) / 1e6, out_path)) else: print("[prep] encoder copy already present") # sanity: every key laya's DecisionModel expects must exist in the checkpoint from laya.common import build_model # noqa: F401 (import check only) with safe_open(os.path.join(CKPT, "model.safetensors"), framework="pt") as f: keys = set(f.keys()) assert {"encoder.embeddings.tok_embeddings.weight", "scorer.0.weight", "type_emb.weight", "act_head.0.weight", "temperature"} <= keys, sorted(keys)[:5] print("[prep] ok - checkpoint exposes %d tensors incl. all laya head keys" % len(keys)) if __name__ == "__main__": main()