File size: 22,393 Bytes
f1a4107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471461a
 
 
 
 
 
 
55bc27a
 
 
 
 
 
 
 
 
f1a4107
 
 
 
 
 
 
5692a3e
 
 
 
 
f1a4107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b42850
 
 
 
 
 
 
f60742b
 
 
 
 
 
 
 
 
 
 
471461a
 
f60742b
471461a
f60742b
 
471461a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1a4107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55bc27a
 
 
 
 
 
471461a
 
 
 
 
 
 
 
 
55bc27a
471461a
 
 
 
 
 
 
 
 
 
 
 
 
f1a4107
2b42850
 
 
 
f1a4107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b42850
 
 
f1a4107
 
 
 
 
 
 
 
 
 
 
 
471461a
 
 
f1a4107
471461a
f1a4107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55bc27a
 
 
 
f1a4107
55bc27a
 
 
 
f1a4107
 
 
55bc27a
f1a4107
 
 
 
55bc27a
f1a4107
 
2b42850
 
 
 
471461a
 
 
 
 
f1a4107
 
 
 
 
 
 
55bc27a
f1a4107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471461a
 
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
#!/usr/bin/env python3
"""Convert a supported Hugging Face model to uzu with RHT + INT4 Group32.

This bypasses MLX quantization and applies lalamo's HybridSpec directly:
  BF16 Linear -> RHT (Hadamard block 32) -> asymmetric INT4 group 32 -> HybridMatrix

The resulting lalamo model is saved, its HybridSpec metadata is rewritten to
uzu's flat form, and encoding.json is added.

Example (0.8B, local CPU):
  JAX_PLATFORM_NAME=cpu python scripts/rht_int4_convert.py \
    --spec-name Qwen3.5-0.8B \
    --lalamo-path /tmp/lalamo-direct \
    --output-dir /tmp/qwen35_0.8b_rht_int4_lalamo \
    --bf16-dir /tmp/qwen35_0.8b_bf16_lalamo
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import time
from dataclasses import replace
from pathlib import Path


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--spec-name", default="Qwen3.5-0.8B", help="Built-in lalamo model spec name")
    parser.add_argument("--hf-repo", default=None, help="Override origin with this Hugging Face repo")
    parser.add_argument("--hf-dir", default=None, help="Use a local HF snapshot directory instead of downloading")
    parser.add_argument("--vendor", default=None)
    parser.add_argument("--name", default=None)
    parser.add_argument("--output-dir", required=True)
    parser.add_argument("--bf16-dir", default=None, help="Also save the unquantized model here")
    parser.add_argument(
        "--load-from",
        default=None,
        help="Load an existing lalamo model directory instead of importing from Hugging Face",
    )
    parser.add_argument("--lalamo-path", default=os.environ.get("LALAMO_PATH", "/tmp/lalamo-direct"))
    parser.add_argument(
        "--parallel",
        choices=("replicated", "tensor", "fsdp", "data"),
        default="replicated",
        help="JAX device sharding: tensor/fsdp use all visible GPUs as one memory pool",
    )
    parser.add_argument("--bits", type=int, default=4, choices=(4, 6, 8))
    parser.add_argument(
        "--layer-bits-json",
        type=Path,
        default=None,
        help='Per-layer bit overrides: {"default": 4, "rules": [{"match": "mlp/down_projection", "bits": 6}]}',
    )
    parser.add_argument(
        "--symmetric-bits",
        default="8",
        help=(
            "Comma-separated bit widths exported as symmetric int (no zero points). "
            "uzu only compiles the zero-point gemm for 4 bits, so int8 must be symmetric. "
            "Pass an empty string to force asymmetric everywhere."
        ),
    )
    parser.add_argument(
        "--embedding-bits",
        type=int,
        default=None,
        choices=(4, 8),
        help="Override --bits for the tied/untied embedding and readout only",
    )
    parser.add_argument(
        "--layer-filter",
        default="",
        help="Only quantize layers whose path contains one of these comma-separated substrings; others stay full precision",
    )
    parser.add_argument("--group-size", type=int, default=32)
    parser.add_argument("--block-size", type=int, default=32, choices=(32, 64, 128))
    parser.add_argument(
        "--no-rht",
        action="store_true",
        help="Disable RHT and quantize with plain INT4 Group (isolation baseline)",
    )
    parser.add_argument(
        "--quantize-embedding",
        action="store_true",
        help="Also quantize the tied token embedding with RHT output-only (matches Mirai-M)",
    )
    parser.add_argument("--dtype", default="bfloat16")
    parser.add_argument("--skip-incompatible", action="store_true", help="Leave non-divisible Linears full precision")
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--hf-token", default=None)
    parser.add_argument(
        "--preconditioners",
        default=None,
        help="NPZ from scripts/yaqa_calibration.py; keys are '<path>/input_block' and optional '/output_block'",
    )
    parser.add_argument(
        "--calibration-json",
        type=Path,
        default=None,
        help="calibration.json paired with --preconditioners; embedded into provenance.json",
    )
    parser.add_argument(
        "--progress-jsonl",
        type=Path,
        default=None,
        help="default: <output-dir>/convert_progress.jsonl",
    )
    return parser.parse_args()


# uzu config strictness:
#   * every struct uses `#[serde(deny_unknown_fields)]`
#   * every field is required, even `Option<T>` (missing != null)
# lalamo emits a newer token_codec schema that violates both rules.
_UZU_TOKEN_CODEC_REQUIRED = ("output_parser_regex", "end_of_thinking_tag")
_UZU_TOKEN_CODEC_UNSUPPORTED = ("response_format", "reasoning_effort")


def normalize_config_for_uzu(output_dir: Path) -> None:
    path = output_dir / "config.json"
    config = json.loads(path.read_text())

    # Keep the untouched lalamo form for lalamo-side evaluation (PPL / logits).
    lalamo_path = output_dir / "config.lalamo.json"
    if not lalamo_path.exists():
        lalamo_path.write_text(json.dumps(config, indent=2) + "\n")

    token_codec = config.get("token_codec_config")
    if token_codec is None:
        return

    removed = [key for key in _UZU_TOKEN_CODEC_UNSUPPORTED if token_codec.pop(key, None) is not None]
    added = [key for key in _UZU_TOKEN_CODEC_REQUIRED if key not in token_codec]
    for key in added:
        token_codec[key] = None

    if removed or added:
        path.write_text(json.dumps(config, indent=2) + "\n")
    print(f"normalize config.json: removed={removed or '[]'} added={added or '[]'}")


def find_spec(qwen_models, name: str):
    for spec in qwen_models:
        if spec.name == name:
            return spec
    raise ValueError(f"model spec {name!r} not found")


def should_quantize(path: str, filters: list[str]) -> bool:
    """Empty filters means everything; otherwise any substring match."""
    if not filters:
        return True
    return any(item in path for item in filters)


def _normalize_path(path: str) -> str:
    """Drop the leading dots lalamo uses per component.

    Site paths look like ``.decoder/.transformer/.layers/[0]/.mlp/.down_projection``
    while the lane spec writes ``mlp/down_projection``, so a naive substring
    test never matched and every layer stayed at the default bits (measured:
    uniform4 and down-out6 produced identical PPL).
    """
    return path.replace(".", "")


def resolve_bits(path: str, rules: list[dict], default: int) -> int:
    """First rule whose ``match`` substring appears in the layer path wins."""
    normalized = _normalize_path(path)
    for rule in rules:
        match = _normalize_path(str(rule.get("match", "")))
        if match and match in normalized:
            return int(rule["bits"])
    return default


def load_layer_bits(spec_path: Path | None, default: int) -> tuple[dict, list[dict]]:
    if spec_path is None:
        return {"default": default, "rules": []}, []
    payload = json.loads(spec_path.read_text(encoding="utf-8"))
    rules = payload.get("rules", [])
    for rule in rules:
        bits = int(rule["bits"])
        if bits not in (4, 6, 8):
            raise SystemExit(f"unsupported bits in layer-bits-json: {bits}")
        if not rule.get("match"):
            raise SystemExit("layer-bits-json rule needs a non-empty 'match'")
    summary = {"default": int(payload.get("default", default)), "rules": rules}
    return summary, rules


def main() -> None:
    args = parse_args()
    os.environ.setdefault("JAX_PLATFORM_NAME", "cpu")
    if args.hf_token:
        os.environ["HF_TOKEN"] = args.hf_token

    progress_path = args.progress_jsonl or (Path(args.output_dir) / "convert_progress.jsonl")
    progress_path.parent.mkdir(parents=True, exist_ok=True)
    run_id = time.strftime("%Y%m%d-%H%M%S")
    progress_path.write_text("", encoding="utf-8")

    def progress(record: dict) -> None:
        record = {"run_id": run_id, **record}
        with open(progress_path, "a", encoding="utf-8") as file:
            file.write(json.dumps(record) + "\n")

    sys.path.insert(0, str(Path(__file__).resolve().parent))
    sys.path.insert(0, args.lalamo_path)

    import jax
    import jax.numpy as jnp
    import equinox as eqx
    import numpy as np

    from lalamo.compressed.hybrid import HybridSpec
    from lalamo.compressed.int import IntSpec
    from lalamo.compressed.incoherence import HadamardSpec, IncoherenceProcessingMode
    from lalamo.model_import.common import import_model
    from lalamo.model_import.model_specs.qwen import QWEN_MODELS
    from lalamo.modules.linear import Linear
    from lalamo.preconditioner import Preconditioner
    from lalamo.utils.sharding import ShardingConfig
    from lalamo.utils.surgery import map_nodes_of_type_with_path, select_nodes_of_type
    from lalamo.weight_matrix import Layout
    from rewrite_lalamo_hybrid_spec import rewrite

    if args.parallel == "tensor":
        sharding = ShardingConfig.tensor_parallel()
    elif args.parallel == "fsdp":
        sharding = ShardingConfig.fully_sharded_data_parallel()
    elif args.parallel == "data":
        sharding = ShardingConfig.data_parallel()
    else:
        sharding = ShardingConfig.replicated()

    if args.load_from:
        from lalamo.model import Model

        print(f"load lalamo model <- {args.load_from}")
        model = Model.load(args.load_from, sharding, dtype=jnp.dtype(args.dtype))
        print("load done")
    else:
        spec = find_spec(QWEN_MODELS, args.spec_name)
        if args.hf_dir:
            from pathlib import Path as _Path

            from lalamo.model_import.origins import LocalOrigin

            weight_files = tuple(sorted(path.name for path in _Path(args.hf_dir).glob("*.safetensors")))
            if not weight_files:
                raise SystemExit(f"no safetensors files in {args.hf_dir}")
            spec = replace(
                spec,
                vendor=args.vendor or spec.vendor,
                name=args.name or spec.name,
                origin=LocalOrigin(root=args.hf_dir, weight_files=weight_files),
            )
        elif args.hf_repo:
            from lalamo.model_import.origins import HuggingFaceOrigin

            spec = replace(
                spec,
                vendor=args.vendor or spec.vendor,
                name=args.name or spec.name,
                origin=HuggingFaceOrigin(repo=args.hf_repo),
            )

        print(f"import {spec.vendor}/{spec.name} <- {spec.origin.description}")
        results = import_model(
            spec,
            sharding_config=sharding,
            dtype=jnp.dtype(args.dtype),
        )
        model = results.model
        print("import done")

    if args.bf16_dir:
        bf16_dir = Path(args.bf16_dir)
        bf16_dir.mkdir(parents=True, exist_ok=True)
        print(f"save BF16 baseline -> {bf16_dir}")
        model.save(bf16_dir)
        normalize_config_for_uzu(bf16_dir)
        (bf16_dir / "COMPLETE").write_text("ok\n", encoding="utf-8")
        print("BF16 baseline saved")

    linear_list = select_nodes_of_type(Linear, model)
    required_divisor = args.group_size if args.no_rht else max(args.block_size, args.group_size)
    bad = []
    for path, linear in linear_list:
        shape = tuple(int(x) for x in linear.weights.shape)
        if len(shape) != 2 or any(dimension % required_divisor for dimension in shape):
            bad.append(("/".join(path), shape))

    print(f"Linear layers: {len(linear_list)}, incompatible: {len(bad)}")
    for path, shape in bad:
        print(f"  {path}: {shape}")
    if bad and not args.skip_incompatible:
        raise SystemExit("incompatible Linear shapes; use --skip-incompatible to leave them full precision")

    symmetric_bits = {
        int(item) for item in str(args.symmetric_bits).split(",") if item.strip()
    }
    if not symmetric_bits.issubset({4, 8}):
        raise SystemExit("--symmetric-bits accepts only 4 and 8")

    layer_bits_summary, layer_bits_rules = load_layer_bits(args.layer_bits_json, args.bits)
    if layer_bits_rules:
        print(f"layer bits overrides: {json.dumps(layer_bits_summary, ensure_ascii=False)}")

    def build_hybrid_spec(bits: int) -> HybridSpec:
        return HybridSpec(
            quantization_spec=IntSpec(
                bits=bits,
                group_size=args.group_size,
                is_symmetric=bits in symmetric_bits,
                layout=Layout.OUTPUT_INPUT,
            ),
            adapter_spec=None,
            incoherence_spec=None
            if args.no_rht
            else HadamardSpec(
                block_size=args.block_size,
                processing_mode=IncoherenceProcessingMode.INPUT_OUTPUT,
            ),
        )

    hybrid_spec = build_hybrid_spec(args.bits)
    layer_bits_used: dict[str, int] = {}
    quantize_key = jax.random.key(0)
    counts = {"quantized": 0, "skipped": 0, "yaqa": 0, "filtered": 0}
    layer_filters = [item for item in (args.layer_filter or "").split(",") if item]
    if layer_filters:
        print(f"layer filter: {layer_filters} (other layers stay full precision)")

    calibration = None
    if args.preconditioners:
        calibration = np.load(args.preconditioners)
        print(f"preconditioners: {args.preconditioners} ({len(calibration.files)} arrays)")

    def preconditioner_for(path) -> Preconditioner | None:
        if calibration is None:
            return None
        key = "/".join(path)
        input_key = f"{key}/input_block"
        if input_key not in calibration:
            return None
        output_key = f"{key}/output_block"
        return Preconditioner.init(
            input_block=jnp.asarray(calibration[input_key], dtype=jnp.float32),
            output_block=jnp.asarray(calibration[output_key], dtype=jnp.float32)
            if output_key in calibration
            else None,
        )

    def quantize_linear(path, linear: Linear) -> Linear:
        started = time.time()
        key = "/".join(path)
        if not should_quantize(key, layer_filters):
            counts["filtered"] += 1
            return linear
        shape = tuple(int(x) for x in linear.weights.shape)
        if len(shape) != 2 or any(dimension % required_divisor for dimension in shape):
            counts["skipped"] += 1
            progress({"path": key, "shape": shape, "status": "skipped", "elapsed_s": time.time() - started})
            if not args.skip_incompatible:
                raise ValueError(f"incompatible Linear {path}: {shape}")
            return linear
        counts["quantized"] += 1
        preconditioner = preconditioner_for(path)
        if preconditioner is not None:
            counts["yaqa"] += 1
        progress({"path": key, "shape": shape, "status": "started"})
        bits = resolve_bits(key, layer_bits_rules, layer_bits_summary["default"])
        layer_bits_used[key] = bits
        spec = build_hybrid_spec(bits) if bits != args.bits else hybrid_spec
        try:
            new_weights = spec.compress(
                linear.weights.decompress(),
                key=quantize_key,
                preconditioner=preconditioner,
                sharding_config=linear.weights.sharding_config,
                is_sharded=linear.weights.is_sharded,
            )
        except Exception as error:
            progress(
                {
                    "path": key,
                    "shape": shape,
                    "status": "failed",
                    "error": repr(error),
                    "elapsed_s": time.time() - started,
                }
            )
            raise
        progress(
            {
                "path": key,
                "shape": shape,
                "status": "quantized",
                "yaqa": preconditioner is not None,
                "elapsed_s": time.time() - started,
            }
        )
        return eqx.tree_at(lambda x: x.weights, linear, new_weights)

    if args.dry_run:
        print("dry-run: no quantization performed")
        return

    if args.no_rht:
        print(
            f"quantize -> plain INT{args.bits} group {args.group_size} "
            f"(symmetric={args.bits in symmetric_bits}, layout=output_input)"
        )
        if args.embedding_bits is not None:
            print(
                f"embedding quantize -> plain INT{args.embedding_bits} group {args.group_size} "
                f"(symmetric={args.embedding_bits in symmetric_bits})"
            )
    else:
        print(
            f"quantize -> RHT block {args.block_size} + INT{args.bits} group {args.group_size} "
            f"(symmetric={args.bits in symmetric_bits}, layout=output_input)"
        )
        if args.embedding_bits is not None:
            print(
                f"embedding quantize -> RHT block {args.block_size} + INT{args.embedding_bits} group {args.group_size} "
                f"(symmetric={args.embedding_bits in symmetric_bits})"
            )
    quantized_model = map_nodes_of_type_with_path(Linear, quantize_linear, model)
    print(
        f"quantized: {counts['quantized']}, skipped: {counts['skipped']}, "
        f"yaqa: {counts['yaqa']}, filtered: {counts['filtered']}"
    )
    if layer_bits_used:
        distribution = {}
        for bits in layer_bits_used.values():
            distribution[bits] = distribution.get(bits, 0) + 1
        print(f"bits distribution: {dict(sorted(distribution.items()))}")

    def embedding_spec(layout: Layout, mode: IncoherenceProcessingMode | None) -> HybridSpec:
        embedding_bits = args.embedding_bits if args.embedding_bits is not None else args.bits
        return HybridSpec(
            quantization_spec=IntSpec(
                bits=embedding_bits,
                group_size=args.group_size,
                is_symmetric=embedding_bits in symmetric_bits,
                layout=layout,
            ),
            adapter_spec=None,
            incoherence_spec=None
            if args.no_rht or mode is None
            else HadamardSpec(block_size=args.block_size, processing_mode=mode),
        )

    def quantize_matrix(matrix, layout: Layout, mode: IncoherenceProcessingMode | None, label: str):
        started = time.time()
        embedding_dim = int(matrix.shape[-1])
        if not args.no_rht and embedding_dim % args.block_size:
            raise SystemExit(f"{label} dim {embedding_dim} is not divisible by block size {args.block_size}")
        new_matrix = embedding_spec(layout, mode).compress(
            matrix.decompress(),
            key=quantize_key,
            sharding_config=matrix.sharding_config,
            is_sharded=matrix.is_sharded,
        )
        shape = tuple(int(x) for x in matrix.shape)
        print(f"{label} quantized: shape={shape}")
        progress({"path": label, "shape": shape, "status": "quantized", "yaqa": False, "elapsed_s": time.time() - started})
        return new_matrix

    if args.quantize_embedding:
        embedding = getattr(quantized_model.decoder, "embedding", None)
        tied = getattr(embedding, "embedding", None)
        if tied is not None:
            matrix = quantize_matrix(
                tied,
                Layout.INPUT_OUTPUT,
                IncoherenceProcessingMode.OUTPUT,
                "tied embedding",
            )
            new_embedding = eqx.tree_at(lambda node: node.embedding, embedding, matrix)
            quantized_model = eqx.tree_at(
                lambda root: root.decoder.embedding,
                quantized_model,
                new_embedding,
            )
        elif hasattr(embedding, "input_embedding") and hasattr(embedding, "output_embedding"):
            input_embedding = quantize_matrix(
                embedding.input_embedding,
                Layout.INPUT_OUTPUT,
                IncoherenceProcessingMode.OUTPUT,
                "input_embedding",
            )
            output_embedding = quantize_matrix(
                embedding.output_embedding,
                Layout.OUTPUT_INPUT,
                IncoherenceProcessingMode.INPUT,
                "output_embedding (lm_head)",
            )
            embedding = eqx.tree_at(lambda node: node.input_embedding, embedding, input_embedding)
            embedding = eqx.tree_at(lambda node: node.output_embedding, embedding, output_embedding)
            quantized_model = eqx.tree_at(
                lambda root: root.decoder.embedding,
                quantized_model,
                embedding,
            )
        else:
            print("embedding: neither tied nor untied embedding found, skipped")

    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    print(f"save quantized model -> {output_dir}")
    quantized_model.save(output_dir)

    print("rewrite HybridSpec metadata for uzu")
    rewrite(output_dir / "model.safetensors")

    normalize_config_for_uzu(output_dir)

    encoding = {"type": "hanashi", "name": "qwen3.5"}
    (output_dir / "encoding.json").write_text(json.dumps(encoding, indent=2) + "\n")

    calibration_summary = None
    if args.calibration_json and args.calibration_json.exists():
        calibration_summary = json.loads(args.calibration_json.read_text())
    source = args.hf_repo or (str(args.hf_dir) if args.hf_dir else None) or args.load_from or args.spec_name
    provenance = {
        "kind": "yaqa" if args.preconditioners else "rtn",
        "source": source,
        "preconditioners": args.preconditioners,
        "calibration_json": str(args.calibration_json) if args.calibration_json else None,
        "calibration": calibration_summary,
        "layer_bits": layer_bits_summary if layer_bits_rules else None,
        "layer_bits_used": layer_bits_used if layer_bits_rules else None,
        "overlap_checked": (
            bool(calibration_summary.get("overlap_checked"))
            if calibration_summary is not None
            else args.preconditioners is None
        ),
    }
    (output_dir / "provenance.json").write_text(
        json.dumps(provenance, indent=2, ensure_ascii=False) + "\n",
        encoding="utf-8",
    )
    (output_dir / "COMPLETE").write_text("ok\n", encoding="utf-8")
    print("encoding.json / provenance.json written")

    for f in sorted(output_dir.iterdir()):
        if f.is_file():
            print(f"  {f.name}: {f.stat().st_size / 1e6:.1f} MB")


if __name__ == "__main__":
    main()