okami.mom/strata

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

Niko1221Merge f-draft-vocab 925d6fb05 into f-p4-int (the draft vocabulary is picked by the computer's languages; a renamed Flash-Next file starts the drafter)bc6f248ff

main
8.7 KiB166 linesraw
1"""Tests for setup.py's draft-vocabulary choice (#287): a setup run again without --draft-vocab keeps the subset the
2model's config chose before (cyrillic, fr, en), and refresh_draft_vocab copies the chosen shipped subset.  Pure file work
3in a temporary folder - no GPU, no downloads, no prompts.
4
5    python -m unittest tools.test_setup_draft_vocab
6"""
7from __future__ import annotations
8
9import hashlib
10import json
11import sys
12import tempfile
13import unittest
14from pathlib import Path
15
16ROOT = Path(__file__).resolve().parents[1]
17sys.path.insert(0, str(ROOT))
18import setup  # noqa: E402
19
20
21class SavedChoice(unittest.TestCase):
22    def test_a_config_keeps_its_choice(self):
23        with tempfile.TemporaryDirectory() as d:
24            for choice in setup.DRAFT_VOCABS:
25                p = Path(d) / "strata-x.json"
26                p.write_text(json.dumps({"args": [], "draft_vocab": choice}), encoding="utf-8")
27                self.assertEqual(setup.saved_draft_vocab(p), choice)
28
29    def test_no_choice_without_a_valid_config(self):
30        with tempfile.TemporaryDirectory() as d:
31            self.assertIsNone(setup.saved_draft_vocab(Path(d) / "missing.json"))
32            for text in ("{}", "[1]", "not json", json.dumps({"draft_vocab": "klingon"})):
33                p = Path(d) / "strata-y.json"
34                p.write_text(text, encoding="utf-8")
35                self.assertIsNone(setup.saved_draft_vocab(p), text)
36
37
38class Refresh(unittest.TestCase):
39    def test_cyrillic_replaces_a_shipped_subset_and_stays(self):
40        if not (ROOT / "data" / setup.DRAFT_VOCABS["cyrillic"]).exists():
41            self.skipTest("data/draft_vocab_cyrillic.bin is not in this checkout")
42        want = hashlib.sha256((ROOT / "data" / setup.DRAFT_VOCABS["cyrillic"]).read_bytes()).hexdigest()
43        with tempfile.TemporaryDirectory() as d:
44            rt = Path(d)
45            (rt / "draft_vocab.bin").write_bytes((ROOT / "data" / setup.DRAFT_VOCABS["cjk"]).read_bytes())
46            setup.refresh_draft_vocab(rt, "cyrillic")
47            self.assertEqual(hashlib.sha256((rt / "draft_vocab.bin").read_bytes()).hexdigest(), want)
48            setup.refresh_draft_vocab(rt, "cyrillic")                       # again: nothing changes
49            self.assertEqual(hashlib.sha256((rt / "draft_vocab.bin").read_bytes()).hexdigest(), want)
50
51
52    def test_fr_replaces_a_shipped_subset_and_back(self):
53        # #597: the French subset is a shipped one too - a later --draft-vocab cjk (or en) replaces it again, while a
54        # subset made by hand stays
55        data = ROOT / "data"
56        if not (data / setup.DRAFT_VOCABS["fr"]).exists():
57            self.skipTest("data/draft_vocab_fr.bin is not in this checkout")
58        sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()   # noqa: E731
59        with tempfile.TemporaryDirectory() as d:
60            rt = Path(d)
61            (rt / "draft_vocab.bin").write_bytes((data / setup.DRAFT_VOCABS["en"]).read_bytes())
62            setup.refresh_draft_vocab(rt, "fr")
63            self.assertEqual(sha(rt / "draft_vocab.bin"), sha(data / setup.DRAFT_VOCABS["fr"]))
64            setup.refresh_draft_vocab(rt, "cjk")
65            self.assertEqual(sha(rt / "draft_vocab.bin"), sha(data / setup.DRAFT_VOCABS["cjk"]))
66            (rt / "draft_vocab.bin").write_bytes(bytes([1, 0, 0, 0]))   # made by hand: kept
67            setup.refresh_draft_vocab(rt, "fr")
68            self.assertEqual((rt / "draft_vocab.bin").read_bytes(), bytes([1, 0, 0, 0]))
69
70    def test_latin_is_copied_and_says_so(self):
71        from unittest import mock
72        data = ROOT / "data"
73        if not (data / setup.DRAFT_VOCABS["latin"]).exists():
74            self.skipTest("data/draft_vocab_latin.bin is not in this checkout")
75        with tempfile.TemporaryDirectory() as d:
76            rt = Path(d)
77            (rt / "draft_vocab.bin").write_bytes((data / setup.DRAFT_VOCABS["cjk"]).read_bytes())
78            with mock.patch.object(setup, "ok") as said:
79                setup.refresh_draft_vocab(rt, "latin")
80            self.assertEqual((rt / "draft_vocab.bin").read_bytes(), (data / setup.DRAFT_VOCABS["latin"]).read_bytes())
81            self.assertEqual(said.call_args[0][0], "draft layer: the token subset with the Latin-script languages")
82
83    def test_fr_holds_the_en_subset_in_its_order(self):
84        # built with tools/draft_vocab.py --base data/draft_vocab_en.bin --corpus ...: the base first, unchanged
85        from array import array
86        data = ROOT / "data"
87        if not (data / setup.DRAFT_VOCABS["fr"]).exists():
88            self.skipTest("data/draft_vocab_fr.bin is not in this checkout")
89        en = list(array("i", (data / setup.DRAFT_VOCABS["en"]).read_bytes()))
90        fr = list(array("i", (data / setup.DRAFT_VOCABS["fr"]).read_bytes()))
91        self.assertEqual(fr[:len(en)], en)
92        self.assertEqual(len(set(fr)), len(fr))
93        self.assertEqual(fr[len(en):], sorted(fr[len(en):]))
94
95
96class SharedFolder(unittest.TestCase):
97    """setup.py --update refreshes the draft subset of every installed config, most recently used first.  Two configs
98    that name one MTP folder: the folder keeps the subset of the one used last, not of the one used longest ago."""
99
100    def setUp(self):
101        self.data = ROOT / "data"
102        if not all((self.data / setup.DRAFT_VOCABS[c]).exists() for c in ("cjk", "cyrillic", "en")):
103            self.skipTest("the shipped draft subsets are not in this checkout")
104        self.sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()   # noqa: E731
105
106    def run_update(self, rt, cfgs):
107        done: set = set()
108        for cfg in cfgs:                                                    # update_install's loop, newest first
109            setup.refresh_shared_draft_vocab(cfg, done)
110        return self.sha(rt / "draft_vocab.bin")
111
112    def test_the_most_recently_used_config_decides(self):
113        with tempfile.TemporaryDirectory() as d:
114            rt = Path(d)
115            (rt / "draft_vocab.bin").write_bytes((self.data / setup.DRAFT_VOCABS["cyrillic"]).read_bytes())
116            in_use = {"args": ["--mtp", str(rt), "--spec", "4"], "draft_vocab": "cyrillic"}
117            older = {"args": ["--mtp", str(rt), "--spec", "4"]}             # no key: the default subset (cjk)
118            self.assertEqual(self.run_update(rt, [in_use, older]), self.sha(self.data / setup.DRAFT_VOCABS["cyrillic"]))
119            self.assertEqual(self.run_update(rt, [older, in_use]), self.sha(self.data / setup.DRAFT_VOCABS["cjk"]))
120
121    def test_separate_folders_each_keep_their_own(self):
122        with tempfile.TemporaryDirectory() as d:
123            a, b = Path(d) / "a", Path(d) / "b"
124            for rt in (a, b):
125                rt.mkdir()
126                (rt / "draft_vocab.bin").write_bytes((self.data / setup.DRAFT_VOCABS["cjk"]).read_bytes())
127            done: set = set()
128            setup.refresh_shared_draft_vocab({"args": ["--mtp", str(a), "--spec", "4"], "draft_vocab": "cyrillic"}, done)
129            setup.refresh_shared_draft_vocab({"args": ["--mtp", str(b), "--spec", "4"], "draft_vocab": "en"}, done)
130            self.assertEqual(self.sha(a / "draft_vocab.bin"), self.sha(self.data / setup.DRAFT_VOCABS["cyrillic"]))
131            self.assertEqual(self.sha(b / "draft_vocab.bin"), self.sha(self.data / setup.DRAFT_VOCABS["en"]))
132
133    def test_a_config_without_a_draft_layer_is_skipped(self):
134        done: set = set()
135        setup.refresh_shared_draft_vocab({"args": ["--spec", "0"]}, done)
136        setup.refresh_shared_draft_vocab({}, done)
137        self.assertEqual(done, set())
138
139
140class SmallCardNote(unittest.TestCase):
141    """#474: a card under 14 GB is told about a smaller draft subset - a note only, and not when one was chosen."""
142
143    def test_note_on_a_small_card_only(self):
144        note = setup.draft_vocab_note(12.0, None)
145        self.assertTrue(note)
146        self.assertIn("--draft-vocab en", " ".join(note))
147        self.assertIn("the draft head does not fit", " ".join(note))
148        for vram, chosen in ((16.0, None), (24.0, None), (12.0, "en"), (12.0, "cyrillic"), (12.0, "fr"), (12.0, "cjk"),
149                             (0.0, None)):
150            self.assertEqual(setup.draft_vocab_note(vram, chosen), [], (vram, chosen))
151
152    def test_sizes_follow_the_shipped_subsets(self):
153        # the MiB the note gives scale with the subsets' token counts (4 bytes per token id in data/)
154        sizes = {}
155        for choice, name in setup.DRAFT_VOCABS.items():
156            p = ROOT / "data" / name
157            if not p.exists():
158                self.skipTest(f"data/{name} is not in this checkout")
159            sizes[choice] = p.stat().st_size // 4
160        for choice in ("en", "cyrillic", "fr", "latin"):
161            want = setup.DRAFT_VOCAB_MIB["cjk"] * sizes[choice] / sizes["cjk"]
162            self.assertAlmostEqual(setup.DRAFT_VOCAB_MIB[choice], want, delta=3)
163
164
165if __name__ == "__main__":
166    unittest.main()