okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-1402-r' into f-1402d19c07650

main
3.6 KiB89 linesraw
1"""Offline test of tools/research_run.py against the server's mock engine (no GPU, no pack)."""
2import contextlib
3import io
4import json
5import sys
6import tempfile
7import unittest
8from pathlib import Path
9
10ROOT = Path(__file__).resolve().parents[1]
11sys.path.insert(0, str(ROOT))
12sys.path.insert(0, str(ROOT / "tools"))
13import research_run  # noqa: E402
14from serve.frontend import ChatTemplate  # noqa: E402
15from serve.server import ByteTokenizer, MockEngine, Service, serve  # noqa: E402
16
17
18class Recorder(MockEngine):
19    def __init__(self, *a, **k):
20        super().__init__(*a, **k)
21        self.samplings = []
22
23    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
24        self.samplings.append(dict(sampling))
25        yield from super().generate(ids, max_new, sampling, cancel, embeddings)
26
27
28class ResearchRun(unittest.TestCase):
29    @classmethod
30    def setUpClass(cls):
31        tok = ByteTokenizer()
32        cls.engine = Recorder(tok, "an answer", max_context=8192)
33        cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
34        cls.httpd = serve(cls.svc, port=0)
35        cls.url = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
36        cls.dir = tempfile.TemporaryDirectory()
37        d = Path(cls.dir.name)
38        (d / "doc.txt").write_text("The document. " * 40, encoding="utf-8")
39        (d / "q.txt").write_text("What is it?\nWho wrote it?\n\nWhen?\n", encoding="utf-8")
40
41    @classmethod
42    def tearDownClass(cls):
43        cls.httpd.shutdown()
44        cls.httpd.server_close()
45        cls.dir.cleanup()
46
47    def go(self, *extra):
48        d = Path(self.dir.name)
49        out = d / "out.json"
50        buf = io.StringIO()
51        with contextlib.redirect_stdout(buf):
52            code = research_run.main(["--url", self.url, "--doc", str(d / "doc.txt"), "--questions", str(d / "q.txt"),
53                                      "--json", str(out), *extra])
54        return code, json.loads(out.read_text(encoding="utf-8")), buf.getvalue()
55
56    def test_split_run_names_the_prefix_and_reports_every_question(self):
57        self.engine.samplings.clear()
58        code, out, text = self.go("--prefix", "on")
59        self.assertEqual(code, 0, text)
60        self.assertEqual([q["q"] for q in out["questions"]], [0, 1, 2])          # the blank line is skipped
61        self.assertTrue(all(q["text"] for q in out["questions"]))
62        self.assertEqual(len(self.engine.samplings), 3)
63        for s in self.engine.samplings:
64            self.assertEqual(s["strata_prefix"]["tokens"] > 0, True)               # resolved by the server
65        self.assertIn("median first token", text)
66
67    def test_prefix_off_and_the_joined_layout(self):
68        self.engine.samplings.clear()
69        self.go("--prefix", "off")
70        self.assertTrue(all("strata_prefix" not in s for s in self.engine.samplings))
71        self.engine.samplings.clear()
72        code, out, _ = self.go("--prefix", "on", "--layout", "joined", "--parallel", "2")
73        self.assertEqual(code, 0)
74        self.assertTrue(all(s["strata_prefix"]["tokens"] > 0 for s in self.engine.samplings))
75
76    def test_compare(self):
77        d = Path(self.dir.name)
78        self.go("--prefix", "off")
79        (d / "a.json").write_text((d / "out.json").read_text(encoding="utf-8"), encoding="utf-8")
80        self.go("--prefix", "on")
81        buf = io.StringIO()
82        with contextlib.redirect_stdout(buf):
83            code = research_run.main(["--compare", str(d / "a.json"), str(d / "out.json")])
84        self.assertEqual(code, 0, buf.getvalue())
85        self.assertIn("3 answers identical, 0 differ", buf.getvalue())
86
87
88if __name__ == "__main__":
89    unittest.main()