File size: 3,346 Bytes
b838b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Small diagnostic QA evaluation, not a general capability benchmark."""
import argparse
import json
import os
from pathlib import Path
os.environ.setdefault("HF_HUB_OFFLINE", "1")
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from terra.common import batch, detect_language, encode_pairs, prompt, read_pairs


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--model", default="checkpoints/terra-2.5-171m-exact")
    parser.add_argument("--data", default="data/multilingual/validation.jsonl")
    parser.add_argument("--output", default="artifacts/evaluation.json")
    args = parser.parse_args()
    torch.set_num_threads(2)
    model = AutoModelForCausalLM.from_pretrained(args.model, local_files_only=True).eval()
    tokenizer = AutoTokenizer.from_pretrained(args.model, local_files_only=True)
    pairs = read_pairs(args.data)
    rows = encode_pairs(pairs, tokenizer, model.config.n_positions)
    samples, total, tokens = [], 0.0, 0
    groups = {}
    with torch.inference_mode():
        for pair, row in zip(pairs, rows):
            inputs = batch([row], tokenizer.pad_token_id)
            n = (inputs["labels"][:, 1:] != -100).sum().item()
            loss = model(**inputs).loss.item()
            total += loss * n
            tokens += n
            language = pair.get("language") or detect_language(pair["question"])
            group = groups.setdefault(language, {"examples": 0, "tokens": 0, "loss_sum": 0.0, "matches": 0})
            group["examples"] += 1
            group["tokens"] += n
            group["loss_sum"] += loss * n
            inputs = tokenizer(prompt(pair["question"], language), return_tensors="pt")
            length = inputs.input_ids.shape[1]
            output = model.generate(**inputs, max_new_tokens=min(128, model.config.n_positions - length),
                                    do_sample=False, use_cache=True, pad_token_id=tokenizer.pad_token_id,
                                    eos_token_id=tokenizer.eos_token_id)
            answer = tokenizer.decode(output[0, length:], skip_special_tokens=True).strip()
            match = answer == pair["answer"].strip()
            group["matches"] += int(match)
            samples.append({**pair, "language": language, "generated": answer, "exact_match": match})
    result = {"model": args.model, "dataset": args.data, "examples": len(pairs),
              "parameters": sum(p.numel() for p in model.parameters()),
              "answer_cross_entropy": total / tokens,
              "exact_match": sum(p["exact_match"] for p in samples) / len(samples),
              "by_language": {lang: {"examples": g["examples"], "answer_cross_entropy": g["loss_sum"] / g["tokens"],
                                      "exact_matches": g["matches"], "exact_match": g["matches"] / g["examples"]}
                              for lang, g in groups.items()},
              "note": "Tiny synthetic diagnostic set; not a general capability benchmark.", "samples": samples}
    path = Path(args.output)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({k: v for k, v in result.items() if k != "samples"}, ensure_ascii=False))


if __name__ == "__main__":
    main()