Buckets:
| """Deterministic, 9-Family-Fold language-normalized code proxy bucket builder. | |
| Builds small, pre-shuffled, reproducible code proxy buckets (`3.0B` DeepSeek-V3 tokens | |
| each: `2.85B` train + `150M` holdout) normalized to NVIDIA's Nemotron 3.5 Lightning | |
| midtraining language blend (Paper 77, Appendix A.2 Table 12) using the Zero-Skew | |
| 9-Family Fold (JS+TS folded, C+C++ folded so Python is locked at 28.48% across every | |
| corpus including UltraData-Code L2) + 10.05% random tail. | |
| Every shard stores BOTH clean `text` AND pre-tokenized DeepSeek-V3 `tokens_u32` (uint32) | |
| in `hf://buckets/ahnaftaz/locus2-proxy-code-v1/<corpus>/`, making every proxy bucket | |
| 100% architecture-independent (Locus-1 89M today; Locus-2 R0/R1/R2 rungs tomorrow). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| import random | |
| import tempfile | |
| import time | |
| from collections import defaultdict | |
| from dataclasses import asdict, dataclass | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any, Iterator | |
| # Exact Nemotron 3.5 Lightning Midtraining Table 12 (p. 15) blend weights (sum = 100.0%). | |
| NEMOTRON_TABLE12_BLEND_PCT: dict[str, float] = { | |
| "Python": 31.0, | |
| "Java": 17.0, | |
| "TypeScript": 12.0, | |
| "C#": 10.0, | |
| "JavaScript": 8.6, | |
| "C++": 7.6, | |
| "PHP": 4.7, | |
| "C": 2.7, | |
| "Rust": 1.9, | |
| "Go": 1.5, | |
| "Dart": 1.4, | |
| "Ruby": 0.9, | |
| "Scala": 0.4, | |
| "Lua": 0.3, | |
| } | |
| # Zero-Skew 9-Family Fold: folds (JavaScript + TypeScript) and (C + C++) into shared | |
| # families so UltraData-Code L2 (which has js & cpp without separate ts/c folders) gets | |
| # the EXACT same 28.48% Python share as Stack-v3-train, Locus-2 PT, and StarCoderData. | |
| # Sum of the 9 families in Table 12 = 97.9% -> scaled to 89.95% core + 10.05% random tail. | |
| NINE_FAMILY_FOLD_PCT: dict[str, float] = { | |
| "Python": 28.48, | |
| "JS+TS": 18.92, # Table 12: 8.6 JS + 12.0 TS = 20.6 | |
| "Java": 15.62, | |
| "C+C++": 9.46, # Table 12: 2.7 C + 7.6 C++ = 10.3 | |
| "C#": 9.19, | |
| "PHP": 4.32, | |
| "Rust": 1.75, | |
| "Go": 1.38, | |
| "Ruby": 0.83, | |
| "__TAIL__": 10.05, | |
| } | |
| FAMILY_SUBLANG_SPLITS: dict[str, dict[str, float]] = { | |
| "JS+TS": {"JavaScript": 8.6 / 20.6, "TypeScript": 12.0 / 20.6}, | |
| "C+C++": {"C": 2.7 / 10.3, "C++": 7.6 / 10.3}, | |
| } | |
| DEFAULT_SEED = 20261123 | |
| DEFAULT_TOTAL_TOKENS = 3_000_000_000 # 3.0B DeepSeek-V3 tokens per proxy bucket | |
| DEFAULT_HOLDOUT_FRACTION = 0.05 # 150M held-out tokens (5%) | |
| DEFAULT_TARGET_BUCKET = "ahnaftaz/locus2-proxy-code-v1" | |
| DEFAULT_TRAIN_SHARDS = 32 | |
| DEFAULT_HOLDOUT_SHARDS = 4 | |
| DEEPSEEK_V3_TOKENIZER = "deepseek-ai/DeepSeek-V3" | |
| LANGUAGE_ALIASES: dict[str, str] = { | |
| "py": "Python", | |
| "python": "Python", | |
| "java": "Java", | |
| "ts": "TypeScript", | |
| "tsx": "TypeScript", | |
| "typescript": "TypeScript", | |
| "cs": "C#", | |
| "csharp": "C#", | |
| "c-sharp": "C#", | |
| "c#": "C#", | |
| "js": "JavaScript", | |
| "jsx": "JavaScript", | |
| "javascript": "JavaScript", | |
| "cpp": "C++", | |
| "c++": "C++", | |
| "cxx": "C++", | |
| "cc": "C++", | |
| "php": "PHP", | |
| "c": "C", | |
| "rs": "Rust", | |
| "rust": "Rust", | |
| "go": "Go", | |
| "golang": "Go", | |
| "dart": "Dart", | |
| "rb": "Ruby", | |
| "ruby": "Ruby", | |
| "scala": "Scala", | |
| "lua": "Lua", | |
| "sh": "Shell", | |
| "shell": "Shell", | |
| "bash": "Shell", | |
| "r": "R", | |
| "sql": "SQL", | |
| "swift": "Swift", | |
| "kotlin": "Kotlin", | |
| "md": "Markdown", | |
| "markdown": "Markdown", | |
| } | |
| def canonical_language(raw: str) -> str: | |
| key = str(raw or "").strip().lower() | |
| return LANGUAGE_ALIASES.get(key, str(raw or "").strip()) | |
| def language_to_family(lang: str) -> str: | |
| canon = canonical_language(lang) | |
| if canon in ("JavaScript", "TypeScript"): | |
| return "JS+TS" | |
| if canon in ("C", "C++"): | |
| return "C+C++" | |
| if canon in NINE_FAMILY_FOLD_PCT and canon != "__TAIL__": | |
| return canon | |
| return "__TAIL__" | |
| class UpstreamCorpusSpec: | |
| slug: str | |
| display_name: str | |
| source_uri: str | |
| source_kind: str # "hf_bucket" | "hf_dataset_parquet" | "hf_dataset_subdir_parquet" | "hf_dataset_jsonl" | "hf_metadata_only" | |
| hf_repo_id: str | |
| subpath: str | |
| text_column: str | |
| lang_column: str | None | |
| has_separate_ts: bool | |
| has_separate_c: bool | |
| access_status: str | |
| notes: str = "" | |
| UPSTREAM_CORPORA: dict[str, UpstreamCorpusSpec] = { | |
| "locus2_pt_source_files": UpstreamCorpusSpec( | |
| slug="locus2_pt_source_files", | |
| display_name="Locus 2 PT Source Files v1 (Ours)", | |
| source_uri="hf://buckets/ahnaftaz/locus2-code-pt-source-files-v1", | |
| source_kind="hf_bucket", | |
| hf_repo_id="ahnaftaz/locus2-code-pt-source-files-v1", | |
| subpath="", | |
| text_column="text", | |
| lang_column="language", | |
| has_separate_ts=True, | |
| has_separate_c=True, | |
| access_status="open_ready", | |
| notes="Our Stack v3 Pipeline 2 C3-deduped source files (~3.03T DeepSeek-V3 tokens, 713 langs).", | |
| ), | |
| "stack_v3_train": UpstreamCorpusSpec( | |
| slug="stack_v3_train", | |
| display_name="The Stack v3 Train (HuggingFaceCode)", | |
| source_uri="hf://datasets/HuggingFaceCode/stack-v3-train", | |
| source_kind="hf_dataset_parquet", | |
| hf_repo_id="HuggingFaceCode/stack-v3-train", | |
| subpath="data", | |
| text_column="content", | |
| lang_column="language", | |
| has_separate_ts=True, | |
| has_separate_c=True, | |
| access_status="open_ready", | |
| notes="8,192 parquet shards (~4.9T tokens, 713 languages) with full source text directly in parquet.", | |
| ), | |
| "ultradata_code_l2": UpstreamCorpusSpec( | |
| slug="ultradata_code_l2", | |
| display_name="UltraData-Code L2 (OpenBMB)", | |
| source_uri="hf://datasets/openbmb/UltraData-Code/data/UltraData-Code-L2", | |
| source_kind="hf_dataset_subdir_parquet", | |
| hf_repo_id="openbmb/UltraData-Code", | |
| subpath="data/UltraData-Code-L2", | |
| text_column="content", | |
| lang_column=None, | |
| has_separate_ts=False, | |
| has_separate_c=False, | |
| access_status="open_ready", | |
| notes="OpenBMB algorithmic L2 curated source files (~400B tokens, 11 language folders, full content).", | |
| ), | |
| "ultradata_code_l3": UpstreamCorpusSpec( | |
| slug="ultradata_code_l3", | |
| display_name="UltraData-Code L3 (OpenBMB Task+Solution)", | |
| source_uri="hf://datasets/openbmb/UltraData-Code/data/UltraData-Code-L3", | |
| source_kind="hf_dataset_subdir_parquet", | |
| hf_repo_id="openbmb/UltraData-Code", | |
| subpath="data/UltraData-Code-L3", | |
| text_column="content", | |
| lang_column=None, | |
| has_separate_ts=False, | |
| has_separate_c=False, | |
| access_status="open_ready", | |
| notes="OpenBMB L3 synthetic exercises using Paper 107 winning Task+Solution `content` serialization (50/25/25 comment/no-fence/md).", | |
| ), | |
| "starcoderdata": UpstreamCorpusSpec( | |
| slug="starcoderdata", | |
| display_name="BigCode StarCoderData", | |
| source_uri="hf://datasets/bigcode/starcoderdata", | |
| source_kind="hf_dataset_subdir_parquet", | |
| hf_repo_id="bigcode/starcoderdata", | |
| subpath="", | |
| text_column="content", | |
| lang_column=None, | |
| has_separate_ts=True, | |
| has_separate_c=True, | |
| access_status="open_ready", | |
| notes="86 language folders (~250B tokens) with full content in parquet (unlocked).", | |
| ), | |
| "locus1_code_v2": UpstreamCorpusSpec( | |
| slug="locus1_code_v2", | |
| display_name="Locus 1 Code Pool v2 (Historical)", | |
| source_uri="hf://datasets/placeholderlabs/locus-repo-code-pool-v2", | |
| source_kind="hf_dataset_jsonl", | |
| hf_repo_id="placeholderlabs/locus-repo-code-pool-v2", | |
| subpath="shards", | |
| text_column="payload", | |
| lang_column="annotations.programming_languages", | |
| has_separate_ts=True, | |
| has_separate_c=True, | |
| access_status="open_ready", | |
| notes="Historical Locus-1 code pool (called repository in Locus-1).", | |
| ), | |
| "nemotron_pretraining_code_v3": UpstreamCorpusSpec( | |
| slug="nemotron_pretraining_code_v3", | |
| display_name="NVIDIA Nemotron-Pretraining-Code-v3", | |
| source_uri="hf://datasets/nvidia/Nemotron-Pretraining-Code-v3", | |
| source_kind="hf_metadata_only", | |
| hf_repo_id="nvidia/Nemotron-Pretraining-Code-v3", | |
| subpath="Nemotron-Code-Metadata", | |
| text_column="content", | |
| lang_column="language", | |
| has_separate_ts=True, | |
| has_separate_c=True, | |
| access_status="metadata_hydrate_via_stack_v3", | |
| notes="64 metadata parquet shards (repo, rel_path, language, commit_id); requires join/hydration against Stack v3 or GitHub.", | |
| ), | |
| } | |
| def compute_nine_family_quotas( | |
| *, | |
| total_tokens: int = DEFAULT_TOTAL_TOKENS, | |
| has_separate_ts: bool = True, | |
| has_separate_c: bool = True, | |
| ) -> dict[str, int]: | |
| """Compute exact per-bucket DeepSeek-V3 token quotas under the Zero-Skew 9-Family Fold. | |
| Every corpus gets IDENTICAL family shares (Python = 28.48%, JS+TS = 18.92%, | |
| Java = 15.62%, C+C++ = 9.46%, C# = 9.19%, PHP = 4.32%, Rust = 1.75%, | |
| Go = 1.38%, Ruby = 0.83%, __TAIL__ = 10.05%). | |
| Corpora that separate JS/TS or C/C++ split those families in exact Nemotron Table 12 ratios. | |
| """ | |
| family_keys = list(NINE_FAMILY_FOLD_PCT.keys()) | |
| fam_quotas: dict[str, int] = {} | |
| assigned = 0 | |
| for idx, fam in enumerate(family_keys): | |
| if idx == len(family_keys) - 1: | |
| q = total_tokens - assigned | |
| else: | |
| q = int(round(total_tokens * (NINE_FAMILY_FOLD_PCT[fam] / 100.0))) | |
| fam_quotas[fam] = q | |
| assigned += q | |
| quotas: dict[str, int] = {} | |
| for fam, q in fam_quotas.items(): | |
| if fam == "JS+TS" and has_separate_ts: | |
| js_q = int(round(q * FAMILY_SUBLANG_SPLITS["JS+TS"]["JavaScript"])) | |
| quotas["JavaScript"] = js_q | |
| quotas["TypeScript"] = q - js_q | |
| elif fam == "JS+TS": | |
| quotas["JavaScript"] = q | |
| elif fam == "C+C++" and has_separate_c: | |
| c_q = int(round(q * FAMILY_SUBLANG_SPLITS["C+C++"]["C"])) | |
| quotas["C"] = c_q | |
| quotas["C++"] = q - c_q | |
| elif fam == "C+C++": | |
| quotas["C++"] = q | |
| else: | |
| quotas[fam] = q | |
| assert sum(quotas.values()) == total_tokens, (sum(quotas.values()), total_tokens) | |
| return quotas | |
| def deterministic_doc_rank(seed: int, corpus: str, language: str, doc_id: str) -> int: | |
| digest = hashlib.blake2b( | |
| f"{seed}:{corpus}:{language}:{doc_id}".encode("utf-8"), | |
| digest_size=8, | |
| ).digest() | |
| return int.from_bytes(digest, "big") | |
| def is_holdout_doc( | |
| seed: int, | |
| corpus: str, | |
| doc_id: str, | |
| holdout_fraction: float = DEFAULT_HOLDOUT_FRACTION, | |
| ) -> bool: | |
| digest = hashlib.blake2b( | |
| f"holdout:{seed}:{corpus}:{doc_id}".encode("utf-8"), | |
| digest_size=8, | |
| ).digest() | |
| bucket = int.from_bytes(digest, "big") % 10_000 | |
| return bucket < int(round(holdout_fraction * 10_000)) | |
| def build_plan_summary( | |
| corpora: list[str] | None = None, | |
| *, | |
| total_tokens: int = DEFAULT_TOTAL_TOKENS, | |
| ) -> dict[str, Any]: | |
| selected = corpora or list(UPSTREAM_CORPORA.keys()) | |
| plan: dict[str, Any] = { | |
| "generated_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), | |
| "fold_name": "code-proxy-9family-fold-v1", | |
| "target_bucket": f"hf://buckets/{DEFAULT_TARGET_BUCKET}", | |
| "tokenizer": DEEPSEEK_V3_TOKENIZER, | |
| "seed": DEFAULT_SEED, | |
| "total_tokens_per_bucket": total_tokens, | |
| "train_tokens_per_bucket": int(round(total_tokens * (1.0 - DEFAULT_HOLDOUT_FRACTION))), | |
| "holdout_tokens_per_bucket": int(round(total_tokens * DEFAULT_HOLDOUT_FRACTION)), | |
| "nine_family_fold_pct": dict(NINE_FAMILY_FOLD_PCT), | |
| "corpora": {}, | |
| } | |
| for slug in selected: | |
| spec = UPSTREAM_CORPORA[slug] | |
| quotas = compute_nine_family_quotas( | |
| total_tokens=total_tokens, | |
| has_separate_ts=spec.has_separate_ts, | |
| has_separate_c=spec.has_separate_c, | |
| ) | |
| plan["corpora"][slug] = { | |
| **asdict(spec), | |
| "quotas_tokens": quotas, | |
| "quotas_pct": {k: round(100.0 * v / total_tokens, 2) for k, v in quotas.items()}, | |
| "est_disk_gb": round((total_tokens / 1e9) * 1.15, 2), | |
| } | |
| return plan | |
| # --------------------------------------------------------------------------- | |
| # Streaming HF Job Builder (runs on `cpu-upgrade` pod inside HF datacenter) | |
| # --------------------------------------------------------------------------- | |
| def _load_deepseek_v3_tokenizer(): | |
| from transformers import AutoTokenizer | |
| tok = AutoTokenizer.from_pretrained(DEEPSEEK_V3_TOKENIZER, use_fast=True) | |
| return tok | |
| def _bucket_key_for_lang(lang: str, quotas: dict[str, int]) -> str: | |
| canon = canonical_language(lang) | |
| if canon in quotas: | |
| return canon | |
| # Fold into combined family if corpus doesn't split JS/TS or C/C++ | |
| if canon == "TypeScript" and "JavaScript" in quotas: | |
| return "JavaScript" | |
| if canon == "C" and "C++" in quotas: | |
| return "C++" | |
| return "__TAIL__" | |
| def _iter_subdir_parquet( | |
| spec: UpstreamCorpusSpec, | |
| quotas: dict[str, int], | |
| filled: dict[str, int], | |
| rng: random.Random, | |
| ) -> Iterator[tuple[str, str, str, str]]: | |
| """Yield `(doc_id, canon_lang, bucket_key, text)` round-robin across language folders.""" | |
| import pyarrow.parquet as pq | |
| from huggingface_hub import HfApi, HfFileSystem | |
| api = HfApi() | |
| fs = HfFileSystem() | |
| top = list( | |
| api.list_repo_tree( | |
| spec.hf_repo_id, | |
| path_in_repo=spec.subpath or None, | |
| repo_type="dataset", | |
| recursive=False, | |
| ) | |
| ) | |
| # Map bucket_key -> list of (canon_lang, parquet_path) | |
| by_bucket: dict[str, list[tuple[str, str]]] = defaultdict(list) | |
| for entry in top: | |
| name = entry.path.split("/")[-1] | |
| if name.startswith(".") or name.endswith(".md") or name in ("assets", "tech_report", "LICENSE"): | |
| continue | |
| canon = canonical_language(name) | |
| bkey = _bucket_key_for_lang(canon, quotas) | |
| sub_items = list( | |
| api.list_repo_tree( | |
| spec.hf_repo_id, | |
| path_in_repo=entry.path, | |
| repo_type="dataset", | |
| recursive=False, | |
| ) | |
| ) | |
| for item in sub_items: | |
| if item.path.endswith(".parquet"): | |
| by_bucket[bkey].append((canon, item.path)) | |
| for bkey, pairs in by_bucket.items(): | |
| rng.shuffle(pairs) | |
| print(f"[proxy-build] {spec.slug} bucket={bkey:12s} shards={len(pairs)}", flush=True) | |
| # Emit bucket by bucket so each language fills its exact quota fast! | |
| for bkey in list(quotas.keys()): | |
| if filled[bkey] >= quotas[bkey]: | |
| continue | |
| pairs = by_bucket.get(bkey, []) | |
| if not pairs: | |
| continue | |
| for canon, pq_path in pairs: | |
| if filled[bkey] >= quotas[bkey]: | |
| break | |
| hf_path = f"datasets/{spec.hf_repo_id}/{pq_path}" | |
| try: | |
| with fs.open(hf_path, "rb") as f: | |
| pf = pq.ParquetFile(f) | |
| cols = [spec.text_column] | |
| id_col = None | |
| for cand in ("uuid", "id", "blob_id", "content_id"): | |
| if cand in pf.schema.names: | |
| id_col = cand | |
| cols.append(cand) | |
| break | |
| rg_indices = list(range(pf.num_row_groups)) | |
| rng.shuffle(rg_indices) | |
| for rg in rg_indices: | |
| if filled[bkey] >= quotas[bkey]: | |
| break | |
| tbl = pf.read_row_group(rg, columns=cols) | |
| texts = tbl[spec.text_column].to_pylist() | |
| ids = tbl[id_col].to_pylist() if id_col else None | |
| order = list(range(len(texts))) | |
| rng.shuffle(order) | |
| for idx in order: | |
| if filled[bkey] >= quotas[bkey]: | |
| break | |
| txt = texts[idx] | |
| if not txt or not isinstance(txt, str): | |
| continue | |
| doc_id = str(ids[idx]) if ids is not None else f"{pq_path}:{rg}:{idx}" | |
| yield doc_id, canon, bkey, txt | |
| except Exception as exc: | |
| print(f"[proxy-build] warn reading {pq_path}: {exc}", flush=True) | |
| continue | |
| def _iter_flat_parquet( | |
| spec: UpstreamCorpusSpec, | |
| quotas: dict[str, int], | |
| rng: random.Random, | |
| ) -> Iterator[tuple[str, str, str, str]]: | |
| """Stream deterministically shuffled shards from flat parquet datasets like stack-v3-train.""" | |
| import pyarrow.parquet as pq | |
| from huggingface_hub import HfApi, HfFileSystem | |
| api = HfApi() | |
| fs = HfFileSystem() | |
| items = list( | |
| api.list_repo_tree( | |
| spec.hf_repo_id, | |
| path_in_repo=spec.subpath or None, | |
| repo_type="dataset", | |
| recursive=False, | |
| ) | |
| ) | |
| shards = [i.path for i in items if i.path.endswith(".parquet")] | |
| rng.shuffle(shards) | |
| print(f"[proxy-build] {spec.slug} total_shards={len(shards)}", flush=True) | |
| for pq_path in shards: | |
| hf_path = f"datasets/{spec.hf_repo_id}/{pq_path}" | |
| try: | |
| with fs.open(hf_path, "rb") as f: | |
| pf = pq.ParquetFile(f) | |
| top_names = set(pf.schema_arrow.names) | |
| if "files" in top_names: | |
| # Nested repo-grouped parquet (e.g., HuggingFaceCode/stack-v3-train) | |
| rg_indices = list(range(pf.num_row_groups)) | |
| rng.shuffle(rg_indices) | |
| for rg in rg_indices: | |
| tbl = pf.read_row_group(rg, columns=["files"]) | |
| repos_files = tbl["files"].to_pylist() | |
| order = list(range(len(repos_files))) | |
| rng.shuffle(order) | |
| for idx in order: | |
| file_list = repos_files[idx] or [] | |
| for f_idx, fobj in enumerate(file_list): | |
| if not isinstance(fobj, dict): | |
| continue | |
| txt = fobj.get(spec.text_column) | |
| if not txt or not isinstance(txt, str): | |
| continue | |
| canon = canonical_language(fobj.get(spec.lang_column or "language") or "unknown") | |
| bkey = _bucket_key_for_lang(canon, quotas) | |
| doc_id = str(fobj.get("content_id") or f"{pq_path}:{rg}:{idx}:{f_idx}") | |
| yield doc_id, canon, bkey, txt | |
| else: | |
| cols = [spec.text_column, spec.lang_column] | |
| id_col = None | |
| for cand in ("content_id", "uuid", "id", "blob_id"): | |
| if cand in top_names: | |
| id_col = cand | |
| cols.append(cand) | |
| break | |
| rg_indices = list(range(pf.num_row_groups)) | |
| rng.shuffle(rg_indices) | |
| for rg in rg_indices: | |
| tbl = pf.read_row_group(rg, columns=[c for c in cols if c]) | |
| texts = tbl[spec.text_column].to_pylist() | |
| langs = tbl[spec.lang_column].to_pylist() if spec.lang_column else ["unknown"] * len(texts) | |
| ids = tbl[id_col].to_pylist() if id_col else None | |
| order = list(range(len(texts))) | |
| rng.shuffle(order) | |
| for idx in order: | |
| txt = texts[idx] | |
| if not txt or not isinstance(txt, str): | |
| continue | |
| canon = canonical_language(langs[idx]) | |
| bkey = _bucket_key_for_lang(canon, quotas) | |
| doc_id = str(ids[idx]) if ids is not None else f"{pq_path}:{rg}:{idx}" | |
| yield doc_id, canon, bkey, txt | |
| except Exception as exc: | |
| print(f"[proxy-build] warn reading {pq_path}: {exc}", flush=True) | |
| continue | |
| def _iter_jsonl_dataset( | |
| spec: UpstreamCorpusSpec, | |
| quotas: dict[str, int], | |
| rng: random.Random, | |
| ) -> Iterator[tuple[str, str, str, str]]: | |
| """Stream deterministically shuffled JSONL shards (e.g., locus-repo-code-pool-v2).""" | |
| from huggingface_hub import HfApi, HfFileSystem | |
| api = HfApi() | |
| fs = HfFileSystem() | |
| items = list( | |
| api.list_repo_tree( | |
| spec.hf_repo_id, | |
| path_in_repo=spec.subpath or None, | |
| repo_type="dataset", | |
| recursive=True, | |
| ) | |
| ) | |
| shards = [i.path for i in items if i.path.endswith(".jsonl")] | |
| rng.shuffle(shards) | |
| print(f"[proxy-build] {spec.slug} jsonl_shards={len(shards)}", flush=True) | |
| for jpath in shards: | |
| try: | |
| with fs.open(f"datasets/{spec.hf_repo_id}/{jpath}", "r", encoding="utf-8") as f: | |
| for line_no, line in enumerate(f): | |
| if not line.strip(): | |
| continue | |
| row = json.loads(line) | |
| txt = row.get(spec.text_column) | |
| if not txt or not isinstance(txt, str): | |
| continue | |
| ann = row.get("annotations") or {} | |
| langs = ann.get("programming_languages") or ["unknown"] | |
| raw_lang = langs[0] if isinstance(langs, list) and langs else str(langs) | |
| canon = canonical_language(raw_lang) | |
| bkey = _bucket_key_for_lang(canon, quotas) | |
| doc_id = str(row.get("id") or f"{jpath}:{line_no}") | |
| yield doc_id, canon, bkey, txt | |
| except Exception as exc: | |
| print(f"[proxy-build] warn reading {jpath}: {exc}", flush=True) | |
| continue | |
| def _iter_hf_bucket_pt( | |
| spec: UpstreamCorpusSpec, | |
| quotas: dict[str, int], | |
| filled: dict[str, int], | |
| rng: random.Random, | |
| ) -> Iterator[tuple[str, str, str, str]]: | |
| """Stream deterministically shuffled shards from our `locus2-code-pt-source-files-v1` HF Bucket.""" | |
| import pyarrow.parquet as pq | |
| from huggingface_hub import HfApi | |
| api = HfApi() | |
| by_bucket: dict[str, list[tuple[str, str]]] = defaultdict(list) | |
| for entry in api.list_bucket_tree(spec.hf_repo_id, recursive=True): | |
| path = getattr(entry, "path", "") | |
| if not path.endswith(".parquet"): | |
| continue | |
| parts = path.split("/") | |
| raw_lang = parts[1] if len(parts) >= 3 and parts[0] == "data" else parts[0] | |
| canon = canonical_language(raw_lang) | |
| bkey = _bucket_key_for_lang(canon, quotas) | |
| by_bucket[bkey].append((canon, path)) | |
| for bkey, pairs in by_bucket.items(): | |
| rng.shuffle(pairs) | |
| print(f"[proxy-build] {spec.slug} bucket={bkey:12s} shards={len(pairs)}", flush=True) | |
| with tempfile.TemporaryDirectory(prefix="pt_cache_") as tmp: | |
| for bkey in list(quotas.keys()): | |
| if filled[bkey] >= quotas[bkey]: | |
| continue | |
| for canon, bpath in by_bucket.get(bkey, []): | |
| if filled[bkey] >= quotas[bkey]: | |
| break | |
| local_pq = Path(tmp) / "shard.parquet" | |
| try: | |
| api.download_bucket_files(spec.hf_repo_id, files=[(bpath, str(local_pq))]) | |
| pf = pq.ParquetFile(local_pq) | |
| text_col = "text" if "text" in pf.schema.names else "content" | |
| id_col = "content_id" if "content_id" in pf.schema.names else ( | |
| "doc_id" if "doc_id" in pf.schema.names else None | |
| ) | |
| for rg in range(pf.num_row_groups): | |
| tbl = pf.read_row_group(rg, columns=[c for c in (text_col, id_col) if c]) | |
| texts = tbl[text_col].to_pylist() | |
| ids = tbl[id_col].to_pylist() if id_col else None | |
| order = list(range(len(texts))) | |
| rng.shuffle(order) | |
| for idx in order: | |
| txt = texts[idx] | |
| if not txt or not isinstance(txt, str): | |
| continue | |
| doc_id = str(ids[idx]) if ids is not None else f"{bpath}:{rg}:{idx}" | |
| yield doc_id, canon, bkey, txt | |
| except Exception as exc: | |
| print(f"[proxy-build] warn reading {bpath}: {exc}", flush=True) | |
| finally: | |
| if local_pq.exists(): | |
| local_pq.unlink() | |
| def build_proxy_bucket_for_corpus( | |
| corpus_slug: str, | |
| *, | |
| total_tokens: int = DEFAULT_TOTAL_TOKENS, | |
| seed: int = DEFAULT_SEED, | |
| target_bucket: str = DEFAULT_TARGET_BUCKET, | |
| train_shards: int = DEFAULT_TRAIN_SHARDS, | |
| holdout_shards: int = DEFAULT_HOLDOUT_SHARDS, | |
| batch_size: int = 256, | |
| ) -> dict[str, Any]: | |
| """Stream, normalize to 9-Family Fold, tokenize (DeepSeek-V3), shard, and upload to HF Bucket.""" | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from huggingface_hub import HfApi | |
| spec = UPSTREAM_CORPORA[corpus_slug] | |
| if spec.source_kind == "hf_metadata_only": | |
| raise RuntimeError( | |
| f"{corpus_slug} is metadata-only ({spec.hf_repo_id}); hydrate via Stack-v3 join first." | |
| ) | |
| t0 = time.monotonic() | |
| quotas = compute_nine_family_quotas( | |
| total_tokens=total_tokens, | |
| has_separate_ts=spec.has_separate_ts, | |
| has_separate_c=spec.has_separate_c, | |
| ) | |
| filled: dict[str, int] = {k: 0 for k in quotas} | |
| realized_by_lang: dict[str, int] = defaultdict(int) | |
| docs_by_lang: dict[str, int] = defaultdict(int) | |
| print( | |
| f"[proxy-build] Starting {corpus_slug} | target={total_tokens:,} DeepSeek-V3 tokens " | |
| f"| bucket={target_bucket}/{corpus_slug} | seed={seed}", | |
| flush=True, | |
| ) | |
| tokenizer = _load_deepseek_v3_tokenizer() | |
| rng = random.Random(seed) | |
| schema = pa.schema( | |
| [ | |
| ("doc_id", pa.string()), | |
| ("corpus", pa.string()), | |
| ("language", pa.string()), | |
| ("family", pa.string()), | |
| ("text", pa.string()), | |
| ("ds_v3_tokens", pa.int32()), | |
| ("tokens_u32", pa.list_(pa.uint32())), | |
| ] | |
| ) | |
| out_dir = Path(tempfile.mkdtemp(prefix=f"proxy_{corpus_slug}_")) | |
| (out_dir / "train").mkdir(parents=True, exist_ok=True) | |
| (out_dir / "holdout").mkdir(parents=True, exist_ok=True) | |
| train_writers = [ | |
| pq.ParquetWriter(out_dir / "train" / f"shard_{i:05d}.parquet", schema, compression="zstd") | |
| for i in range(train_shards) | |
| ] | |
| holdout_writers = [ | |
| pq.ParquetWriter(out_dir / "holdout" / f"shard_{i:05d}.parquet", schema, compression="zstd") | |
| for i in range(holdout_shards) | |
| ] | |
| train_bufs: list[dict[str, list[Any]]] = [ | |
| {name: [] for name in schema.names} for _ in range(train_shards) | |
| ] | |
| holdout_bufs: list[dict[str, list[Any]]] = [ | |
| {name: [] for name in schema.names} for _ in range(holdout_shards) | |
| ] | |
| def _flush_buf(buf: dict[str, list[Any]], writer: pq.ParquetWriter) -> None: | |
| if not buf["doc_id"]: | |
| return | |
| writer.write_table(pa.Table.from_pydict(buf, schema=schema)) | |
| for k in buf: | |
| buf[k].clear() | |
| if spec.source_kind == "hf_bucket": | |
| stream = _iter_hf_bucket_pt(spec, quotas, filled, rng) | |
| elif spec.source_kind == "hf_dataset_subdir_parquet": | |
| stream = _iter_subdir_parquet(spec, quotas, filled, rng) | |
| elif spec.source_kind == "hf_dataset_parquet": | |
| stream = _iter_flat_parquet(spec, quotas, rng) | |
| elif spec.source_kind == "hf_dataset_jsonl": | |
| stream = _iter_jsonl_dataset(spec, quotas, rng) | |
| else: | |
| raise ValueError(f"Unsupported source_kind={spec.source_kind}") | |
| pending: list[tuple[str, str, str, str]] = [] | |
| train_tokens_total = 0 | |
| holdout_tokens_total = 0 | |
| train_docs_total = 0 | |
| holdout_docs_total = 0 | |
| last_log = time.monotonic() | |
| def _all_done() -> bool: | |
| return all(filled[k] >= quotas[k] for k in quotas) | |
| def _process_batch(batch: list[tuple[str, str, str, str]]) -> None: | |
| nonlocal train_tokens_total, holdout_tokens_total, train_docs_total, holdout_docs_total | |
| if not batch: | |
| return | |
| # Cap giant single files (>512 KB) to prevent tokenizer spikes on minified blobs | |
| texts = [item[3][:524_288] for item in batch] | |
| enc = tokenizer(texts, add_special_tokens=False, return_attention_mask=False)["input_ids"] | |
| for (doc_id, canon, bkey, txt), tok_ids in zip(batch, enc): | |
| n_tok = len(tok_ids) | |
| if n_tok == 0 or filled[bkey] >= quotas[bkey]: | |
| continue | |
| filled[bkey] += n_tok | |
| realized_by_lang[canon] += n_tok | |
| docs_by_lang[canon] += 1 | |
| fam = language_to_family(canon) | |
| rank = deterministic_doc_rank(seed, corpus_slug, canon, doc_id) | |
| if is_holdout_doc(seed, corpus_slug, doc_id): | |
| sidx = rank % holdout_shards | |
| buf = holdout_bufs[sidx] | |
| writer = holdout_writers[sidx] | |
| holdout_tokens_total += n_tok | |
| holdout_docs_total += 1 | |
| else: | |
| sidx = rank % train_shards | |
| buf = train_bufs[sidx] | |
| writer = train_writers[sidx] | |
| train_tokens_total += n_tok | |
| train_docs_total += 1 | |
| buf["doc_id"].append(doc_id) | |
| buf["corpus"].append(corpus_slug) | |
| buf["language"].append(canon) | |
| buf["family"].append(fam) | |
| buf["text"].append(txt[:524_288]) | |
| buf["ds_v3_tokens"].append(n_tok) | |
| buf["tokens_u32"].append(tok_ids) | |
| if len(buf["doc_id"]) >= 256: | |
| _flush_buf(buf, writer) | |
| try: | |
| for doc_id, canon, bkey, txt in stream: | |
| if filled[bkey] >= quotas[bkey]: | |
| if _all_done(): | |
| break | |
| continue | |
| pending.append((doc_id, canon, bkey, txt)) | |
| if len(pending) >= batch_size: | |
| _process_batch(pending) | |
| pending.clear() | |
| now = time.monotonic() | |
| if now - last_log >= 20.0: | |
| tot = sum(filled.values()) | |
| pct = 100.0 * tot / max(total_tokens, 1) | |
| done_b = sum(1 for k in quotas if filled[k] >= quotas[k]) | |
| print( | |
| f"[proxy-build] {corpus_slug}: {tot/1e9:.3f}B/{total_tokens/1e9:.2f}B " | |
| f"({pct:.1f}%) | buckets_done={done_b}/{len(quotas)} | elapsed={now-t0:.0f}s", | |
| flush=True, | |
| ) | |
| last_log = now | |
| if _all_done(): | |
| break | |
| if pending and not _all_done(): | |
| _process_batch(pending) | |
| pending.clear() | |
| finally: | |
| for buf, w in zip(train_bufs, train_writers): | |
| _flush_buf(buf, w) | |
| w.close() | |
| for buf, w in zip(holdout_bufs, holdout_writers): | |
| _flush_buf(buf, w) | |
| w.close() | |
| total_realized = train_tokens_total + holdout_tokens_total | |
| manifest = { | |
| "fold_name": "code-proxy-9family-fold-v1", | |
| "corpus": corpus_slug, | |
| "display_name": spec.display_name, | |
| "source_uri": spec.source_uri, | |
| "tokenizer": DEEPSEEK_V3_TOKENIZER, | |
| "seed": seed, | |
| "target_tokens": total_tokens, | |
| "realized_tokens": total_realized, | |
| "train_tokens": train_tokens_total, | |
| "holdout_tokens": holdout_tokens_total, | |
| "train_docs": train_docs_total, | |
| "holdout_docs": holdout_docs_total, | |
| "train_shards": train_shards, | |
| "holdout_shards": holdout_shards, | |
| "quotas_tokens": quotas, | |
| "filled_by_bucket": filled, | |
| "realized_by_language_tokens": dict(sorted(realized_by_lang.items(), key=lambda kv: -kv[1])), | |
| "realized_by_language_docs": dict(sorted(docs_by_lang.items(), key=lambda kv: -kv[1])), | |
| "elapsed_seconds": round(time.monotonic() - t0, 1), | |
| "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), | |
| } | |
| manifest_path = out_dir / "MANIFEST.json" | |
| manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") | |
| # Upload shards + MANIFEST.json directly to HF Bucket | |
| api = HfApi() | |
| api.create_bucket(target_bucket, private=False, exist_ok=True) | |
| upload_pairs: list[tuple[str, str]] = [(str(manifest_path), f"{corpus_slug}/MANIFEST.json")] | |
| for p in sorted((out_dir / "train").glob("*.parquet")): | |
| upload_pairs.append((str(p), f"{corpus_slug}/train/{p.name}")) | |
| for p in sorted((out_dir / "holdout").glob("*.parquet")): | |
| upload_pairs.append((str(p), f"{corpus_slug}/holdout/{p.name}")) | |
| print( | |
| f"[proxy-build] Uploading {len(upload_pairs)} files to hf://buckets/{target_bucket}/{corpus_slug}/...", | |
| flush=True, | |
| ) | |
| api.batch_bucket_files(target_bucket, add=upload_pairs) | |
| print( | |
| f"[proxy-build] DONE {corpus_slug} | realized={total_realized/1e9:.3f}B tok " | |
| f"(train={train_tokens_total/1e9:.3f}B, holdout={holdout_tokens_total/1e9:.3f}B) " | |
| f"in {(time.monotonic()-t0)/60.0:.1f} min", | |
| flush=True, | |
| ) | |
| return manifest | |
| def main(argv: list[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser(description="9-Family Fold deterministic code proxy bucket builder") | |
| parser.add_argument("--plan", action="store_true", help="Print the full normalized sampling plan JSON and exit") | |
| parser.add_argument("--build", default=None, choices=sorted(UPSTREAM_CORPORA), help="Build & upload one corpus") | |
| parser.add_argument("--corpora", nargs="*", default=None, choices=sorted(UPSTREAM_CORPORA)) | |
| parser.add_argument("--tokens-b", type=float, default=3.0, help="Target DeepSeek-V3 tokens (billions) per bucket") | |
| parser.add_argument("--seed", type=int, default=DEFAULT_SEED) | |
| parser.add_argument("--target-bucket", default=DEFAULT_TARGET_BUCKET) | |
| parser.add_argument("--write-plan", default=None) | |
| args = parser.parse_args(argv) | |
| total_tokens = int(round(args.tokens_b * 1_000_000_000)) | |
| if args.build: | |
| build_proxy_bucket_for_corpus( | |
| args.build, | |
| total_tokens=total_tokens, | |
| seed=args.seed, | |
| target_bucket=args.target_bucket, | |
| ) | |
| return 0 | |
| plan = build_plan_summary(args.corpora, total_tokens=total_tokens) | |
| if args.write_plan: | |
| out = Path(args.write_plan) | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| out.write_text(json.dumps(plan, indent=2) + "\n", encoding="utf-8") | |
| if args.plan or not args.write_plan: | |
| print(json.dumps(plan, indent=2)) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |
Xet Storage Details
- Size:
- 35.5 kB
- Xet hash:
- 803b15868ba5dbfc2a12d0cdb609acc0f2cbd57cc495f1bf52b656e37df3d362
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.