File size: 3,111 Bytes
82119d7 | 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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | import hashlib
import json
from collections import Counter, defaultdict
from pathlib import Path
from didata.io import iter_jsonl
CURATED = Path("data/curated/documents.jsonl")
CONFIG = Path("configs/data_mix.json")
OUTPUT = Path("data/curated/tokenizer_sample.txt")
REPORT = Path("reports/tokenizer_sample.json")
def deterministic_fraction(seed, doc_id):
raw = hashlib.blake2b(f"{seed}:{doc_id}".encode(), digest_size=8).digest()
return int.from_bytes(raw, "little") / (2**64 - 1)
def main():
cfg = json.loads(CONFIG.read_text(encoding="utf-8"))
weights = cfg["bucket_weights"]
total_target = int(cfg["tokenizer_sample_chars"])
seed = int(cfg["seed"])
available_bucket = Counter()
available_family = Counter()
for doc in iter_jsonl(CURATED):
n = len(doc.text)
available_bucket[doc.bucket] += n
available_family[doc.source_family] += n
bucket_target = {
bucket: int(total_target * weight)
for bucket, weight in weights.items()
}
bucket_probability = {
bucket: min(1.0, bucket_target[bucket] / max(1, available_bucket[bucket]))
for bucket in weights
}
default_family_cap = float(cfg["max_source_family_share"])
family_caps = cfg.get("source_family_caps", {})
expected_family = Counter()
for doc in iter_jsonl(CURATED):
expected_family[doc.source_family] += (
len(doc.text) * bucket_probability.get(doc.bucket, 0.0)
)
family_multiplier = {}
for family, expected in expected_family.items():
share_cap = float(family_caps.get(family, default_family_cap))
char_cap = total_target * share_cap
family_multiplier[family] = min(1.0, char_cap / max(1.0, expected))
written_bucket = Counter()
written_family = Counter()
docs_written = 0
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
with OUTPUT.open("w", encoding="utf-8") as out:
for doc in iter_jsonl(CURATED):
p = bucket_probability.get(doc.bucket, 0.0)
p *= family_multiplier.get(doc.source_family, 1.0)
if deterministic_fraction(seed, doc.id) > p:
continue
target = bucket_target.get(doc.bucket, 0)
if written_bucket[doc.bucket] >= target:
continue
out.write(doc.text)
out.write("\n\n")
n = len(doc.text)
written_bucket[doc.bucket] += n
written_family[doc.source_family] += n
docs_written += 1
report = {
"documents": docs_written,
"characters": sum(written_bucket.values()),
"bucket_characters": dict(written_bucket),
"family_characters": dict(written_family),
"bucket_targets": bucket_target,
}
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(report, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
|