File size: 9,342 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
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
# SPDX-License-Identifier: Apache-2.0
"""From scorer logits to typed answers: temperature scaling, softmax, the answer fields, usage and the optional
``min_confidence`` abstention gate -- the response half of laya's classic runtime (0.5.8 semantics, this package's
code).  Pure numpy; float32 like the official decoder so rounded outputs match."""
from __future__ import annotations

import math
from typing import Any, Dict, List, Optional, Sequence, Union

import numpy as np

from .text import QTYPE_NAMES, Question, QuestionError, Row, render_criterion

TEMP_MIN, TEMP_MAX = 0.5, 5.0
BUCKET_QTYPES = ("choice", "score", "noul")
BUCKET_SIZES = ("2", "3-5", "6-10", "11+")
MODEL_NAME = "laya-rl-agent"


def size_bucket(k: int) -> str:
    return "2" if k <= 2 else "3-5" if k <= 5 else "6-10" if k <= 10 else "11+"


def temp_bucket(qtype: int, k: int) -> str:
    return "%s:%s" % (QTYPE_NAMES[int(qtype)], size_bucket(k))


def clamp_temperature(t: Any) -> float:
    if isinstance(t, bool):
        return 1.0
    try:
        t = float(t)
    except (TypeError, ValueError, OverflowError):
        return 1.0
    if not math.isfinite(t):
        return 1.0
    return min(TEMP_MAX, max(TEMP_MIN, t))


class Calibration:
    """Per-type temperatures + per-(type, option-count) temperatures, clamped to [0.5, 5] like the official runtime,
    plus optional per-language overrides (``lang_temperatures``)."""

    def __init__(self, temperature: Sequence[float], by_options: Optional[Dict[str, float]] = None,
                 lang: Optional[Dict[str, dict]] = None):
        if not isinstance(temperature, (list, tuple)) or len(temperature) != 3:
            raise ValueError("temperature must be a list of 3 floats, got %r" % (temperature,))
        self.raw = list(temperature)
        self.raw_by_options = dict(by_options or {})
        self.temperature = [clamp_temperature(t) for t in temperature]
        self.by_options = {k: clamp_temperature(v) for k, v in (by_options or {}).items()}
        self.lang: Dict[str, dict] = {}
        for code, cfg in (lang or {}).items():
            if not isinstance(code, str):
                raise ValueError("language override keys must be strings, got %r" % (code,))
            cfg = cfg or {}
            if not isinstance(cfg, dict):
                raise ValueError("language override %r must be a mapping" % (code,))
            t = cfg.get("temperature")
            t = self.raw if t is None else t
            if not isinstance(t, (list, tuple)) or len(t) != 3:
                raise ValueError("language override %r temperature must be a list of 3 floats" % (code,))
            tbo = cfg.get("temperature_by_options") or {}
            if not isinstance(tbo, dict):
                raise ValueError("language override %r temperature_by_options must be a mapping" % (code,))
            self.lang[code.split("-")[0].lower()] = {"temperature": [clamp_temperature(x) for x in t],
                                                     "by_options": {k: clamp_temperature(v) for k, v in tbo.items()}}

    def scale(self, qtype: int, k: int, lang: Optional[str] = None) -> float:
        b = temp_bucket(qtype, k)
        if lang:
            l = self.lang.get(lang.split("-")[0].lower())
            if l is not None:
                return l["by_options"].get(b, l["temperature"][qtype])
        return self.by_options.get(b, self.temperature[qtype])

    def describe(self) -> dict:
        return {"temperature": self.temperature, "temperature_by_options": self.by_options,
                "lang_temperatures": sorted(self.lang)}


def confidence_from_probs(p: np.ndarray, k: int) -> float:
    if k < 2:
        return 1.0
    pk = p[:k]
    ent = -float((pk * np.log(np.clip(pk, 1e-12, 1.0))).sum())
    s = 1.0 - ent / math.log(k)
    return 0.0 if s < 0.0 else (1.0 if s > 1.0 else s)


def answer_confidence(p: np.ndarray, k: int) -> float:
    if k < 1:
        return 1.0
    v = float(p[:k].max())
    return 0.0 if v < 0.0 else (1.0 if v > 1.0 else v)


def probs(logits_row: np.ndarray, t_scale: float, order: Optional[List[int]]) -> np.ndarray:
    """Temperature-scaled softmax in float32 (the official decoder's arithmetic), back in option order."""
    z = np.asarray(logits_row, dtype=np.float32) / t_scale
    p = np.exp(z - z.max())
    p /= p.sum()
    if order is not None and len(order) == len(p):
        q = np.empty_like(p)
        q[np.asarray(order, dtype=int)] = p
        p = q
    return p


def answer(q: Question, logits_row: np.ndarray, act0: float, cal: Calibration, lang: Optional[str] = None) -> dict:
    k = len(logits_row)
    p = probs(logits_row, cal.scale(q.qtype, k, lang), q.order)
    ac = round(answer_confidence(p, k), 4)
    action = {"act_probability": round(float(act0), 4)}
    if q.t == "choice":
        keys = list(q.crit.keys())
        return {"type": "choice", "choice": keys[int(p.argmax())],
                "probabilities": {str(kk): round(float(v), 4) for kk, v in zip(keys, p)},
                "confidence": round(confidence_from_probs(p, k), 4), "answer_confidence": ac, "action": action}
    if q.t == "score":
        return {"type": "score", "score": round(float((np.arange(k) * p).sum()), 4),
                "legend": {str(i): render_criterion(c) for i, c in enumerate(q.crit)},
                "probabilities": {str(i): round(float(v), 4) for i, v in enumerate(p)},
                "confidence": round(confidence_from_probs(p, k), 4), "answer_confidence": ac, "action": action}
    p1 = float(p[1])
    return {"type": "noul", "noul": round(p1, 4), "confidence": round(max(p1, 1.0 - p1), 4),
            "answer_confidence": ac, "action": action}


def usage(qs: Sequence[Question], rows: Sequence[Row]) -> dict:
    dropped = max(r.state_tokens - r.state_used for r in rows)
    u = {"input_tokens": int(sum(len(r.ids) for r in rows)), "output_tokens": 0,
         "state_tokens": rows[0].state_tokens, "state_tokens_dropped": dropped, "truncated": dropped > 0,
         "truncated_questions": [q.qid for q, r in zip(qs, rows) if r.truncated]}
    collapsed = {q.qid: {"total": r.n_options, "distinct": r.options_distinct, "tokens_per_option": r.tokens_per_option}
                 for q, r in zip(qs, rows) if r.options_distinct < r.n_options}
    if collapsed:
        u["options"] = collapsed
    return u


def result(qs: Sequence[Question], rows: Sequence[Row], logits: Sequence[np.ndarray], act0: Sequence[float],
           cal: Calibration, lang: Optional[str] = None) -> dict:
    """One state's response (``logits[j]``: question j's K raw scorer logits, slot order)."""
    answers = {q.qid: answer(q, l, a, cal, lang) for q, l, a in zip(qs, logits, act0)}
    return {"model": MODEL_NAME, "answers": answers, "usage": usage(qs, rows)}


# ----------------------------------------------------------------------------- min_confidence gate (opt-in)
def _finite(v: Any) -> bool:
    if isinstance(v, bool) or not isinstance(v, (int, float)):
        return False
    try:
        return math.isfinite(v)
    except OverflowError:
        return False


def check_min_confidence(v: Any) -> Union[float, Dict[str, float]]:
    def one(x):
        if not _finite(x) or x < 0.0 or x > 1.0:
            raise QuestionError("min_confidence must be a float in [0.0, 1.0], got %r" % (x,))
        return float(x)

    if isinstance(v, dict):
        if not v:
            raise QuestionError("a min_confidence map must be a non-empty dict of bucket -> float, got %r" % (v,))
        allowed = {"%s:%s" % (t, s) for t in BUCKET_QTYPES for s in BUCKET_SIZES} | {"default"}
        out = {}
        for k, x in v.items():
            if not isinstance(k, str) or k not in allowed:
                raise QuestionError("min_confidence map keys must be a bucket like 'choice:3-5' or 'default', got %r"
                                    % (k,))
            out[k] = one(x)
        return out
    return one(v)


def _bucket_of(a: dict) -> Optional[str]:
    qt = a.get("type")
    if qt not in BUCKET_QTYPES:
        return None
    pr = a.get("probabilities")
    k = len(pr) if isinstance(pr, dict) and pr else (2 if qt == "noul" else None)
    return None if k is None else "%s:%s" % (qt, size_bucket(k))


def _gate_value(a: dict) -> Optional[float]:
    for key in ("answer_confidence", "confidence"):
        if _finite(a.get(key)):
            return float(a[key])
    return None


def apply_gate(results: List[dict], min_confidence) -> None:
    """``low_confidence`` / ``abstention`` / ``abstention_threshold`` on every answer when a gate is set."""
    if min_confidence is None:
        return
    is_map = isinstance(min_confidence, dict)
    for res in results:
        for a in res.get("answers", {}).values():
            if is_map:
                b = _bucket_of(a)
                thr = min_confidence[b] if b is not None and b in min_confidence else min_confidence.get("default", 0.0)
            else:
                thr = min_confidence
            v = _gate_value(a)
            if v is not None and v < thr:
                a["low_confidence"] = True
                a["abstention"] = "abstained"
            else:
                a.pop("low_confidence", None)
                a["abstention"] = "passed" if v is not None else "unevaluated"
            a["abstention_threshold"] = float(thr)