File size: 2,549 Bytes
87cc7f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""Apply the authors' indexed BF16 replacements to a pinned base safetensors file."""
import argparse
import hashlib
from pathlib import Path

import numpy as np
import torch
from safetensors.torch import load_file, save_file


def tensor_sha256(tensor: torch.Tensor) -> str:
    raw = tensor.detach().contiguous().view(torch.uint8).cpu().numpy().tobytes()
    return hashlib.sha256(raw).hexdigest()


def apply_edit(base_path: Path, edit_path: Path, manifest_path: Path, output_path: Path) -> None:
    manifest = __import__("json").loads(manifest_path.read_text(encoding="utf-8"))
    weights = load_file(str(base_path), device="cpu")
    with np.load(edit_path, allow_pickle=False) as diff:
        for i, spec in enumerate(manifest["tensors"]):
            name = spec["name"]
            tensor = weights[name]
            if tensor.dtype != torch.bfloat16:
                raise ValueError(f"{name}: expected BF16, got {tensor.dtype}")
            if tensor_sha256(tensor) != spec["base_sha256"]:
                raise ValueError(f"{name}: base tensor hash does not match the pinned manifest")
            indices = torch.from_numpy(np.asarray(diff[f"t{i}_idx"], dtype=np.int64))
            values = torch.from_numpy(np.asarray(diff[f"t{i}_val"], dtype=np.uint16).copy())
            flat = tensor.view(torch.uint16).reshape(-1)
            if indices.numel() != values.numel() or int(indices.max()) >= flat.numel():
                raise ValueError(f"{name}: malformed sparse replacement arrays")
            flat[indices] = values
            if tensor_sha256(tensor) != spec["edited_sha256"]:
                raise ValueError(f"{name}: edited tensor hash does not match the published manifest")
    output_path.parent.mkdir(parents=True, exist_ok=True)
    save_file(weights, str(output_path))
    print(f"wrote reconstructed checkpoint file {output_path}; verify remaining config/tokenizer files from the pinned upstream snapshot")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--base-checkpoint", required=True, type=Path)
    parser.add_argument("--edit", type=Path, default=Path("results/checkpoint_analysis/published_sparse_edit.npz"))
    parser.add_argument("--manifest", type=Path, default=Path("results/checkpoint_analysis/manifest.json"))
    parser.add_argument("--output", required=True, type=Path)
    args = parser.parse_args()
    apply_edit(args.base_checkpoint, args.edit, args.manifest, args.output)

if __name__ == "__main__":
    main()