File size: 9,602 Bytes
4df9b63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6ae5c2
4df9b63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6ae5c2
 
 
 
 
 
 
4df9b63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6ae5c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4df9b63
 
 
 
 
 
 
 
 
 
 
b6ae5c2
 
 
4df9b63
b6ae5c2
4df9b63
 
 
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
import json
from pathlib import Path

import numpy as np

from . import MODEL_VERSION
from .artifacts import sha256
from .settings import TEMPLATE_VERSION


def softmax(logits):
    logits = np.asarray(logits, dtype=np.float64)
    e = np.exp(logits - logits.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)


def metrics(probabilities, gold, ordinal=False, positive_label=None):
    p = np.asarray(probabilities, dtype=np.float64)
    y = np.asarray(gold, dtype=int)
    if len(y) == 0 or p.ndim != 2 or len(p) != len(y) or not np.isfinite(p).all():
        raise ValueError("Немає коректних даних для метрик.")
    prediction = p.argmax(axis=1)
    correct = prediction == y
    confidence = p.max(axis=1)
    nll = -np.log(np.clip(p[np.arange(len(y)), y], 1e-12, 1)).mean()
    target = np.zeros_like(p)
    target[np.arange(len(y)), y] = 1
    f1s = []
    for label in sorted(set(y) | set(prediction)):
        tp = ((prediction == label) & (y == label)).sum()
        denominator = (prediction == label).sum() + (y == label).sum()
        f1s.append(float(2 * tp / denominator) if denominator else 0.)
    ece, reliability = 0., []
    for b in range(10):
        selected = np.minimum((confidence * 10).astype(int), 9) == b
        count = int(selected.sum())
        accuracy = float(correct[selected].mean()) if count else None
        conf = float(confidence[selected].mean()) if count else None
        if count:
            ece += count / len(y) * abs(accuracy - conf)
        reliability.append({"left": b / 10, "right": (b + 1) / 10, "count": count,
                            "accuracy": accuracy, "confidence": conf})
    result = {"n": len(y), "accuracy": float(correct.mean()), "macro_f1": float(np.mean(f1s)),
              "nll": float(nll), "brier": float(np.square(p - target).sum(axis=1).mean()),
              "ece": float(ece), "reliability": reliability}
    if ordinal:
        result["mae"] = float(np.abs(p @ np.arange(p.shape[1]) - y).mean())
    if positive_label is not None:
        actual=y==positive_label;predicted=prediction==positive_label
        tp=int((actual&predicted).sum());fp=int((~actual&predicted).sum())
        fn=int((actual&~predicted).sum());tn=int((~actual&~predicted).sum())
        result.update(positive_recall=tp/(tp+fn) if tp+fn else 0.,
            positive_precision=tp/(tp+fp) if tp+fp else 0.,
            positive_support=tp+fn,confusion=[[tn,fp],[fn,tp]])
    return result


def fit_head(x, y, mask, val_x, val_y, val_mask, epochs=50, learning_rate=.001, patience=5, batch_size=128, seed=42):
    import torch

    if len(y) == 0 or len(val_y) == 0:
        raise ValueError("Потрібні непорожні train і validation.")
    torch.set_num_threads(2)
    torch.manual_seed(seed)
    tensor = lambda a, dtype: torch.as_tensor(a, dtype=dtype)
    x, y, mask = tensor(x, torch.float32), tensor(y, torch.long), tensor(mask, torch.bool)
    vx, vy, vm = tensor(val_x, torch.float32), tensor(val_y, torch.long), tensor(val_mask, torch.bool)
    weight = torch.nn.Parameter(torch.zeros(x.shape[-1], dtype=torch.float32))
    optimizer = torch.optim.AdamW([weight], lr=learning_rate, weight_decay=.01)
    best, best_weight, stale, history = float("inf"), None, 0, []
    for epoch in range(epochs):
        permutation = torch.randperm(len(y))
        total = 0.
        for indices in permutation.split(batch_size):
            optimizer.zero_grad(set_to_none=True)
            logits = (x[indices] @ weight).masked_fill(~mask[indices], -torch.inf)
            loss = torch.nn.functional.cross_entropy(logits, y[indices])
            loss.backward()
            optimizer.step()
            total += loss.item() * len(indices)
        with torch.no_grad():
            val_loss = torch.nn.functional.cross_entropy((vx @ weight).masked_fill(~vm, -torch.inf), vy).item()
        if not np.isfinite(val_loss):
            raise ValueError("Навчання повернуло нескінченну помилку.")
        history.append({"epoch": epoch + 1, "train_nll": total / len(y), "validation_nll": val_loss})
        if val_loss < best - 1e-6:
            best, best_weight, stale = val_loss, weight.detach().numpy().copy(), 0
        else:
            stale += 1
            if stale >= patience:
                break
    return best_weight, history


def fit_temperature(logits, gold):
    logits = np.asarray(logits, dtype=np.float64)
    y = np.asarray(gold, dtype=int)
    if len(y) == 0:
        raise ValueError("Немає даних калібрування.")
    def nll(t):
        return -np.log(np.clip(softmax(logits / t)[np.arange(len(y)), y], 1e-12, 1)).mean()
    candidates = np.r_[1., np.exp(np.linspace(np.log(.05), np.log(50.), 400))]
    scores = [nll(t) for t in candidates]
    return float(candidates[int(np.argmin(scores))])


def balanced_candidate_weights(rows):
    """Equal mass per type, candidate count and gold class; IDs are unused."""
    from collections import Counter
    if not rows:
        raise ValueError('Порожня навчальна вибірка.')
    keys = [(r['type'], r['candidates'], r['gold']) for r in rows]
    counts = Counter(keys)
    classes = Counter((kind, count) for kind, count, gold in counts)
    variants = Counter(kind for kind, count in classes)
    weights = np.array([1 / (counts[k] * classes[k[:2]] * variants[k[0]]) for k in keys])
    return weights / weights.sum()


def fit_logistic_head(x, y, mask, val_x, val_y, val_mask, weights, val_weights,
                      max_iter=300, regularization=1e-5, patience=8):
    """Conditioned convex fit. Return raw-space w; inference stays w^T mean(H)."""
    import torch
    torch.set_num_threads(2)
    x = np.asarray(x, dtype=np.float64)
    mask = np.asarray(mask, dtype=bool)
    weights, val_weights = np.asarray(weights), np.asarray(val_weights)
    if len(y) == 0 or len(val_y) == 0 or not mask.any(1).all():
        raise ValueError('Потрібні непорожні вибірки й варіанти.')
    if len(weights) != len(y) or len(val_weights) != len(val_y) or not np.isfinite(weights).all() or not np.isfinite(val_weights).all() or (weights <= 0).any() or (val_weights <= 0).any():
        raise ValueError('Некоректні ваги прикладів.')
    # Subtract the SAME vector from every candidate in a question. This is
    # exactly softmax invariant. Padding contributes neither mean nor scale.
    center = (x * mask[:, :, None]).sum(1, keepdims=True) / mask.sum(1)[:, None, None]
    centered = np.where(mask[:, :, None], x - center, 0.)
    scale = np.maximum(np.sqrt(np.square(centered).sum((0, 1)) / mask.sum()), 1e-6)
    xt, yt, mt = torch.tensor(centered / scale), torch.tensor(y), torch.tensor(mask)
    wt = torch.tensor(weights / weights.sum())
    theta = torch.nn.Parameter(torch.zeros(x.shape[-1], dtype=torch.float64))
    optimizer = torch.optim.LBFGS([theta], lr=1., max_iter=10, history_size=50,
        line_search_fn='strong_wolfe', tolerance_grad=1e-7)
    def closure():
        optimizer.zero_grad()
        logits = (xt @ theta).masked_fill(~mt, -torch.inf)
        loss = (torch.nn.functional.cross_entropy(logits, yt, reduction='none') * wt).sum()
        loss = loss + regularization * theta.square().sum()
        loss.backward()
        return loss
    best, best_weight, stale, history = float('inf'), None, 0, []
    for step in range((max_iter + 9) // 10):
        optimizer.step(closure)
        weight = (theta.detach().numpy() / scale).astype(np.float32)
        logits = np.asarray(val_x, dtype=np.float64) @ weight.astype(np.float64)
        logits[~np.asarray(val_mask, dtype=bool)] = -np.inf
        losses = -np.log(np.clip(softmax(logits)[np.arange(len(val_y)), val_y], 1e-12, 1))
        val_loss = float(np.average(losses, weights=val_weights))
        if not np.isfinite(val_loss) or not np.isfinite(weight).all():
            raise ValueError('Некоректний результат оптимізації.')
        history.append({'epoch': (step + 1) * 10, 'validation_nll': val_loss})
        if val_loss < best - 1e-6:
            best, best_weight, stale = val_loss, weight.copy(), 0
        else:
            stale += 1
            if stale >= patience:
                break
    return best_weight, history


def save_bundle(path, weight, temperatures, manifest, result):
    from safetensors.numpy import save_file

    path = Path(path)
    path.mkdir(parents=True, exist_ok=True)
    save_file({"weight": np.ascontiguousarray(weight, dtype=np.float32)}, str(path / "head.safetensors"))
    fitted = manifest.get("stage") in {"calibrated", "evaluated"}
    (path / "calibration.json").write_text(json.dumps({"method": "per-type temperature scaling" if fitted else "none",
        "temperatures": temperatures, "fitted_on": "calibration" if fitted else None,
        "status": "fitted" if fitted else "unfitted"}, indent=2), encoding="utf-8")
    (path / "metrics.json").write_text(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False), encoding="utf-8")
    files = ['head.safetensors','calibration.json','metrics.json']
    if manifest.get('encoder_delta'):
        files.append('encoder_delta.safetensors')
    manifest = {**manifest, "format_version": 1, "model_version": MODEL_VERSION, "template_version": TEMPLATE_VERSION,
                "files": {name: sha256(path / name) for name in files}}
    (path / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8")
    return manifest