File size: 28,244 Bytes
70ac094
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
from __future__ import annotations

import argparse
import functools
import hashlib
import json
import os
import traceback
from copy import deepcopy
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Iterable, Mapping, Sequence

import numpy as np


CALIBRATION_SIZE = 128
CALIBRATION_SEQUENCE_LENGTH = 2048
CALIBRATION_SCHEMA_VERSION = 1
SAMPLING_ALGORITHM = "numpy-default_rng-shuffle-complete-index-array-v1"


@dataclass(frozen=True)
class DatasetSpec:
    name: str
    repo_id: str
    config: str
    split: str
    revision: str
    row_count: int


# Repository revisions were resolved from the Hugging Face API on 2026-07-13.
# Changing one is an environment change and must produce a new calibration artifact.
DATASET_SPECS = {
    "c4": DatasetSpec(
        name="c4",
        repo_id="allenai/c4",
        config="en",
        split="train",
        revision="1588ec454efa1a09f29cd18ddd04fe05fc8653a2",
        row_count=364_868_892,
    ),
    "wikitext2": DatasetSpec(
        name="wikitext2",
        repo_id="Salesforce/wikitext",
        config="wikitext-2-raw-v1",
        split="train",
        revision="b08601e04326c79dfdd32d625aee71d232d685c3",
        row_count=36_718,
    ),
}


class CalibrationArtifactError(ValueError):
    pass


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Build GPTQ/AWQ checkpoints from a frozen paired calibration artifact."
    )
    parser.add_argument("--model-id", required=True)
    parser.add_argument(
        "--model-revision",
        required=True,
        help="Immutable model commit used for both tokenizer and model loading.",
    )
    parser.add_argument("--method", choices=["gptq", "awq"])
    parser.add_argument("--output-dir")
    parser.add_argument("--seed", type=int, required=True)
    parser.add_argument("--bits", type=int, default=4)
    parser.add_argument("--dataset", choices=sorted(DATASET_SPECS), default="c4")
    parser.add_argument(
        "--dataset-revision",
        help="Override only to create a new, explicitly recorded environment cell.",
    )
    parser.add_argument("--dataset-cache-dir")
    parser.add_argument("--calibration-artifact", required=True)
    parser.add_argument(
        "--prepare-calibration-only",
        action="store_true",
        help="Create/validate the shared artifact without loading a quantization backend.",
    )
    parser.add_argument(
        "--verify-stream-row-count",
        action="store_true",
        help="Preflight-only: exhaust the pinned stream and fail closed unless it "
        "yields exactly the registered row_count before any artifact is created.",
    )
    parser.add_argument("--trust-remote-code", action="store_true")
    args = parser.parse_args()

    if not args.prepare_calibration_only and (args.method is None or args.output_dir is None):
        parser.error("--method and --output-dir are required unless --prepare-calibration-only is used")

    try:
        from transformers import AutoTokenizer
    except ImportError as exc:
        raise SystemExit("Missing transformers. Install the pinned container runtime.") from exc

    tokenizer = AutoTokenizer.from_pretrained(
        args.model_id,
        revision=args.model_revision,
        trust_remote_code=args.trust_remote_code,
    )
    spec = DATASET_SPECS[args.dataset]
    if args.dataset_revision:
        spec = DatasetSpec(
            spec.name,
            spec.repo_id,
            spec.config,
            spec.split,
            args.dataset_revision,
            spec.row_count,
        )

    if args.verify_stream_row_count:
        try:
            from datasets import load_dataset
        except ImportError as exc:
            raise SystemExit("Missing datasets. Install the pinned container runtime.") from exc
        counted = verify_stream_row_count(
            make_stream_factory(load_dataset, spec, args.dataset_cache_dir), spec
        )
        print(f"Stream row count verified: {counted} rows match the registered row_count", flush=True)

    artifact_path = Path(args.calibration_artifact)
    artifact = load_or_create_calibration_artifact(
        artifact_path,
        tokenizer=tokenizer,
        model_id=args.model_id,
        model_revision=args.model_revision,
        dataset_spec=spec,
        seed=args.seed,
        dataset_cache_dir=args.dataset_cache_dir,
    )
    print(f"Calibration artifact: {artifact_path} ({artifact['artifact_sha256']})", flush=True)
    if args.prepare_calibration_only:
        return

    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    if args.method == "gptq":
        build_gptq(args, tokenizer, artifact)
    else:
        build_awq(args, tokenizer, artifact)
    write_calibration_receipt(output_dir / "calibration_manifest.json", artifact, args)


def load_or_create_calibration_artifact(
    path: Path,
    *,
    tokenizer: Any,
    model_id: str,
    model_revision: str,
    dataset_spec: DatasetSpec,
    seed: int,
    dataset_cache_dir: str | None = None,
) -> dict[str, Any]:
    if path.exists():
        artifact = read_json(path)
        validate_calibration_artifact(
            artifact,
            tokenizer=tokenizer,
            model_id=model_id,
            model_revision=model_revision,
            dataset_spec=dataset_spec,
            seed=seed,
        )
        return artifact

    try:
        from datasets import load_dataset
    except ImportError as exc:
        raise SystemExit("Missing datasets. Install the pinned container runtime.") from exc

    if dataset_spec.name == "c4":
        artifact = create_calibration_artifact_from_stream(
            make_stream_factory(load_dataset, dataset_spec, dataset_cache_dir),
            tokenizer,
            model_id=model_id,
            model_revision=model_revision,
            dataset_spec=dataset_spec,
            seed=seed,
        )
    else:
        dataset = load_dataset(
            dataset_spec.repo_id,
            dataset_spec.config,
            split=dataset_spec.split,
            revision=dataset_spec.revision,
            streaming=False,
            cache_dir=dataset_cache_dir,
        )
        artifact = create_calibration_artifact(
            dataset,
            tokenizer,
            model_id=model_id,
            model_revision=model_revision,
            dataset_spec=dataset_spec,
            seed=seed,
        )
    write_json_atomic(path, artifact)
    return artifact


def create_calibration_artifact(
    dataset: Sequence[Mapping[str, Any]],
    tokenizer: Any,
    *,
    model_id: str,
    model_revision: str,
    dataset_spec: DatasetSpec,
    seed: int,
    size: int = CALIBRATION_SIZE,
    sequence_length: int = CALIBRATION_SEQUENCE_LENGTH,
) -> dict[str, Any]:
    _validate_requested_shape(size, sequence_length)
    try:
        dataset_length = len(dataset)
    except TypeError as exc:
        raise CalibrationArtifactError(
            "the registered algorithm requires an indexable, non-streaming dataset"
        ) from exc
    if dataset_length < size:
        raise CalibrationArtifactError(
            f"dataset has {dataset_length} rows, fewer than requested calibration size {size}"
        )

    indices = shuffled_indices(dataset_length, seed)
    samples, visited, skipped_short = select_samples_in_registered_order(
        ((int(index), dataset[int(index)]) for index in indices),
        tokenizer,
        size=size,
        sequence_length=sequence_length,
        dataset_length=dataset_length,
    )
    dataset_fingerprint = getattr(dataset, "_fingerprint", None)
    return assemble_calibration_artifact(
        samples,
        tokenizer=tokenizer,
        model_id=model_id,
        model_revision=model_revision,
        dataset_spec=dataset_spec,
        seed=seed,
        size=size,
        sequence_length=sequence_length,
        dataset_length=dataset_length,
        dataset_fingerprint=str(dataset_fingerprint) if dataset_fingerprint else None,
        visited=visited,
        skipped_short=skipped_short,
        retrieval={"strategy": "indexable-dataset"},
    )


def make_stream_factory(
    load_dataset: Callable[..., Iterable[Mapping[str, Any]]],
    dataset_spec: DatasetSpec,
    dataset_cache_dir: str | None,
) -> Callable[[], Iterable[Mapping[str, Any]]]:
    def stream_factory() -> Iterable[Mapping[str, Any]]:
        return load_dataset(
            dataset_spec.repo_id,
            dataset_spec.config,
            split=dataset_spec.split,
            revision=dataset_spec.revision,
            streaming=True,
            cache_dir=dataset_cache_dir,
        )

    return stream_factory


def verify_stream_row_count(
    stream_factory: Callable[[], Iterable[Mapping[str, Any]]],
    dataset_spec: DatasetSpec,
) -> int:
    """Exhaust the stream and fail closed unless it yields exactly row_count rows.

    The registered permutation is built over DatasetSpec.row_count. An overstated
    count already fails closed in retrieve_stream_rows, but an understated count
    would silently shrink the sampling universe, so the preflight must run this
    check once per pinned dataset revision before any artifact is created.
    """
    expected = int(dataset_spec.row_count)
    actual = 0
    for actual, _ in enumerate(stream_factory(), start=1):
        pass
    if actual != expected:
        raise CalibrationArtifactError(
            f"{dataset_spec.repo_id} ({dataset_spec.config}/{dataset_spec.split}) stream "
            f"yielded {actual} rows but the registered row_count is {expected}; the frozen "
            "permutation would cover the wrong sampling universe"
        )
    return actual


def create_calibration_artifact_from_stream(
    stream_factory: Callable[[], Iterable[Mapping[str, Any]]],
    tokenizer: Any,
    *,
    model_id: str,
    model_revision: str,
    dataset_spec: DatasetSpec,
    seed: int,
    size: int = CALIBRATION_SIZE,
    sequence_length: int = CALIBRATION_SEQUENCE_LENGTH,
    retrieval_window: int = 4096,
) -> dict[str, Any]:
    """Retrieve shuffled indices through a sequential stream without changing order.

    The complete registered NumPy permutation is still generated. A prefix of its
    indices is fetched in one sequential pass, then restored to permutation order
    before eligibility checks. If the prefix has too few eligible rows, a larger
    disjoint prefix is fetched in another deterministic pass.

    Assumes the sequential streaming order of the pinned dataset revision equals
    indexed row order, and that DatasetSpec.row_count is exact; both are verified
    once per revision by the preflight's verify_stream_row_count pass.
    """
    _validate_requested_shape(size, sequence_length)
    if retrieval_window < size:
        raise CalibrationArtifactError("stream retrieval_window must be at least the sample count")
    dataset_length = int(dataset_spec.row_count)
    indices = shuffled_indices(dataset_length, seed)
    selected: list[dict[str, Any]] = []
    visited = 0
    skipped_short = 0
    total_stream_rows_scanned = 0
    passes = 0
    for start in range(0, dataset_length, retrieval_window):
        requested = [int(value) for value in indices[start : start + retrieval_window]]
        retrieved, scanned = retrieve_stream_rows(stream_factory(), requested)
        passes += 1
        total_stream_rows_scanned += scanned
        remaining = size - len(selected)
        batch, batch_visited, batch_skipped = select_samples_in_registered_order(
            ((index, retrieved[index]) for index in requested),
            tokenizer,
            size=remaining,
            sequence_length=sequence_length,
            dataset_length=dataset_length,
            require_full=False,
        )
        selected.extend(batch)
        visited += batch_visited
        skipped_short += batch_skipped
        if len(selected) == size:
            break
    if len(selected) != size:
        raise CalibrationArtifactError(
            f"only {len(selected)} of {dataset_length} rows contain at least "
            f"{sequence_length} tokens; the frozen protocol requires {size}"
        )
    return assemble_calibration_artifact(
        selected,
        tokenizer=tokenizer,
        model_id=model_id,
        model_revision=model_revision,
        dataset_spec=dataset_spec,
        seed=seed,
        size=size,
        sequence_length=sequence_length,
        dataset_length=dataset_length,
        dataset_fingerprint=None,
        visited=visited,
        skipped_short=skipped_short,
        retrieval={
            "strategy": "sequential-stream-index-retrieval",
            "window_size": retrieval_window,
            "passes": passes,
            "stream_rows_scanned": total_stream_rows_scanned,
        },
    )


def shuffled_indices(dataset_length: int, seed: int) -> np.ndarray:
    indices = np.arange(dataset_length, dtype=np.int64)
    np.random.default_rng(seed).shuffle(indices)
    return indices


def retrieve_stream_rows(
    stream: Iterable[Mapping[str, Any]], requested_indices: Sequence[int]
) -> tuple[dict[int, Mapping[str, Any]], int]:
    targets = set(requested_indices)
    found: dict[int, Mapping[str, Any]] = {}
    scanned = 0
    for index, row in enumerate(stream):
        scanned = index + 1
        if index in targets:
            found[index] = row
            if len(found) == len(targets):
                break
    missing = sorted(targets - set(found))
    if missing:
        preview = missing[:5]
        raise CalibrationArtifactError(
            f"stream ended before registered dataset indices were retrieved: {preview}"
        )
    return found, scanned


def select_samples_in_registered_order(
    indexed_rows: Iterable[tuple[int, Mapping[str, Any]]],
    tokenizer: Any,
    *,
    size: int,
    sequence_length: int,
    dataset_length: int,
    require_full: bool = True,
) -> tuple[list[dict[str, Any]], int, int]:
    samples: list[dict[str, Any]] = []
    skipped_short = 0
    visited = 0
    for index, row in indexed_rows:
        visited += 1
        if "text" not in row:
            raise CalibrationArtifactError(f"dataset row {index} has no 'text' field")
        text = str(row["text"])
        token_ids = encode_text(tokenizer, text, truncation=False)
        if len(token_ids) < sequence_length:
            skipped_short += 1
            continue
        selected_ids = token_ids[:sequence_length]
        samples.append(
            {
                "document_index": int(index),
                "text": text,
                "input_ids": selected_ids,
                "token_sha256": token_ids_sha256(selected_ids),
            }
        )
        if len(samples) == size:
            break
    if require_full and len(samples) != size:
        raise CalibrationArtifactError(
            f"only {len(samples)} of {dataset_length} rows contain at least "
            f"{sequence_length} tokens; the frozen protocol requires {size}"
        )
    return samples, visited, skipped_short


def assemble_calibration_artifact(
    samples: list[dict[str, Any]],
    *,
    tokenizer: Any,
    model_id: str,
    model_revision: str,
    dataset_spec: DatasetSpec,
    seed: int,
    size: int,
    sequence_length: int,
    dataset_length: int,
    dataset_fingerprint: str | None,
    visited: int,
    skipped_short: int,
    retrieval: Mapping[str, Any],
) -> dict[str, Any]:
    artifact: dict[str, Any] = {
        "schema_version": CALIBRATION_SCHEMA_VERSION,
        "sampling_algorithm": SAMPLING_ALGORITHM,
        "seed": int(seed),
        "sample_count": int(size),
        "sequence_length": int(sequence_length),
        "visited_document_count": visited,
        "skipped_short_document_count": skipped_short,
        "retrieval": dict(retrieval),
        "dataset": {
            "name": dataset_spec.name,
            "repo_id": dataset_spec.repo_id,
            "config": dataset_spec.config,
            "split": dataset_spec.split,
            "revision": dataset_spec.revision,
            "row_count": dataset_length,
            "datasets_fingerprint": dataset_fingerprint,
        },
        "tokenizer": tokenizer_identity(tokenizer, model_id, model_revision),
        "selected_document_indices": [sample["document_index"] for sample in samples],
        "selected_token_hashes": [sample["token_sha256"] for sample in samples],
        "samples": samples,
    }
    artifact["artifact_sha256"] = artifact_sha256(artifact)
    validate_calibration_artifact(
        artifact,
        tokenizer=tokenizer,
        model_id=model_id,
        model_revision=model_revision,
        dataset_spec=dataset_spec,
        seed=seed,
        expected_size=size,
        expected_sequence_length=sequence_length,
    )
    return artifact


def _validate_requested_shape(size: int, sequence_length: int) -> None:
    if size <= 0 or sequence_length <= 0:
        raise CalibrationArtifactError("calibration size and sequence length must be positive")


def validate_calibration_artifact(
    artifact: Mapping[str, Any],
    *,
    tokenizer: Any,
    model_id: str,
    model_revision: str,
    dataset_spec: DatasetSpec,
    seed: int,
    expected_size: int = CALIBRATION_SIZE,
    expected_sequence_length: int = CALIBRATION_SEQUENCE_LENGTH,
) -> None:
    if artifact.get("schema_version") != CALIBRATION_SCHEMA_VERSION:
        raise CalibrationArtifactError("unsupported calibration artifact schema")
    if artifact.get("sampling_algorithm") != SAMPLING_ALGORITHM:
        raise CalibrationArtifactError("calibration artifact uses a different sampling algorithm")
    if int(artifact.get("seed", -1)) != seed:
        raise CalibrationArtifactError("calibration artifact seed does not match the requested seed")
    if int(artifact.get("sample_count", -1)) != expected_size:
        raise CalibrationArtifactError("calibration artifact does not contain the required sample count")
    if int(artifact.get("sequence_length", -1)) != expected_sequence_length:
        raise CalibrationArtifactError("calibration artifact does not use the required sequence length")

    expected_dataset = {
        "name": dataset_spec.name,
        "repo_id": dataset_spec.repo_id,
        "config": dataset_spec.config,
        "split": dataset_spec.split,
        "revision": dataset_spec.revision,
        "row_count": dataset_spec.row_count,
    }
    actual_dataset = artifact.get("dataset", {})
    for key, expected in expected_dataset.items():
        if actual_dataset.get(key) != expected:
            raise CalibrationArtifactError(f"calibration dataset {key} does not match: {actual_dataset.get(key)!r}")

    expected_tokenizer = tokenizer_identity(tokenizer, model_id, model_revision)
    actual_tokenizer = artifact.get("tokenizer", {})
    for key in ("model_id", "model_revision", "class", "vocab_sha256"):
        if actual_tokenizer.get(key) != expected_tokenizer[key]:
            raise CalibrationArtifactError(f"calibration tokenizer {key} does not match")

    samples = artifact.get("samples")
    if not isinstance(samples, list) or len(samples) != expected_size:
        raise CalibrationArtifactError("calibration samples are absent or incomplete")
    indices: list[int] = []
    hashes: list[str] = []
    for position, sample in enumerate(samples):
        ids = [int(value) for value in sample.get("input_ids", [])]
        if len(ids) != expected_sequence_length:
            raise CalibrationArtifactError(f"sample {position} is not exactly {expected_sequence_length} tokens")
        token_hash = token_ids_sha256(ids)
        if sample.get("token_sha256") != token_hash:
            raise CalibrationArtifactError(f"sample {position} token hash is invalid")
        text_ids = encode_text(
            tokenizer,
            str(sample.get("text", "")),
            truncation=True,
            max_length=expected_sequence_length,
        )
        if text_ids != ids:
            raise CalibrationArtifactError(
                f"sample {position} text no longer tokenizes to its recorded token IDs"
            )
        indices.append(int(sample["document_index"]))
        hashes.append(token_hash)
    if len(set(indices)) != len(indices):
        raise CalibrationArtifactError("calibration document indices are not unique")
    if artifact.get("selected_document_indices") != indices:
        raise CalibrationArtifactError("selected_document_indices does not match sample order")
    if artifact.get("selected_token_hashes") != hashes:
        raise CalibrationArtifactError("selected_token_hashes does not match sample order")
    if artifact.get("artifact_sha256") != artifact_sha256(artifact):
        raise CalibrationArtifactError("calibration artifact checksum is invalid")


def _strip_revision_from_shell_model(build_shell_model: Callable) -> Callable:
    """Wrap ``gptqmodel.utils.hf.build_shell_model`` so ``revision`` never reaches
    transformers' ``from_config``.

    Pinned-runtime workaround (gptqmodel 7.1.0 + transformers 5.13.0). When
    gptqmodel builds the meta-device shell model it forwards its model-init
    kwargs straight into ``AutoModelForCausalLM.from_config``; under
    transformers>=5, ``from_config`` passes unknown kwargs into the concrete
    model ``__init__``, which rejects hub-only kwargs like ``revision``
    (``TypeError: Qwen2ForCausalLM.__init__() got an unexpected keyword argument
    'revision'``). The pinned-revision weights are already resolved upstream
    (``loader.get_model_local_path``) before this seam, so ``revision`` is inert
    here — it governs hub fetches, not architecture, which comes from the config
    object. ``build_shell_model`` already strips ``device_map``/``_fast_init`` at
    this same boundary; this extends that set by exactly one key and changes
    nothing else. No released gptqmodel fixes this (7.2.0's ``utils/hf.py`` is
    byte-identical to 7.1.0's and carries algorithm-relevant deltas), so a
    version bump is not an option under the pinned image.
    """

    @functools.wraps(build_shell_model)
    def wrapper(loader, config, trust_remote_code=True, **model_init_kwargs):
        model_init_kwargs.pop("revision", None)
        return build_shell_model(
            loader, config, trust_remote_code=trust_remote_code, **model_init_kwargs
        )

    wrapper._flipeval_strips_revision = True  # idempotency guard
    return wrapper


def build_gptq(args: Any, tokenizer: Any, artifact: Mapping[str, Any]) -> None:
    try:
        from gptqmodel import GPTQConfig, GPTQModel
        from gptqmodel.utils import hf as gptq_hf
    except ImportError as exc:
        traceback.print_exception(exc)
        raise SystemExit("GPTQ quantization requires the pinned gptqmodel runtime.") from exc

    # loader.from_pretrained imports build_shell_model from this module at call
    # time, so patching the module attribute before GPTQModel.load takes effect.
    if not getattr(gptq_hf.build_shell_model, "_flipeval_strips_revision", False):
        gptq_hf.build_shell_model = _strip_revision_from_shell_model(gptq_hf.build_shell_model)

    quantize_config = GPTQConfig(bits=args.bits, group_size=128, desc_act=False)
    examples = [
        {"input_ids": list(sample["input_ids"]), "attention_mask": [1] * artifact["sequence_length"]}
        for sample in artifact["samples"]
    ]
    model = GPTQModel.load(
        args.model_id,
        quantize_config,
        revision=args.model_revision,
        trust_remote_code=args.trust_remote_code,
    )
    model.quantize(examples, batch_size=1)
    model.save(args.output_dir)
    tokenizer.save_pretrained(args.output_dir)


def build_awq(args: Any, tokenizer: Any, artifact: Mapping[str, Any]) -> None:
    try:
        from awq import AutoAWQForCausalLM
    except ImportError as exc:
        traceback.print_exception(exc)
        raise SystemExit("AWQ quantization requires the pinned autoawq runtime.") from exc

    model = AutoAWQForCausalLM.from_pretrained(
        args.model_id,
        revision=args.model_revision,
        trust_remote_code=args.trust_remote_code,
    )
    quant_config = {"zero_point": True, "q_group_size": 128, "w_bit": args.bits, "version": "GEMM"}
    model.quantize(
        tokenizer,
        quant_config=quant_config,
        # AutoAWQ's pinned get_calib_dataset helper accepts pre-tokenized
        # list[list[int]] input. Passing the artifact IDs avoids text stripping,
        # special-token defaults, and a second tokenizer code path.
        calib_data=[list(sample["input_ids"]) for sample in artifact["samples"]],
        max_calib_samples=int(artifact["sample_count"]),
        max_calib_seq_len=int(artifact["sequence_length"]),
    )
    model.save_quantized(args.output_dir)
    tokenizer.save_pretrained(args.output_dir)


def write_calibration_receipt(path: Path, artifact: Mapping[str, Any], args: Any) -> None:
    receipt = {
        "schema_version": 1,
        "artifact_sha256": artifact["artifact_sha256"],
        "model_id": args.model_id,
        "model_revision": args.model_revision,
        "method": args.method,
        "bits": args.bits,
        "dataset": deepcopy(artifact["dataset"]),
        "tokenizer": deepcopy(artifact["tokenizer"]),
        "seed": artifact["seed"],
        "sample_count": artifact["sample_count"],
        "sequence_length": artifact["sequence_length"],
        "selected_document_indices": list(artifact["selected_document_indices"]),
        "selected_token_hashes": list(artifact["selected_token_hashes"]),
    }
    write_json_atomic(path, receipt)


def tokenizer_identity(tokenizer: Any, model_id: str, model_revision: str) -> dict[str, Any]:
    try:
        vocab = tokenizer.get_vocab()
    except (AttributeError, NotImplementedError):
        vocab = None
    if vocab is None:
        vocab_payload = {"vocab_size": int(getattr(tokenizer, "vocab_size", -1))}
    else:
        vocab_payload = sorted((str(token), int(index)) for token, index in vocab.items())
    vocab_sha = hashlib.sha256(canonical_json(vocab_payload)).hexdigest()
    return {
        "model_id": model_id,
        "model_revision": model_revision,
        "class": tokenizer.__class__.__name__,
        "name_or_path": str(getattr(tokenizer, "name_or_path", model_id)),
        "vocab_size": int(getattr(tokenizer, "vocab_size", len(vocab) if vocab is not None else -1)),
        "vocab_sha256": vocab_sha,
    }


def encode_text(
    tokenizer: Any,
    text: str,
    *,
    truncation: bool,
    max_length: int | None = None,
) -> list[int]:
    kwargs: dict[str, Any] = {"add_special_tokens": False, "truncation": truncation}
    if max_length is not None:
        kwargs["max_length"] = max_length
    encoded = tokenizer(text, **kwargs)
    values = encoded["input_ids"]
    if values and isinstance(values[0], list):
        if len(values) != 1:
            raise CalibrationArtifactError("tokenizer returned an unexpected batch")
        values = values[0]
    return [int(value) for value in values]


def token_ids_sha256(token_ids: Sequence[int]) -> str:
    return hashlib.sha256(canonical_json([int(value) for value in token_ids])).hexdigest()


def artifact_sha256(artifact: Mapping[str, Any]) -> str:
    payload = dict(artifact)
    payload.pop("artifact_sha256", None)
    return hashlib.sha256(canonical_json(payload)).hexdigest()


def canonical_json(value: Any) -> bytes:
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8")


def read_json(path: Path) -> dict[str, Any]:
    with path.open("r", encoding="utf-8") as stream:
        value = json.load(stream)
    if not isinstance(value, dict):
        raise CalibrationArtifactError(f"expected a JSON object in {path}")
    return value


def write_json_atomic(path: Path, value: Mapping[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
    with temporary.open("w", encoding="utf-8") as stream:
        json.dump(value, stream, indent=2, ensure_ascii=True)
        stream.write("\n")
    os.replace(temporary, path)


if __name__ == "__main__":
    main()