File size: 3,642 Bytes
f1a4107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f26e497
4d9b333
 
 
 
 
 
f26e497
4d9b333
 
 
f26e497
 
 
f1a4107
 
 
 
 
 
 
 
 
 
 
f26e497
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Create a lalamo-loadable evaluation copy from a uzu-normalized model directory.

Conversion rewrites two things for uzu:
  * config.json (strict fields, no response_format)
  * HybridSpec metadata (flat form, original kept as model.safetensors.lalamo.bak)

lalamo evaluation (PPL / logits) needs the opposite form. This script links the
original weights and writes a lalamo config without duplicating tensor bytes.

Usage:
  python scripts/make_lalamo_eval_copy.py \
    --source /tmp/qwen35_0.8b_rht_int4_lalamo \
    --dest /tmp/qwen35_0.8b_rht_int4_lalamo_lalamo
"""

from __future__ import annotations

import argparse
import json
import os
import shutil
from pathlib import Path

RESPONSE_FORMAT = {
    "reasoning_pattern": r"(?: response|(?:(?: think|(?=.* response))(?P<chain_of_thought>.*?)(?: response\s*|\Z)))?(?P<response>.*)",
    "prefixes": [" think", " response"],
    "turn_pattern": None,
    "tool_calls": {
        "tags": ["<tool_call>", "</tool_call>"],
        "function_pattern": r"<function=([^>\n]+)>(.*?)</function>",
        "parameter_pattern": r"<parameter=([^>\n]+)>\n?(.*?)\n?</parameter>",
    },
}


def link_or_copy(source: Path, destination: Path) -> None:
    if destination.exists():
        destination.unlink()
    try:
        os.link(source, destination)
    except OSError:
        shutil.copy2(source, destination)


def lalamo_config(source: Path) -> dict:
    saved = source / "config.lalamo.json"
    if saved.exists():
        return json.loads(saved.read_text())

    config = json.loads((source / "config.json").read_text())
    token_codec = config.get("token_codec_config")
    if token_codec is not None:
        token_codec.pop("end_of_thinking_tag", None)
        token_codec.pop("output_parser_regex", None)
        token_codec["response_format"] = RESPONSE_FORMAT
    return config


def fresh_backup(weights: Path, backup: Path) -> bool:
    """The backup holds pre-rewrite bytes, so mtimes cannot reveal staleness.

    rewrite_lalamo_hybrid_spec stamps the backup with the rewritten file's
    mtime; the backup is only valid while the weights carry that mtime.
    """
    stamp = backup.with_name(backup.name + ".stamp")
    try:
        recorded = int(stamp.read_text(encoding="utf-8").strip())
        return recorded == weights.stat().st_mtime_ns
    except (OSError, ValueError):
        return False


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--source", type=Path, required=True)
    parser.add_argument("--dest", type=Path, required=True)
    args = parser.parse_args()

    args.dest.mkdir(parents=True, exist_ok=True)
    (args.dest / "config.json").write_text(json.dumps(lalamo_config(args.source), indent=2) + "\n")

    weights = args.source / "model.safetensors"
    original_weights = args.source / "model.safetensors.lalamo.bak"
    use_backup = original_weights.exists() and fresh_backup(weights, original_weights)
    if original_weights.exists() and not use_backup:
        print(
            f"warning: {original_weights.name} is older than {weights.name}; "
            "ignoring the stale lalamo backup",
            flush=True,
        )
    link_or_copy(original_weights if use_backup else weights, args.dest / "model.safetensors")

    for name in ("tokenizer.json", "encoding.json"):
        source = args.source / name
        if source.exists():
            link_or_copy(source, args.dest / name)

    print(f"created {args.dest}")
    for file in sorted(args.dest.iterdir()):
        print(f"  {file.name}: {file.stat().st_size / 1e6:.1f} MB")


if __name__ == "__main__":
    main()