Download tests/data/test_shards.py from Kolgrim/hades: direct link, hf CLI and curl.
- Browser
- Download file 5.41 kB
-
https://huggingface.co/Kolgrim/hades/resolve/main/tests/data/test_shards.py
- Command line
-
hf download hf://Kolgrim/hades/tests/data/test_shards.py
-
curl -L -o test_shards.py https://huggingface.co/Kolgrim/hades/resolve/main/tests/data/test_shards.py
5.41 kB
| import json | |
| import numpy as np | |
| from hades.data.pipeline import normalize_stage, sample_stage, tokenize_stage | |
| from hades.data.shards import ShardWriter, split_of, write_manifest, write_shards | |
| from hades.data.sources.base import Record | |
| from hades.tokenizer.export import export_hf | |
| BOS, EOS = 900, 901 | |
| def test_split_of_deterministic_and_rate(): | |
| assert split_of("CVE-2024-1") == split_of("CVE-2024-1") | |
| vals = sum(split_of(f"doc-{i}") == "val" for i in range(100_000)) | |
| assert 300 <= vals <= 700 | |
| def test_shards_roundtrip(tmp_path): | |
| docs = [[1, 2, 3], [4], [5, 6, 7, 8, 9], [10, 11]] | |
| shards = write_shards(docs, tmp_path, "train", bos_id=BOS, eos_id=EOS, shard_tokens=8) | |
| data = np.concatenate([np.fromfile(s["path"], dtype="<u2") for s in shards]).tolist() | |
| expected = [t for d in docs for t in [BOS, *d, EOS]] | |
| assert data == expected | |
| assert [s["tokens"] for s in shards] == [len(np.fromfile(s["path"], dtype="<u2")) for s in shards] | |
| assert len(shards) >= 2 | |
| first = np.fromfile(shards[0]["path"], dtype="<u2").tolist() | |
| assert first[-1] == EOS # docs are never cut at a shard boundary | |
| def test_manifest_counts(tmp_path): | |
| w = ShardWriter(tmp_path, "train", BOS, EOS, shard_tokens=100) | |
| w.add([1, 2, 3], n_bytes=10) | |
| shards = w.close() | |
| stats = {"tokenizer_sha256": "x", "groups": {"logs": {"train": {"tokens": w.tokens, "bytes": w.bytes, "shards": shards}}}, | |
| "sources": {}} | |
| write_manifest(tmp_path, stats) | |
| m = json.loads((tmp_path / "manifest.json").read_text()) | |
| assert m["groups"]["logs"]["train"]["tokens"] == 5 == sum(s["tokens"] for s in m["groups"]["logs"]["train"]["shards"]) | |
| assert "created" in m and len(m["groups"]["logs"]["train"]["shards"][0]["sha256"]) == 64 | |
| class _FakeSource: | |
| def __init__(self, name, group, texts): | |
| self.NAME, self.GROUP, self.LICENSE, self._texts = name, group, "L", texts | |
| def iter_records(self, raw_dir): | |
| for i, t in enumerate(self._texts): | |
| yield Record(self.NAME, f"{self.NAME}-{i}", self.LICENSE, self.GROUP, t) | |
| def test_pipeline_end_to_end(tmp_path, trained_small): | |
| para = "Secure Shell protects remote logins. Administrators review authentication logs every morning. " | |
| leaked = "Oct 28 sshd[1]: Failed password for root from 1.2.3.4 port 22 ssh2 " * 3 | |
| sources = { | |
| "sec": _FakeSource("sec", "security", [para * 3 + str(i) for i in range(30)] + [para * 3 + leaked]), | |
| "gen": _FakeSource("gen", "general", [para * 4 + str(i) for i in range(30)] + [para * 3 + "0"]), | |
| "synth_logs": _FakeSource("synth_logs", "logs", [leaked * 5 + str(i) for i in range(10)]), | |
| } | |
| interim = tmp_path / "interim" | |
| normalize_stage(tmp_path / "raw", interim, sources) | |
| assert sum(1 for _ in open(interim / "gen.jsonl")) == 30 # exact duplicate of a sec doc dropped | |
| sample_stage(interim, interim / "tokenizer_sample.txt", total_bytes=5_000, mix={"security": 0.4, "general": 0.4, "logs": 0.2}) | |
| assert 0 < (interim / "tokenizer_sample.txt").stat().st_size <= 7_000 | |
| (tmp_path / "eval").mkdir() | |
| (tmp_path / "eval" / "eval_text.jsonl").write_text(json.dumps({"text": leaked}) + "\n") | |
| export_hf(trained_small, tmp_path / "tok.json") | |
| out = tmp_path / "processed" | |
| tokenize_stage(interim, out, tmp_path / "tok.json", tmp_path / "eval", sources) | |
| m = json.loads((out / "manifest.json").read_text()) | |
| assert m["sources"]["sec"]["contaminated"] == 1 and m["sources"]["sec"]["docs"] == 30 | |
| assert m["sources"]["synth_logs"]["contaminated"] == 0 and m["sources"]["synth_logs"]["docs"] == 10 | |
| for group in ("security", "general", "logs"): | |
| g = m["groups"][group] | |
| total = sum(s["tokens"] for split in g.values() for s in split["shards"]) | |
| assert total == sum(split["tokens"] for split in g.values()) > 0 | |
| def test_tokenize_refuses_without_eval_texts(tmp_path, trained_small): | |
| import pytest | |
| sources = {"gen": _FakeSource("gen", "general", ["Plain educational text about rivers and valleys. " * 10])} | |
| interim = tmp_path / "interim" | |
| normalize_stage(tmp_path / "raw", interim, sources) | |
| export_hf(trained_small, tmp_path / "tok.json") | |
| (tmp_path / "eval").mkdir() | |
| with pytest.raises(ValueError, match="decontamination"): | |
| tokenize_stage(interim, tmp_path / "out", tmp_path / "tok.json", tmp_path / "eval", sources) | |
| tokenize_stage(interim, tmp_path / "out", tmp_path / "tok.json", tmp_path / "eval", sources, allow_no_decontam=True) | |
| m = json.loads((tmp_path / "out" / "manifest.json").read_text()) | |
| assert m["decontamination"] == {"eval_texts": 0, "ngrams": 0, "eval_sha256": None} | |
| def test_manifest_records_decontamination(tmp_path, trained_small): | |
| sources = {"gen": _FakeSource("gen", "general", ["Plain educational text about rivers and valleys. " * 10])} | |
| interim = tmp_path / "interim" | |
| normalize_stage(tmp_path / "raw", interim, sources) | |
| export_hf(trained_small, tmp_path / "tok.json") | |
| (tmp_path / "eval").mkdir() | |
| (tmp_path / "eval" / "eval_text.jsonl").write_text(json.dumps({"text": "a b c d e f g h i j k l m n o p"}) + "\n") | |
| tokenize_stage(interim, tmp_path / "out", tmp_path / "tok.json", tmp_path / "eval", sources) | |
| d = json.loads((tmp_path / "out" / "manifest.json").read_text())["decontamination"] | |
| assert d["eval_texts"] == 1 and d["ngrams"] > 0 and len(d["eval_sha256"]) == 64 | |