Download distill/tests/test_compact_cache.py from Grizzlykw/ternlight-multilingual-e5: direct link, hf CLI and curl.
- Browser
- Download file 2.42 kB
-
https://huggingface.co/Grizzlykw/ternlight-multilingual-e5/resolve/main/distill/tests/test_compact_cache.py
- Command line
-
hf download hf://Grizzlykw/ternlight-multilingual-e5/distill/tests/test_compact_cache.py
-
curl -L -o test_compact_cache.py https://huggingface.co/Grizzlykw/ternlight-multilingual-e5/resolve/main/distill/tests/test_compact_cache.py
2.42 kB
| 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 | |
| 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() | |