File size: 3,651 Bytes
4807d4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The engine on a tiny offline model: loading a folder, the contract, determinism, batching, limits."""

import math

import pytest

import discerna
from discerna.contract import DecisionRequest, check_response, distribution
from discerna.model.weights import from_checkpoint
from probes import image_requests, text_requests
from tiny import tiny_folder


@pytest.fixture(scope="module", params=[False, True], ids=["text", "vision"])
def model(request, tmp_path_factory):
    m = discerna.load(tiny_folder(tmp_path_factory.mktemp("tiny"), vision=request.param), device="cpu")
    yield m
    m.close()


def probes(model) -> dict[str, DecisionRequest]:
    return text_requests() | (image_requests() if model.accepts_images else {})


def dists(request, response):
    return {n: distribution(q, response.answers[n]) for n, q in request.questions.items()}


def assert_close(a: dict, b: dict, tol: float = 1e-5):
    assert a.keys() == b.keys()
    for name in a:
        for key in a[name]:
            assert math.isclose(a[name][key], b[name][key], abs_tol=tol), (name, key)


def test_every_response_honours_the_contract(model):
    for name, request in probes(model).items():
        response = model.decide(request)
        assert check_response(request, response) == [], name
        assert response.model == "tiny" and response.usage.input_tokens > 0


def test_deterministic(model):
    for request in probes(model).values():
        assert_close(dists(request, model.decide(request)), dists(request, model.decide(request)), 0.0)


def test_questions_do_not_affect_each_other(model):
    request = text_requests()["ticket"]
    together = dists(request, model.decide(request))
    for name, q in request.questions.items():
        alone = DecisionRequest(state=request.state, questions={name: q})
        assert_close({name: together[name]}, dists(alone, model.decide(alone)))


def test_batch_matches_single(model):
    requests = list(probes(model).values())
    for request, result in zip(requests, model.decide_batch(requests), strict=True):
        assert not isinstance(result, Exception), result
        assert_close(dists(request, result), dists(request, model.decide(request)))


def test_plain_dicts_are_accepted_and_bad_ones_fail_alone(model):
    good = {"state": "The cup is red.", "questions": {"red": {"type": "noul", "instructions": "Is it red?"}}}
    bad = {"state": "x", "questions": {}}
    results = model.decide_batch([good, bad, good])
    assert not isinstance(results[0], Exception) and not isinstance(results[2], Exception)
    assert isinstance(results[1], Exception)
    assert results[0].answers["red"].noul == results[2].answers["red"].noul


def test_images_refused_by_a_text_only_model(model):
    if model.accepts_images:
        pytest.skip("this model accepts images")
    result = model.decide_batch([image_requests()["image_only_state"]])[0]
    assert isinstance(result, discerna.Unsupported)


def test_a_folder_loads_exactly(tmp_path):
    folder = tiny_folder(tmp_path / "m", vision=True, seed=3)
    again = from_checkpoint(folder)
    original = discerna.load(folder, device="cpu").model
    for (name, a), (_, b) in zip(original.state_dict().items(), again.state_dict().items(), strict=True):
        assert a.equal(b), name


def test_wrong_format_is_refused(tmp_path):
    import json

    folder = tiny_folder(tmp_path / "m")
    config = json.loads((folder / "config.json").read_text())
    (folder / "config.json").write_text(json.dumps({**config, "format": "something-else/1"}))
    with pytest.raises(ValueError, match="not a discerna/1 model"):
        discerna.load(folder, device="cpu")