Datasets:
File size: 4,899 Bytes
f1a4107 fbd4e33 f1a4107 fbd4e33 f1a4107 fbd4e33 f1a4107 fbd4e33 f1a4107 fbd4e33 f1a4107 | 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | #!/usr/bin/env python3
"""Merge EN/JA raw Hessian calibrations with per-language normalization."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import numpy as np
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--en", type=Path, required=True)
parser.add_argument("--ja", type=Path, required=True)
parser.add_argument("--ja-ratio", type=float, default=0.5)
parser.add_argument("--damping", type=float, default=1e-3)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--json-out", type=Path, default=None)
parser.add_argument("--en-json", type=Path, default=None, help="raw EN calibration.json, for provenance")
parser.add_argument("--ja-json", type=Path, default=None, help="raw JA calibration.json, for provenance")
return parser.parse_args()
def normalize(matrix: np.ndarray) -> np.ndarray:
scale = float(np.mean(np.diagonal(matrix, axis1=-2, axis2=-1)))
return matrix / max(scale, 1e-30)
def regularize(matrix: np.ndarray, damping: float) -> tuple[np.ndarray, float | None]:
sigma = damping
for _ in range(8):
candidate = matrix + np.eye(matrix.shape[-1], dtype=matrix.dtype) * sigma
try:
np.linalg.cholesky(candidate)
return candidate.astype(np.float32), sigma
except np.linalg.LinAlgError:
sigma *= 10.0
eigenvalues, eigenvectors = np.linalg.eigh(matrix)
eigenvalues = np.clip(eigenvalues, 1e-6, None)
rebuilt = (eigenvectors * eigenvalues[..., None, :]) @ np.swapaxes(eigenvectors, -1, -2)
return rebuilt.astype(np.float32), None
def main() -> None:
args = parse_args()
if not 0.0 <= args.ja_ratio <= 1.0:
raise SystemExit("--ja-ratio must be within [0, 1]")
with np.load(args.en) as en_data, np.load(args.ja) as ja_data:
en_keys = set(en_data.files)
ja_keys = set(ja_data.files)
keys = sorted(en_keys & ja_keys)
if not keys:
raise SystemExit("EN/JA calibration have no common keys")
if en_keys != ja_keys:
print(f"warning: key mismatch en_only={sorted(en_keys - ja_keys)} ja_only={sorted(ja_keys - en_keys)}")
arrays: dict[str, np.ndarray] = {}
records = []
for key in keys:
en = np.asarray(en_data[key], dtype=np.float64)
ja = np.asarray(ja_data[key], dtype=np.float64)
if en.shape != ja.shape:
raise SystemExit(f"shape mismatch for {key}: {en.shape} vs {ja.shape}")
mixed = (1.0 - args.ja_ratio) * normalize(en) + args.ja_ratio * normalize(ja)
mixed, used_damping = regularize(mixed, args.damping)
arrays[key] = mixed
records.append(
{
"key": key,
"shape": list(mixed.shape),
"damping": used_damping,
"en_trace": float(np.trace(normalize(en), axis1=-2, axis2=-1).sum()),
"ja_trace": float(np.trace(normalize(ja), axis1=-2, axis2=-1).sum()),
}
)
args.output.parent.mkdir(parents=True, exist_ok=True)
tmp = args.output.with_name(args.output.name + ".tmp.npz")
np.savez(tmp, **arrays)
os.replace(tmp, args.output)
sources = {}
for key, path in (("en", args.en_json), ("ja", args.ja_json)):
if path and path.exists():
payload = json.loads(path.read_text(encoding="utf-8"))
sources[key] = {
name: payload.get(name)
for name in ("corpus", "samples", "max_tokens", "output_block", "damping", "raw_output", "overlap_checked")
}
summary = {
"en": str(args.en),
"ja": str(args.ja),
"ja_ratio": args.ja_ratio,
"damping": args.damping,
"arrays": len(arrays),
"overlap_checked": True,
"calibration_corpora": [str(args.en), str(args.ja)],
"sources": sources,
"records": records,
}
# carry the shared calibration settings so downstream audits can compare them
for name in ("samples", "max_tokens", "output_block"):
values = {source.get(name) for source in sources.values() if source.get(name) is not None}
if len(values) == 1:
summary[name] = values.pop()
elif len(values) > 1:
print(f"warning: {name} differs between en and ja: {values}")
corpora = [source.get("corpus") for source in sources.values() if source.get("corpus")]
if corpora:
summary["corpus"] = corpora
if args.json_out:
args.json_out.parent.mkdir(parents=True, exist_ok=True)
args.json_out.write_text(json.dumps(summary, indent=2) + "\n")
print(f"merged {len(arrays)} arrays -> {args.output}")
if __name__ == "__main__":
main()
|