okami.mom/strata

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

Niko1221Merge branch 'f-139-prs' into f-139-rel3ed9dafa1

main
1.8 KiB47 linesraw
1"""Tests for tools/draft_vocab.py's corpus coverage mode (#597): the most frequent tokens of a corpus that together cover
2a given share of its occurrences.  No model, no GPU.
3
4    python -m unittest tools.test_draft_vocab
5"""
6from __future__ import annotations
7
8import sys
9import tempfile
10import unittest
11from collections import Counter
12from pathlib import Path
13
14sys.path.insert(0, str(Path(__file__).resolve().parent))
15import draft_vocab as DV  # noqa: E402
16
17
18class Coverage(unittest.TestCase):
19    def test_most_frequent_first_until_the_share_is_covered(self):
20        c = Counter({7: 50, 3: 30, 9: 15, 4: 5})              # 100 occurrences
21        self.assertEqual(DV.covering(c, 0.5), [7])
22        self.assertEqual(DV.covering(c, 0.8), [7, 3])
23        self.assertEqual(DV.covering(c, 0.81), [7, 3, 9])
24        self.assertEqual(DV.covering(c, 1.0), [7, 3, 9, 4])
25
26    def test_ties_take_the_lower_id_first(self):
27        self.assertEqual(DV.covering(Counter({5: 10, 2: 10, 8: 10}), 0.5), [2, 5])
28
29    def test_share_outside_a_subset(self):
30        c = Counter({1: 60, 2: 30, 3: 10})
31        self.assertAlmostEqual(DV.outside(c, [1]), 0.4)
32        self.assertAlmostEqual(DV.outside(c, [1, 2, 3]), 0.0)
33        self.assertEqual(DV.outside(Counter(), [1]), 0.0)
34
35    def test_corpus_counts_reads_every_file(self):
36        class Tok:                                            # one id per character
37            def encode(self, text):
38                return [ord(ch) for ch in text]
39        with tempfile.TemporaryDirectory() as d:
40            a, b = Path(d) / "a.txt", Path(d) / "b.txt"
41            a.write_text("été", encoding="utf-8")
42            b.write_text("eté", encoding="utf-8")
43            self.assertEqual(DV.corpus_counts(Tok(), [a, b]), Counter({ord("é"): 3, ord("t"): 2, ord("e"): 1}))
44
45
46if __name__ == "__main__":
47    unittest.main()