"""Build the pinyin-conditioned stores for the zh three-task model (stage 1). Selection train: web/review documents in P1 (zh13 pools.json, label zh-v13-pool) outside the memorization probe, plus LCCC train utterances; without pools_path (export-r2, which has neither pools nor the probe) every train document is eligible, and a missing LCCC file is skipped; validation: every export validation document and LCCC validation utterance. u = doc_hash(label, id) / 2**64 (chat key "lccc//"): u < plain_fraction -> plain, the next pinyin_fraction -> pinyin. Disjoint documents feed the two, so no paragraph is in both. chat_pinyin_repeats (default 1) gives each train chat utterance that many pinyin samples, seeds "#r". Stores (one directory each under output_dir) plain BOS + paragraph + EOS cut into <=128-token windows, every target supervised (first = 1); windows shorter than plain_minimum_tokens are dropped full, mixed, initials, error [2,4]+context+[5]+keys+[6]+output+[3], first = index of the first output token; one sample per simplified paragraph or utterance, kind drawn from kind_weights (a paragraph holding a listed misreading becomes an error sample around it with listed_boost_probability) Typo mode (mode = "typo", configs/data-zh-pinyin-typo.toml) one store, typo: the same documents and paragraphs as the pinyin stores of the same label and fractions (plain documents are skipped), each paragraph a full (typo.full_share) or mixed sample whose keys carry one or two keyboard typos (zh_typo), the output still the correct text. Seeds "#typo", so the pinyin samples of the same paragraphs are not reproduced. Layout and format as the other pinyin stores. Files per store and split: {split}.tokens.bin ( 0 for name in info.get("errors", ()): stats[f"error_source_{name}"] += 1 if kind == "error": stats[f"error_base_{info['base']}"] += 1 stats[f"error_count_{len(info['errors'])}"] += 1 def _typo(part, stats, rng, text): config, pinyin, sp = _state["config"], _state["pinyin"], _state["sp"] typo = config["typo"] base = "full" if rng.random() < typo["full_share"] else "mixed" sample = pinyin.sample(rng, text, base) if sample is None: stats[f"skip_{base}"] += 1 return context, keys, output, info = sample edited = add_typos(rng, keys, info["units"], typo) if edited is None: stats["skip_typo_edit"] += 1 return keys, edits = edited encoded = encode(sp, context, keys, output) if encoded is None: stats["skip_encode_typo"] += 1 return ids, first, removed = encoded part.add("typo", ids, first) stats["typo_tokens"] += len(ids) stats["typo_output_chars"] += len(output) stats["typo_output_tokens"] += len(ids) - first - 1 stats["typo_context_tokens"] += ids.index(5) - 2 stats["typo_empty_context"] += ids.index(5) == 2 stats["typo_context_trimmed"] += removed > 0 stats[f"typo_base_{base}"] += 1 stats[f"typo_count_{len(edits)}"] += 1 for edit in edits: stats[f"typo_edit_{edit}"] += 1 if base == "full": stats["typo_full_valid_pinyin" if full_pinyin(keys, pinyin.valid) else "typo_full_invalid_pinyin"] += 1 def run_job(job): import pyarrow.parquet as pq config, sp, pools = _state["config"], _state["sp"], _state["pools"] split, source = job["split"], source_of(job["path"]) label = config["label"] if split == "train": plain_fraction = config["chat_plain_fraction" if source == "chat" else "web_plain_fraction"] pinyin_fraction = config["chat_pinyin_fraction" if source == "chat" else "web_pinyin_fraction"] else: plain_fraction = config["validation_chat_plain_fraction" if source == "chat" else "validation_plain_fraction"] pinyin_fraction = config["validation_chat_pinyin_fraction" if source == "chat" else "validation_pinyin_fraction"] repeats = config.get("chat_pinyin_repeats", 1) if split == "train" and source == "chat" else 1 plain_cut = int(plain_fraction * 2 ** 64) pinyin_cut = int((plain_fraction + pinyin_fraction) * 2 ** 64) if pools: thresholds, memo_threshold = pools["thresholds"], pools["memo_threshold"] pool_label, memo_label = pools["labels"]["pool"], pools["labels"]["memo"] typo = config.get("mode") == "typo" part, stats = Part(stores_of(config)), Counter() handle = pq.ParquetFile(job["path"]) columns = ["text", "dialogue", "turn", "script"] if source == "chat" else ["id", "text", "script"] for group in range(*job["groups"]): table = handle.read_row_group(group, columns=columns).to_pydict() if source == "chat": keys = [f"lccc/{d}/{t}" for d, t in zip(table["dialogue"], table["turn"])] else: keys = table["id"] for key, text, script in zip(keys, table["text"], table["script"]): stats["documents_seen"] += 1 if pools and split == "train" and source != "chat": h = doc_hash(pool_label, key) if h >= thresholds["p1"]: continue if h < thresholds["p20"] and doc_hash(memo_label, key) < memo_threshold: stats["probe_excluded"] += 1 continue u = doc_hash(label, key) if u >= pinyin_cut: continue if source == "chat": text = text.strip() if not text or META_SPACE in text: continue paragraphs = [text] else: paragraphs, _ = clean_paragraphs(text) if typo: if u < plain_cut: continue if script != "hans": stats["pinyin_skipped_hant_documents"] += 1 continue stats["pinyin_documents"] += 1 rng = random.Random(doc_hash(label + "/rng", f"{key}#typo")) for paragraph in paragraphs: stats["pinyin_paragraphs"] += 1 _typo(part, stats, rng, paragraph) continue rng = random.Random(doc_hash(label + "/rng", key)) if u < plain_cut: stats["plain_documents"] += 1 for paragraph in paragraphs: _plain(part, stats, sp, paragraph, config["plain_minimum_tokens"]) elif script == "hans": stats["pinyin_documents"] += 1 for paragraph in paragraphs: stats["pinyin_paragraphs"] += 1 _pinyin(part, stats, rng, paragraph) # chat_pinyin_repeats > 1 draws extra samples per train utterance, each from its own seed for r in range(1, repeats): extra = random.Random(doc_hash(label + "/rng", f"{key}#{r}")) for paragraph in paragraphs: stats["pinyin_repeat_paragraphs"] += 1 _pinyin(part, stats, extra, paragraph) else: stats["pinyin_skipped_hant_documents"] += 1 part.save(Path(config["parts_dir"]) / job["name"]) counts = {s: len(part.lengths[s]) for s in part.stores} return job["name"], source, counts, dict(stats) def merge(parts_dir, names, output_dir, split, stores=STORES): result = {} for store in stores: directory = Path(output_dir) / store directory.mkdir(parents=True, exist_ok=True) lengths = [np.fromfile(Path(parts_dir) / n / f"{store}.lengths.bin", dtype="u1") for n in names] lengths = np.concatenate(lengths).astype("