File size: 4,506 Bytes
f882f26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Host tests (no device, no model weights needed beyond the tokenizer): gates G0 / G1-decode / G4-host.

* G0: the token rows (ids, [MASK] markers) of every golden case are identical to the official runtime's batch.
* decode: feeding the OFFICIAL raw logits / action probabilities through this package's decoder reproduces the
  official response dict exactly (answers incl. rounding, usage, the min_confidence gate fields).

    python -m pytest tt_laya/tests/test_host_text.py -q
"""
from __future__ import annotations

import glob
import json
import os

import numpy as np
import pytest

ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", ".."))
GOLD = os.environ.get("LAYA_GOLDEN_DIR") or os.path.join(ROOT, "assets", "laya", "golden")
CKPT = os.environ.get("LAYA_WEIGHTS_ROOT") or os.path.join(ROOT, "assets", "laya", "ckpt")


def _cases():
    out = []
    for prof in ("english", "typed-decisions", "multilingual"):
        for p in sorted(glob.glob(os.path.join(GOLD, prof, "*.json"))):
            if not os.path.basename(p).startswith("_"):
                out.append((prof, os.path.basename(p)[:-5]))
    return out


CASES = _cases()


@pytest.fixture(scope="module")
def toks():
    from tt_laya import text as T
    from tt_laya import weights as Wt

    out = {}
    for prof in ("english", "typed-decisions", "multilingual"):
        d = os.path.join(CKPT, prof)
        if os.path.isdir(os.path.join(d, "tokenizer")):
            ck = Wt.load_checkpoint(prof, root=d)
            out[prof] = (ck, T.Tokenizer(os.path.join(d, "tokenizer")))
    return out


@pytest.mark.skipif(not CASES, reason="no goldens")
@pytest.mark.parametrize("prof,case", CASES)
def test_rows_and_decode_match_official(prof, case, toks):
    from tt_laya import decode as Dc
    from tt_laya import text as T

    if prof not in toks:
        pytest.skip("no tokenizer for " + prof)
    ck, tok = toks[prof]
    doc = json.load(open(os.path.join(GOLD, prof, case + ".json")))
    z = np.load(os.path.join(GOLD, prof, case + ".npz"))
    kw = doc["kwargs"]
    qs = T.normalise_questions(doc["questions"])
    rows = T.build_rows(tok, doc["state"], qs, kw.get("max_len", ck.max_len), kw.get("head_max_len", ck.head_max_len))
    # G0
    assert len(rows) == z["input_ids"].shape[0]
    for i, r in enumerate(rows):
        n = int(z["attention_mask"][i].sum())
        assert r.ids == z["input_ids"][i, :n].tolist(), (i, len(r.ids), n)
        K = int(z["marker_mask"][i].sum())
        assert r.markers == z["marker_pos"][i, :K].tolist()
        assert r.qtype == int(z["qtype"][i])
    # decode of the official logits == the official response
    cal = Dc.Calibration(ck.cfg["temperature"], ck.cfg.get("temperature_by_options"))
    L = [z["logits_fp32"][i, :len(r.markers)] for i, r in enumerate(rows)]
    res = Dc.result(qs, rows, L, [float(a[0]) for a in z["act_fp32"]], cal)
    mc = kw.get("min_confidence")
    Dc.apply_gate([res], Dc.check_min_confidence(mc) if mc is not None else None)
    off = doc["official_fp32"]
    assert res["usage"] == off["usage"]
    assert res["answers"] == off["answers"]


def test_question_validation_messages():
    from tt_laya import text as T

    bad = [
        ({"type": "maybe", "instructions": "x"}, "unknown type"),
        ({"type": "choice", "instructions": "x"}, "criteria"),
        ({"type": "choice", "instructions": "x", "criteria": ["a", "a"]}, "repeats"),
        ({"type": "score", "instructions": "x", "criteria": []}, "at least one level"),
        ({"type": "noul", "instructions": "x", "criteria": {"yes": "y"}}, "true'/'false"),
        ({"type": "noul", "instructions": ""}, "must not be empty"),
        ({"type": "choice", "instructions": "x", "criteria": ["a", "b"], "option_order": [0, 0]}, "permutation"),
        ({"type": "score", "instructions": "x", "criteria": ["a"], "labels": {"false": "n", "true": "y"}}, "labels"),
    ]
    for q, msg in bad:
        with pytest.raises(T.QuestionError, match=msg):
            T.normalise_question("q", q)


def test_min_confidence_validation():
    from tt_laya import decode as Dc
    from tt_laya.text import QuestionError

    assert Dc.check_min_confidence(0.5) == 0.5
    assert Dc.check_min_confidence({"noul:2": 0.7, "default": 0.1}) == {"noul:2": 0.7, "default": 0.1}
    for bad in (1.5, -0.1, True, "x", {"noul:3": 0.5}, {}):
        with pytest.raises(QuestionError):
            Dc.check_min_confidence(bad)