File size: 2,418 Bytes
a840bec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import importlib.util
import sys
import tempfile
import unittest
from pathlib import Path

DISTILL = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(DISTILL))

HAS_TORCH = importlib.util.find_spec("torch") is not None


@unittest.skipUnless(HAS_TORCH, "PyTorch is only installed in the training environment")
class CompactCacheTest(unittest.TestCase):
    def test_tensor_cache_round_trip_and_collation(self):
        import torch
        from data import TernDataset, collate_fn, load_cache, save_cache, split_size

        split = {
            "input_ids": torch.arange(24, dtype=torch.int32).reshape(3, 8),
            "attention_mask": torch.ones((3, 8), dtype=torch.bool),
            "teacher_emb": torch.nn.functional.normalize(torch.randn(3, 4), dim=1),
            "source": ["a", "a", "b"],
        }
        with tempfile.TemporaryDirectory() as directory:
            save_cache(
                {"train": split, "val": split, "test": split},
                {"format": "test"},
                Path(directory),
                "compact",
            )
            loaded, manifest = load_cache(Path(directory), "compact")

        self.assertEqual(manifest["format"], "test")
        self.assertEqual(split_size(loaded["train"]), 3)
        dataset = TernDataset(loaded["train"])
        batch = collate_fn([dataset[0], dataset[1]])
        self.assertEqual(batch["input_ids"].dtype, torch.int64)
        self.assertEqual(tuple(batch["input_ids"].shape), (2, 8))
        self.assertEqual(batch["source"], ["a", "a"])

    def test_compact_stratified_split_preserves_rows(self):
        import torch
        from data import split_size
        from prep.ingest import stratified_tensor_split

        tokens = {
            "input_ids": torch.arange(96, dtype=torch.int32).reshape(12, 8),
            "attention_mask": torch.ones((12, 8), dtype=torch.bool),
        }
        teacher = torch.nn.functional.normalize(torch.randn(12, 4), dim=1)
        splits = stratified_tensor_split(
            tokens,
            teacher,
            ["a"] * 6 + ["b"] * 6,
            val_ratio=1 / 6,
            test_ratio=1 / 6,
            seed=42,
        )

        self.assertEqual(sum(split_size(split) for split in splits.values()), 12)
        self.assertEqual(split_size(splits["val"]), 2)
        self.assertEqual(split_size(splits["test"]), 2)


if __name__ == "__main__":
    unittest.main()