File size: 2,624 Bytes
4df9b63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6ae5c2
 
 
 
 
 
 
 
 
 
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
import json

import numpy as np
import pytest

from decision_model.learning import fit_head, fit_temperature, softmax, metrics, save_bundle
from decision_model.artifacts import verify_bundle


def separable():
    # Contextual representations with the correct candidate on the first axis.
    rng = np.random.default_rng(42)
    x = rng.normal(0, .04, (40, 3, 2)).astype(np.float32)
    y = np.arange(40) % 3
    for i, gold in enumerate(y):
        x[i, gold, 0] += 4
    return x, y, np.ones((40, 3), dtype=bool)


def test_head_learns_and_padded_candidates_are_excluded():
    x, y, mask = separable()
    x = np.pad(x, ((0, 0), (0, 1), (0, 0)), constant_values=1e5)
    mask = np.pad(mask, ((0, 0), (0, 1)), constant_values=False)
    weight, history = fit_head(x, y, mask, x, y, mask, epochs=50, learning_rate=.03)
    logits = np.einsum('nkh,h->nk', x, weight)
    logits[~mask] = -np.inf
    assert (logits.argmax(1) == y).mean() == 1
    assert history[-1]['validation_nll'] < history[0]['validation_nll']


def test_temperature_is_positive_and_improves_heldout_nll():
    logits = np.array([[9., 0.]] * 10)
    gold = np.array([0] * 7 + [1] * 3)
    temperature = fit_temperature(logits, gold)
    assert np.isfinite(temperature) and temperature > 0
    assert metrics(softmax(logits / temperature), gold)['nll'] < metrics(softmax(logits), gold)['nll']


def test_metrics_calibration_and_ordinal_expectation():
    p = np.array([[.8, .2], [.1, .9]])
    result = metrics(p, np.array([0, 1]), ordinal=True)
    assert result['accuracy'] == 1 and result['macro_f1'] == 1
    assert result['ece'] == pytest.approx(.15)
    assert result['mae'] == pytest.approx(.15)
    assert len(result['reliability']) == 10


def test_artifact_bundle_is_integrity_checked(tmp_path):
    manifest = {'encoder_id': 'test', 'encoder_revision': 'a' * 40, 'hidden_size': 2,
                'data_hash': 'b' * 64, 'review_status': 'experimental'}
    save_bundle(tmp_path, np.array([1., 2.]), {'noul': 1., 'choice': 2., 'score': 3.}, manifest, {'accuracy': .5})
    assert verify_bundle(tmp_path)['hidden_size'] == 2
    (tmp_path / 'calibration.json').write_text('{}')
    with pytest.raises(ValueError, match='SHA256'):
        verify_bundle(tmp_path)


def test_binary_report_exposes_majority_collapse_despite_high_accuracy():
    p=np.tile([.99,.01],(100,1));y=np.array([0]*90+[1]*10)
    result=metrics(p,y,positive_label=1)
    assert result['accuracy']==.9
    assert result['positive_recall']==0
    assert result['positive_precision']==0
    assert result['positive_support']==10
    assert result['confusion']==[[90,0],[10,0]]