File size: 10,992 Bytes
589eb71
615b9eb
 
589eb71
615b9eb
 
 
 
 
 
 
 
 
 
589eb71
615b9eb
589eb71
615b9eb
 
 
 
 
 
 
 
 
 
 
589eb71
 
 
 
 
 
 
 
 
615b9eb
 
 
 
 
 
 
589eb71
615b9eb
 
589eb71
 
 
615b9eb
 
589eb71
 
 
615b9eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589eb71
 
 
 
 
 
62ebd55
 
615b9eb
 
 
 
 
 
 
589eb71
 
615b9eb
589eb71
 
615b9eb
589eb71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
615b9eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589eb71
 
615b9eb
 
 
 
589eb71
615b9eb
 
 
 
 
 
 
589eb71
 
 
 
 
 
 
615b9eb
589eb71
615b9eb
 
 
 
 
589eb71
 
 
 
 
 
 
 
 
615b9eb
589eb71
615b9eb
 
589eb71
615b9eb
 
 
 
589eb71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
615b9eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589eb71
 
615b9eb
589eb71
 
 
 
 
 
 
 
 
 
 
 
615b9eb
 
966d672
 
 
 
589eb71
966d672
 
589eb71
 
966d672
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
"""Behavior tests against the real checkpoint (CPU)."""

import json
import math
import os
import threading
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import pytest
import torch

from julia15 import Runtime
from julia15.encoding import QTYPES, RequestError, answer, build_rows
from julia15.runtime import load_models, rotations

ROOT = Path(os.environ.get('JULIA15_ROOT', Path(__file__).resolve().parents[2]))
REFERENCE = json.loads((Path(__file__).parent / 'fixtures/reference.json').read_text())
ROW = {
    'state': 'The player has 2 HP and the boss has 50 HP.',
    'question': 'What should the player do?',
    'type': 'choice',
    'options': ['Attack the boss', 'Drink a healing potion', 'Dance'],
}


def close(a, b, atol=2e-5, rtol=5e-5):
    """fp32 reduction order differs between batch layouts; error scales with logit size."""
    return torch.allclose(torch.tensor(a), torch.tensor(b), atol=atol, rtol=rtol)


def probs(logits):
    top = max(logits)
    e = [math.exp(x - top) for x in logits]
    return [x / sum(e) for x in e]


@pytest.fixture(scope='module')
def rt():
    return Runtime(ROOT, device='cpu', threads=4, cache_entries=0)


# ---- contracts ---------------------------------------------------------------


def test_single_model():
    assert set(load_models(ROOT)['models']) == {'julia-1.5'}
    assert not (ROOT / 'router.json').exists()


@pytest.mark.parametrize('n,views,expected', [(3, 1, [0]), (3, 3, [0, 1, 2]), (4, 2, [0, 2]), (2, 8, [0, 1])])
def test_rotations(n, views, expected):
    assert rotations(n, views) == expected


def test_build_rows_julia1_rules():
    rows, keys = build_rows(
        {'ticket': 'x'},
        {
            'team': {
                'type': 'choice',
                'instructions': 'Which team?',
                'criteria': {'billing': 'Billing', 'tech': 'Tech'},
            },
            'urgent': {'type': 'noul', 'instructions': 'Urgent?'},
            'level': {'type': 'score', 'instructions': 'Severity?', 'criteria': ['low', 'mid', 'high']},
        },
    )
    assert [r['options'] for r in rows.values()] == [['Billing', 'Tech'], ['false', 'true'], ['low', 'mid', 'high']]
    assert keys == {'team': ['billing', 'tech'], 'urgent': ['false', 'true'], 'level': ['0', '1', '2']}
    assert QTYPES[rows['urgent']['type']] == 2


@pytest.mark.parametrize(
    'questions',
    [
        {},
        {'q': {'type': 'noul', 'criteria': {'true': 'yes'}}},
        {'q': {'type': 'choice', 'criteria': ['a', 'b']}},
        {'q': {'type': 'score', 'criteria': {'a': 1}}},
        {'q': {'type': 'rank'}},
    ],
)
def test_build_rows_rejects_invalid(questions):
    with pytest.raises(RequestError):
        build_rows('s', questions)


@pytest.mark.parametrize(
    'kind,labels,logits,expected',
    [
        ('choice', ['a', 'b'], [2.0, 0.0], {'choice': 'a'}),
        ('score', ['0', '1', '2'], [0.0, 0.0, 0.0], {'score': 1.0, 'level': 0}),
        ('noul', ['false', 'true'], [0.0, 0.0], {'noul': 0.5}),
    ],
)
def test_answer_shape_matches_julia1(kind, labels, logits, expected):
    out = answer(kind, labels, logits)
    for k, v in expected.items():
        assert out[k] == pytest.approx(v)
    assert ('max_probability' in out) == (kind != 'noul')
    assert sum(out['probabilities'].values()) == pytest.approx(1.0)


# ---- numerical parity with the training reference ----------------------------


def test_logits_match_training_reference(rt):
    if os.environ.get('JULIA15_SKIP_REFERENCE'):
        pytest.skip('checkpoint differs from the fixture checkpoint')
    got = rt.logits(REFERENCE['rows'])
    for g, want in zip(got, REFERENCE['logits']['julia-1.5/core']):
        assert close(g, want, atol=5e-5), (g, want)


def test_batch_equals_single(rt):
    other = dict(ROW, state='Short.', options=['yes', 'no'])
    single = [rt.logits([ROW])[0], rt.logits([other])[0]]
    for s, b in zip(single, rt.logits([ROW, other])):
        assert close(s, b)


# ---- order-robust views --------------------------------------------------------


def test_views_one_is_plain_logits(rt):
    assert close(rt.logits([ROW], views=1)[0], rt.logits([ROW])[0], 0, 0)


def test_full_views_are_rotation_invariant(rt):
    opts = ROW['options']
    a = probs(rt.logits([ROW], views=3)[0])
    rotated = dict(ROW, options=opts[1:] + opts[:1])
    b = probs(rt.logits([rotated], views=3)[0])
    assert close(a, b[-1:] + b[:-1], 1e-5)  # same probability for the same option text
    plain = probs(rt.logits([ROW])[0])
    assert sum(a) == pytest.approx(1.0) and not close(a, plain, 1e-6)


def test_views_leave_ordered_types_alone(rt):
    noul = dict(ROW, type='noul', options=['false', 'true'])
    score = dict(ROW, type='score', options=['low', 'mid', 'high'])
    for r in (noul, score):
        assert close(rt.logits([r], views=4)[0], rt.logits([r])[0], 0, 0)
    _, meta = rt.logits([noul, ROW], details=True, views=4)
    assert [m['views'] for m in meta] == [1, 3]


@pytest.mark.parametrize('views', [0, 9, 1.5, 'two', True])
def test_views_rejects_invalid(rt, views):
    with pytest.raises(RequestError):
        rt.logits([ROW], views=views)


# ---- scheduler / errors / cache ------------------------------------------------


def test_concurrent_requests_coalesce_and_match(rt):
    rows = [dict(ROW, state=f'Case {i}: the player has {i} HP.') for i in range(24)]
    sequential = [rt.logits([r])[0] for r in rows]
    batches = rt.stats['batches']
    with ThreadPoolExecutor(12) as pool:
        parallel = list(pool.map(lambda r: rt.logits([r])[0], rows))
    assert all(close(a, b) for a, b in zip(sequential, parallel))
    assert rt.stats['batches'] - batches < len(rows)


def test_errors_reach_caller_and_runtime_keeps_working(rt):
    with pytest.raises(RequestError):
        rt.logits([dict(ROW, options=['only one'])])
    with pytest.raises(RequestError):
        rt.logits([ROW], model='missing')
    with pytest.raises(RequestError):
        rt.logits([{'state': 's'}], views=3)
    assert len(rt.logits([ROW])[0]) == 3


def test_strict_mode_rejects_truncation_and_markers():
    strict = Runtime(ROOT, device='cpu', strict=True, cache_entries=0, warmup=False)
    with pytest.raises(RequestError):
        strict.logits([dict(ROW, state='word ' * 3000)])
    with pytest.raises(RequestError):
        strict.logits([dict(ROW, question='pick <mask> now')])
    assert len(strict.logits([ROW])[0]) == 3


def test_truncation_is_reported(rt):
    _, meta = rt.logits([dict(ROW, state='word ' * 3000), ROW], details=True)
    assert [m['truncated'] for m in meta] == [True, False]
    out = rt.decide('word ' * 3000, 'Act?', ['a', 'b'])
    assert out['truncated'] is True


def test_result_cache_hits():
    cached = Runtime(ROOT, device='cpu', cache_entries=16, warmup=False)
    first = cached.logits([ROW])
    assert cached.logits([ROW]) == first
    assert cached.stats['cache_hits'] == 1


# ---- typed API -----------------------------------------------------------------

QUESTIONS = {
    'team': {'type': 'choice', 'instructions': 'Which team?', 'criteria': {'billing': 'Billing', 'tech': 'Tech'}},
    'urgent': {'type': 'noul', 'instructions': 'Is it urgent?'},
    'level': {'type': 'score', 'instructions': 'Severity', 'criteria': ['low', 'high']},
}


def test_predict_api_shape(rt):
    out = rt.predict_questions({'ticket': 'My card was charged twice'}, QUESTIONS)
    assert out['model'] == 'julia-1.5'
    a = out['answers']
    assert a['team']['choice'] in ('billing', 'tech')
    assert 0 <= a['urgent']['noul'] <= 1 and 'max_probability' not in a['urgent']
    assert 0 <= a['level']['score'] <= 1 and set(a['level']['probabilities']) == {'0', '1'}


def test_predict_many_matches_single(rt):
    states = [{'ticket': 'My card was charged twice'}, {'ticket': 'The app crashes on login'}]
    many = rt.predict_many([{'state': s, 'questions': QUESTIONS} for s in states], views=2)
    for s, got in zip(states, many):
        want = rt.predict_questions(s, QUESTIONS, views=2)
        for q in QUESTIONS:
            assert close(list(got['answers'][q]['probabilities'].values()),
                         list(want['answers'][q]['probabilities'].values()))
    assert many[0]['answers']['team']['views'] == 2


def test_decide_convenience(rt):
    out = rt.decide(ROW['state'], ROW['question'], {'a': 'Attack the boss', 'h': 'Drink a healing potion'})
    assert out['choice'] in ('a', 'h') and set(out['probabilities']) == {'a', 'h'}
    yn = rt.decide(ROW['state'], 'Is the player in danger?', None or ['false', 'true'], type='noul')
    assert 0 <= yn['noul'] <= 1


# ---- HTTP ----------------------------------------------------------------------


def test_http_server(rt):
    from julia15.server import make_server

    server = make_server(rt, '127.0.0.1', 0)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    base = f'http://127.0.0.1:{server.server_address[1]}'

    def post(path, body):
        request = urllib.request.Request(base + path, json.dumps(body).encode(), {'Content-Type': 'application/json'})
        return json.load(urllib.request.urlopen(request))

    try:
        assert json.load(urllib.request.urlopen(base + '/health'))['status'] == 'ok'
        info = json.load(urllib.request.urlopen(base + '/v1/info'))
        assert set(info['models']) == {'julia-1.5'}
        assert info['models']['julia-1.5']['fingerprint']
        assert b'julia15_rows_total' in urllib.request.urlopen(base + '/metrics').read()
        out = post('/v1/predict', {'state': 'boss fight', 'questions': {'q': {'type': 'noul', 'instructions': 'Flee?'}}})
        assert 0 <= out['answers']['q']['noul'] <= 1
        out = post('/v1/predict_batch', {'views': 2, 'requests': [{'state': 'a', 'questions': QUESTIONS}] * 2})
        assert len(out['results']) == 2 and out['results'][0]['answers']['team']['views'] == 2
        out = post('/v1/logits', {'rows': [ROW], 'views': 3})
        assert len(out['logits'][0]) == 3 and out['rows'][0]['views'] == 3
        for path, body in (('/v1/predict', {'state': 's', 'questions': {'q': {'type': 'bogus'}}}),
                           ('/v1/logits', {'rows': [ROW], 'views': 99}),
                           ('/v1/predict', {'questions': {}})):
            with pytest.raises(urllib.error.HTTPError) as error:
                post(path, body)
            assert error.value.code == 400
    finally:
        server.shutdown()


def test_padded_attention_matches_packed():
    """GPU attention layout, verified on CPU: same logits as the packed path."""
    padded = Runtime(ROOT, device='cpu', attention='padded', cache_entries=0, warmup=False)
    assert padded.info()['attention'] == 'padded'
    rows = REFERENCE['rows'] + [ROW]
    want = Runtime(ROOT, device='cpu', cache_entries=0, warmup=False).logits(rows)
    for g, w in zip(padded.logits(rows), want):
        assert close(g, w, atol=5e-5)