File size: 7,420 Bytes
f310a09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compare baseline and candidate causal-LM likelihood on a frozen multilingual test corpus."""

from __future__ import annotations

import argparse
import gc
import json
import math
from pathlib import Path
from typing import Any

from training.nlp.common import iter_jsonl, read_json, sha256_file
from training.nlp.run_stage import task_data_files, validate_prepared_row


def evaluate_model(
    model_source: str,
    revision: str | None,
    local_only: bool,
    data_files: list[Path],
    sequence_length: int,
    device: str,
    device_map: str | None,
) -> dict[str, Any]:
    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer

    tokenizer = AutoTokenizer.from_pretrained(
        model_source,
        revision=revision,
        trust_remote_code=False,
        local_files_only=local_only,
    )
    kwargs: dict[str, Any] = {
        "revision": revision,
        "trust_remote_code": False,
        "use_safetensors": True,
        "torch_dtype": "auto",
        "local_files_only": local_only,
    }
    if device_map:
        kwargs["device_map"] = device_map
    model = AutoModelForCausalLM.from_pretrained(model_source, **kwargs)
    if not device_map:
        model.to(device)
    model.eval()
    totals: dict[str, dict[str, float | int]] = {}
    with torch.inference_mode():
        for path in data_files:
            for line_number, row in iter_jsonl(path):
                validate_prepared_row(row, "evaluation", f"{path.name}:{line_number}")
                text = row["text"]
                encoded = tokenizer(text, add_special_tokens=False, return_tensors="pt")["input_ids"]
                if tokenizer.eos_token_id is not None:
                    eos = torch.tensor([[tokenizer.eos_token_id]], dtype=encoded.dtype)
                    encoded = torch.cat((encoded, eos), dim=1)
                if encoded.shape[1] < 2:
                    continue
                if encoded.shape[1] > sequence_length:
                    raise ValueError(
                        f"{path.name}:{line_number} exceeds sequence_length={sequence_length}; prepare shorter evaluation records"
                    )
                input_device = model.get_input_embeddings().weight.device if device_map else device
                encoded = encoded.to(input_device)
                loss = model(input_ids=encoded, labels=encoded).loss
                count = int(encoded.shape[1] - 1)
                row_total = totals.setdefault(row["language"], {
                    "examples": 0, "utf8_bytes": 0, "predicted_tokens": 0, "negative_log_likelihood_nats": 0.0,
                })
                row_total["examples"] += 1
                row_total["utf8_bytes"] += len(text.encode("utf-8"))
                row_total["predicted_tokens"] += count
                row_total["negative_log_likelihood_nats"] += float(loss) * count

    metrics = {}
    for language, totals_for_language in sorted(totals.items()):
        byte_count = int(totals_for_language["utf8_bytes"])
        nll = float(totals_for_language["negative_log_likelihood_nats"])
        metrics[language] = {
            **totals_for_language,
            "bits_per_byte": nll / (byte_count * math.log(2)) if byte_count else None,
            "nats_per_token": nll / int(totals_for_language["predicted_tokens"]),
        }
    del model, tokenizer
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
    return metrics


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--manifest", type=Path, required=True, help="Frozen evaluation-purpose manifest, test split only")
    parser.add_argument("--candidate", type=Path, required=True, help="Locally saved model candidate")
    parser.add_argument("--baseline-id", required=True)
    parser.add_argument("--baseline-revision", required=True, help="Full pinned model commit")
    parser.add_argument("--sequence-length", type=int, default=2048)
    parser.add_argument("--device", default="auto", help="Model device when --device-map is omitted")
    parser.add_argument("--device-map", help="Optional Transformers device map, such as auto")
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    if args.sequence_length < 2:
        raise ValueError("sequence-length must be at least 2")
    device = args.device
    if device == "auto":
        import torch

        device = "cuda" if torch.cuda.is_available() else "cpu"
    if len(args.baseline_revision) != 40 or any(char not in "0123456789abcdef" for char in args.baseline_revision):
        raise ValueError("baseline-revision must be a full 40-character commit SHA")
    manifest_path = args.manifest.resolve()
    manifest = read_json(manifest_path)
    if manifest.get("schema_version") != 1 or manifest.get("purpose") != "evaluation":
        raise ValueError("evaluation requires a prepared schema-v1 evaluation manifest")
    if int(manifest.get("splits", {}).get("test", {}).get("rows", 0)) < 1:
        raise ValueError("frozen evaluation test split is empty")
    paths = task_data_files(manifest_path, manifest, "test")
    for entry, path in zip(manifest["splits"]["test"]["files"], paths):
        if not entry.get("sha256") or sha256_file(path) != entry["sha256"]:
            raise ValueError(f"frozen evaluation shard hash mismatch: {path.name}")
    candidate = args.candidate.resolve()
    if not candidate.is_dir() or not (candidate / "config.json").is_file():
        raise ValueError("candidate must be a local Transformers model directory with config.json")
    output = args.output.resolve()
    if output.exists():
        raise FileExistsError(f"refusing to overwrite evaluation report: {output}")

    baseline_metrics = evaluate_model(
        args.baseline_id, args.baseline_revision, False, paths, args.sequence_length, device, args.device_map
    )
    candidate_metrics = evaluate_model(
        str(candidate), None, True, paths, args.sequence_length, device, args.device_map
    )
    candidate_run = candidate / "candidate-run.json"
    report = {
        "schema_version": 1,
        "evaluation": "frozen multilingual causal-LM likelihood comparison",
        "evaluation_manifest": str(manifest_path),
        "evaluation_manifest_sha256": sha256_file(manifest_path),
        "baseline": {"model_id": args.baseline_id, "revision": args.baseline_revision, "metrics_by_language": baseline_metrics},
        "candidate": {
            "path": str(candidate),
            "run_manifest_sha256": sha256_file(candidate_run) if candidate_run.is_file() else None,
            "metrics_by_language": candidate_metrics,
        },
        "limitations": [
            "bits per byte is a language-model likelihood diagnostic, not a measure of helpfulness, factuality, reasoning, safety, or generation quality",
            "Arabic and other language scores are meaningful only when the frozen test corpus contains sufficient independently reviewed examples",
            "this report cannot promote or publish a candidate",
        ],
    }
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print(json.dumps({"output": str(output), "languages": sorted(set(baseline_metrics) & set(candidate_metrics))}))


if __name__ == "__main__":
    main()