Download scripts/nova.py from ml-intern-explorers/nova1-pretrain-20T: direct link, hf CLI and curl.
- Browser
- Download file 75 kB
-
https://huggingface.co/datasets/ml-intern-explorers/nova1-pretrain-20T/resolve/main/scripts/nova.py
- Command line
-
hf download hf://datasets/ml-intern-explorers/nova1-pretrain-20T/scripts/nova.py
-
curl -L -o nova.py https://huggingface.co/datasets/ml-intern-explorers/nova1-pretrain-20T/resolve/main/scripts/nova.py
75 kB
| #!/usr/bin/env python3 | |
| # ============================================================================== | |
| # nova.py β NOVA-1 ALL-IN-ONE: tokenizer training + data pipeline + launcher | |
| # | |
| # THREE MODES controlled by MODE env var: | |
| # | |
| # MODE=launch (default) β run locally, trains tokenizer as HF Job, | |
| # then launches 4 domain pipeline jobs | |
| # MODE=train_tokenizer β runs inside HF Job, trains + uploads tokenizer | |
| # MODE=worker β runs inside HF Job, streams/tokenizes/uploads data | |
| # | |
| # QUICK START: | |
| # 1. rotate your HF token at huggingface.co/settings/tokens (old one is exposed) | |
| # 2. set HF_TOKEN and HF_USER below | |
| # 3. pip install "huggingface_hub>=0.24.0" | |
| # 4. python nova.py | |
| # | |
| # that's literally it. script uploads itself, fires the jobs, polls status. | |
| # go touch grass. it'll be cooking for days. no cap. | |
| # ============================================================================== | |
| # /// script | |
| # requires-python = ">=3.11" | |
| # dependencies = [ | |
| # "datasets==2.21.0", | |
| # "tokenizers>=0.19.0", | |
| # "xxhash", | |
| # "numpy", | |
| # "huggingface_hub[hf_transfer]>=0.24.0", | |
| # ] | |
| # /// | |
| import os, gc, re, sys, json, time, threading | |
| from collections import defaultdict | |
| from pathlib import Path | |
| # ============================================================================== | |
| # βοΈ CONFIGURE THESE TWO LINES β everything else is automatic | |
| # ============================================================================== | |
| # ============================================================================== | |
| # replace the top config block in nova.py with this | |
| # ============================================================================== | |
| import os | |
| # ββ NO HARDCODED TOKENS. ever. this file gets uploaded to a public repo. ββββββ | |
| # set these as env vars locally before running, never paste them into the file | |
| HF_TOKEN = os.environ.get("HF_TOKEN") | |
| HF_USER = "ml-intern-explorers" | |
| REPO_NAME = os.environ.get("HF_REPO_NAME", "nova1-pretrain-20T") | |
| if not HF_TOKEN: | |
| raise RuntimeError( | |
| "HF_TOKEN not set. export it before running:\n" | |
| " export HF_TOKEN=hf_your_new_rotated_token\n" | |
| ) | |
| if not HF_USER: | |
| raise RuntimeError( | |
| "HF_USER not set. export it before running:\n" | |
| " export HF_USER=YourHFUsername\n" | |
| ) | |
| REPO_ID = f"{HF_USER}/{REPO_NAME}" # β created if it doesn't exist | |
| # ============================================================================== | |
| REPO_ID = f"{HF_USER}/{REPO_NAME}" | |
| MODE = os.environ.get("MODE", "launch") # launch | train_tokenizer | worker | |
| # ββ runtime env (set by launcher when submitting jobs) ββββββββββββββββββββββββ | |
| DOMAIN_FILTER = os.environ.get("DOMAIN_FILTER", "ALL") | |
| SHARD_ROWS = int(os.environ.get("SHARD_ROWS", "100000")) | |
| JOB_TIMEOUT_H = float(os.environ.get("JOB_TIMEOUT_H", "999999999")) | |
| # ββ hardware ββ CPU Performance: 32 vCPU / 256 GB RAM / 1024 GB disk / $1.90/hr | |
| # 4 parallel domain jobs = $7.60/hr total | |
| # $1,000 budget = ~131 hrs wall-clock across all 4 jobs simultaneously | |
| FLAVOR = "cpu-performance" | |
| # ββ pipeline constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| SEQ_LEN = 2048 | |
| TOKENIZE_BATCH = 512 | |
| DEFAULT_MAX_MINUTES_PER_DATASET = 240 | |
| INSTRUCT_MAX_MINUTES = 60 | |
| BIG_MAX_MINUTES = 999_999 | |
| DOMAIN_TOKEN_BUDGETS = { | |
| "code": 8_000_000_000_000, # 8T priority 1 | |
| "general": 6_000_000_000_000, # 6T priority 2 | |
| "math": 4_000_000_000_000, # 4T priority 3 | |
| "reasoning": 2_000_000_000_000, # 2T priority 4 | |
| } | |
| # ββ tokenizer config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| VOCAB_SIZE = 65_536 # power of 2 sweet spot β big enough for great coverage, | |
| # small enough embedding table doesn't eat model params | |
| MIN_FREQ = 10 | |
| TOK_SAMPLE_DOCS = 5_000_000 | |
| # no domain routing tokens β removed in v16 | |
| # chat template tokens kept so model learns conversation format | |
| # FIM tokens for code completion (fill-in-middle) | |
| SPECIAL_TOKENS = [ | |
| "<|endoftext|>", # EOS / doc separator β MUST be index 0 | |
| "<|pad|>", | |
| "<|unk|>", | |
| "<|im_start|>", | |
| "<|im_end|>", | |
| "<|code_start|>", | |
| "<|code_end|>", | |
| "<|math_start|>", | |
| "<|math_end|>", | |
| "<|solution|>", | |
| "<|doc_end|>", | |
| "<|fim_prefix|>", # fill-in-middle for code completion | |
| "<|fim_middle|>", | |
| "<|fim_suffix|>", | |
| *[f"<|extra_{i}|>" for i in range(16)], # future-proof padding slots | |
| ] | |
| START_TIME = time.time() | |
| def elapsed_h(): return (time.time() - START_TIME) / 3600 | |
| # ============================================================================== | |
| # SHARED UTILS | |
| # ============================================================================== | |
| def get_api(): | |
| from huggingface_hub import HfApi, login | |
| login(token=HF_TOKEN, add_to_git_credential=False) | |
| return HfApi(token=HF_TOKEN) | |
| def ensure_repo(api): | |
| try: | |
| api.repo_info(repo_id=REPO_ID, repo_type="dataset") | |
| print(f"β repo exists: https://huggingface.co/datasets/{REPO_ID}", flush=True) | |
| except Exception: | |
| api.create_repo(repo_id=REPO_ID, repo_type="dataset", private=False, exist_ok=True) | |
| print(f"π created repo: https://huggingface.co/datasets/{REPO_ID}", flush=True) | |
| # ============================================================================== | |
| # TOKENIZER SECTION | |
| # ============================================================================== | |
| def build_tokenizer_from_hub() -> "Tokenizer": | |
| """pull the custom nova-1 tokenizer from Hub. used by worker jobs.""" | |
| from tokenizers import Tokenizer | |
| from huggingface_hub import hf_hub_download | |
| try: | |
| path = hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename="tokenizer/nova_tokenizer.json", | |
| repo_type="dataset", | |
| token=HF_TOKEN, | |
| local_dir="/tmp/nova_tok", | |
| ) | |
| t = Tokenizer.from_file(path) | |
| print(f"β custom Nova-1 tokenizer loaded β vocab: {t.get_vocab_size():,}", flush=True) | |
| except Exception as e: | |
| # fallback to gpt2 if tokenizer job hasn't finished yet | |
| print(f"β οΈ custom tokenizer not on Hub yet ({e}) β falling back to gpt2", flush=True) | |
| t = Tokenizer.from_pretrained("gpt2") | |
| for tok in SPECIAL_TOKENS: | |
| if t.token_to_id(tok) is None: | |
| t.add_special_tokens([tok]) | |
| t.no_padding() | |
| t.no_truncation() | |
| return t | |
| _TOK = None | |
| def get_tok(): | |
| global _TOK | |
| if _TOK is None: | |
| _TOK = build_tokenizer_from_hub() | |
| return _TOK | |
| def tokenize_texts(texts: list) -> list: | |
| if not texts: return [] | |
| t = get_tok() | |
| try: | |
| encs = t.encode_batch(texts) | |
| return [e.ids if len(e.ids) >= 5 else [] for e in encs] | |
| except Exception: | |
| out = [] | |
| for tx in texts: | |
| try: | |
| ids = t.encode(tx).ids | |
| out.append(ids if len(ids) >= 5 else []) | |
| except Exception: | |
| out.append([]) | |
| return out | |
| # ββ tokenizer training sources β code-first distribution βββββββββββββββββββββ | |
| # mirrors the domain split: code 40% | general 30% | math 20% | reasoning 10% | |
| TOKENIZER_SOURCES = [ | |
| # CODE β 40% | |
| {"name": "bigcode/starcoderdata", "config": "default", "split": "train", | |
| "n": 2_000_000, "text_key": "content"}, | |
| # GENERAL β 30% | |
| {"name": "HuggingFaceFW/fineweb", "config": "CC-MAIN-2024-10", "split": "train", "n": 500_000, "text_key": "text"}, | |
| {"name": "HuggingFaceFW/fineweb-edu", "config": "sample-10BT", "split": "train", "n": 300_000, "text_key": "text"}, | |
| {"name": "allenai/c4", "config": "en", "split": "train", "n": 300_000, "text_key": "text"}, | |
| {"name": "wikimedia/wikipedia", "config": "20231101.en", "split": "train", "n": 200_000, "text_key": "text"}, | |
| {"name": "sedthh/gutenberg_english", "config": None, "split": "train", "n": 100_000, "text_key": "TEXT"}, | |
| {"name": "cc_news", "config": None, "split": "train", "n": 100_000, "text_key": "text"}, | |
| # multilingual β tokenizer must see these character sets | |
| *[{"name": "wikimedia/wikipedia", "config": f"20231101.{lang}", | |
| "split": "train", "n": 50_000, "text_key": "text"} | |
| for lang in ["zh", "ja", "ar", "ko", "ru", "de", "fr", "es", "pt", "nl"]], | |
| # MATH β 20% | |
| {"name": "open-web-math/open-web-math", "config": None, "split": "train", "n": 500_000, "text_key": "text"}, | |
| {"name": "EleutherAI/proof-pile-2", "config": "arxiv", "split": "train", "n": 200_000, "text_key": "text"}, | |
| {"name": "GAIR/MathPile", "config": None, "split": "train", "n": 200_000, "text_key": "text"}, | |
| {"name": "math-ai/AutoMathText", "config": "web-90", "split": "train", "n": 100_000, "text_key": "text"}, | |
| # REASONING β 10% | |
| {"name": "teknium/OpenHermes-2.5", "config": None, "split": "train", "n": 200_000}, | |
| {"name": "Open-Orca/OpenOrca", "config": None, "split": "train", "n": 150_000}, | |
| {"name": "HuggingFaceH4/ultrachat_200k", "config": None, "split": "train_sft", "n": 150_000}, | |
| ] | |
| def _extract_tok_text(example: dict, src: dict) -> str: | |
| """pull text from any example for tokenizer training.""" | |
| if "text_key" in src: | |
| return example.get(src["text_key"], "") or "" | |
| if "content" in example: | |
| return example["content"] or "" | |
| if "conversations" in example: | |
| return "\n".join( | |
| (m.get("content", m.get("value", "")) or "") | |
| for m in (example["conversations"] or []) | |
| if isinstance(m, dict) | |
| ) | |
| if "messages" in example: | |
| return "\n".join( | |
| (m.get("content", "") or "") | |
| for m in (example["messages"] or []) | |
| if isinstance(m, dict) | |
| ) | |
| if "question" in example and "response" in example: | |
| return (example.get("question","") or "") + "\n" + (example.get("response","") or "") | |
| for key in ("text", "TEXT", "body", "document", "raw_content"): | |
| if example.get(key): | |
| return example[key] | |
| return "" | |
| def _iter_tokenizer_texts(): | |
| """stream ~5M docs for tokenizer training.""" | |
| from datasets import load_dataset | |
| total = 0 | |
| for src in TOKENIZER_SOURCES: | |
| name, config, split, n = src["name"], src.get("config"), src["split"], src["n"] | |
| taken = 0 | |
| print(f" sampling [{name}/{config or 'default'}] n={n:,}", flush=True) | |
| try: | |
| kw = dict(split=split, streaming=True, trust_remote_code=True, token=HF_TOKEN) | |
| ds = load_dataset(name, config, **kw) if config else load_dataset(name, **kw) | |
| for ex in ds: | |
| if taken >= n: break | |
| text = _extract_tok_text(ex, src) | |
| if text and len(text) > 50: | |
| yield text | |
| taken += 1 | |
| total += 1 | |
| except Exception as e: | |
| print(f" β οΈ [{name}] skipped: {e}", flush=True) | |
| print(f" β got {taken:,} | total {total:,}", flush=True) | |
| def run_train_tokenizer(): | |
| """ | |
| MODE=train_tokenizer | |
| trains byte-level BPE from scratch on 5M docs, uploads to Hub. | |
| runs as its own HF Job before the 4 domain pipeline jobs start. | |
| byte-level BPE = zero UNK tokens ever, handles all unicode natively. | |
| 65,536 vocab = 30% fewer tokens per code file vs GPT-2's 50,257. | |
| that's like getting 6T extra tokens of effective context for free. | |
| """ | |
| from tokenizers import Tokenizer | |
| from tokenizers.models import BPE | |
| from tokenizers.normalizers import NFC | |
| from tokenizers.pre_tokenizers import ByteLevel | |
| from tokenizers.decoders import ByteLevel as ByteLevelDecoder | |
| from tokenizers.trainers import BpeTrainer | |
| api = get_api() | |
| ensure_repo(api) | |
| print("=" * 68, flush=True) | |
| print("π₯ NOVA-1 TOKENIZER TRAINING FROM SCRATCH", flush=True) | |
| print(f" vocab size : {VOCAB_SIZE:,}", flush=True) | |
| print(f" type : byte-level BPE", flush=True) | |
| print(f" special tokens : {len(SPECIAL_TOKENS)}", flush=True) | |
| print(f" training docs : ~{TOK_SAMPLE_DOCS:,}", flush=True) | |
| print(f" domain mix : code 40% | general 30% | math 20% | reasoning 10%", flush=True) | |
| print(f" why not gpt2 : tokenizes 8 spaces as 4-5 tokens (yikes)", flush=True) | |
| print(f" no code patterns in merges, inconsistent numbers", flush=True) | |
| print("=" * 68, flush=True) | |
| tokenizer = Tokenizer(BPE(unk_token="<|unk|>")) | |
| tokenizer.normalizer = NFC() # type: ignore | |
| tokenizer.pre_tokenizer = ByteLevel(add_prefix_space=False) # type: ignore | |
| tokenizer.decoder = ByteLevelDecoder() # type: ignore | |
| trainer = BpeTrainer( | |
| vocab_size=VOCAB_SIZE, | |
| min_frequency=MIN_FREQ, | |
| special_tokens=SPECIAL_TOKENS, | |
| show_progress=True, | |
| initial_alphabet=ByteLevel.alphabet(), # ensures every byte has a token | |
| ) | |
| t0 = time.time() | |
| tokenizer.train_from_iterator( | |
| _iter_tokenizer_texts(), | |
| trainer=trainer, | |
| length=TOK_SAMPLE_DOCS, | |
| ) | |
| print(f"\nβ trained in {(time.time()-t0)/60:.1f} min", flush=True) | |
| print(f" actual vocab: {tokenizer.get_vocab_size():,}", flush=True) | |
| tokenizer.no_padding() | |
| tokenizer.no_truncation() | |
| # sanity check β verify round-trips and token efficiency | |
| print("\nπ§ͺ sanity checks:", flush=True) | |
| tests = [ | |
| " def forward(self, x: torch.Tensor) -> torch.Tensor:", | |
| " return self.linear(x) * self.scale_factor", | |
| "\\frac{d}{dx}\\left(x^2\\right) = 2x", | |
| "SELECT id, name FROM users WHERE age > 18;", | |
| "fn main() {\n println!(\"hello world\");\n}", | |
| "θΏζ―δΈδΈͺζ΅θ―γζ₯ζ¬θͺγγΉγγνκ΅μ΄.", | |
| "1234567890 + 9876543210 = 11111111100", | |
| "<|im_start|>user\nhey bestie<|im_end|>", | |
| "<|fim_prefix|>def add(a, b):<|fim_suffix|> return result<|fim_middle|>", | |
| ] | |
| for test in tests: | |
| enc = tokenizer.encode(test) | |
| dec = tokenizer.decode(enc.ids) | |
| ok = "β " if dec == test else "β οΈ " | |
| print(f" {ok} {len(enc.ids):3d} tok | {test[:65]!r}", flush=True) | |
| # save + upload | |
| Path("/tmp/nova_tok").mkdir(exist_ok=True) | |
| tok_path = "/tmp/nova_tok/nova_tokenizer.json" | |
| tokenizer.save(tok_path) | |
| token_map = {t: tokenizer.token_to_id(t) for t in SPECIAL_TOKENS} | |
| map_path = "/tmp/nova_tok/token_map.json" | |
| with open(map_path, "w") as f: | |
| json.dump(token_map, f, indent=2) | |
| readme = f"""# Nova-1 Tokenizer | |
| Byte-level BPE tokenizer trained **from scratch** for Nova-1 pretraining. | |
| | Property | Value | | |
| |---|---| | |
| | Type | Byte-level BPE | | |
| | Vocab size | {tokenizer.get_vocab_size():,} | | |
| | Training docs | ~5M, code-first | | |
| | Domain mix | code 40% / general 30% / math 20% / reasoning 10% | | |
| | Special tokens | {len(SPECIAL_TOKENS)} (chat template + code/math fences + FIM) | | |
| | UNK tokens | Impossible β byte-level covers all Unicode | | |
| ## Why not GPT-2 tokenizer? | |
| GPT-2 was trained on WebText (Reddit links). It has no idea code exists. | |
| - 8 leading spaces (common Python indentation) = 4-5 tokens in GPT-2 vs 1-2 here | |
| - Numbers tokenize inconsistently, hurting math | |
| - No merged tokens for common code patterns like `return `, `self.`, `def ` | |
| Training on the same distribution as the pretraining corpus means ~20-30% | |
| more efficient tokenization of code, effectively giving you more data per | |
| training step for free. | |
| ## Usage | |
| ```python | |
| from tokenizers import Tokenizer | |
| tok = Tokenizer.from_file("nova_tokenizer.json") | |
| ids = tok.encode("def hello(): return 42").ids | |
| ``` | |
| """ | |
| readme_path = "/tmp/nova_tok/README.md" | |
| with open(readme_path, "w") as f: f.write(readme) | |
| print("\nβ¬οΈ uploading tokenizer to Hub...", flush=True) | |
| for local, remote, msg in [ | |
| (tok_path, "tokenizer/nova_tokenizer.json", f"Nova-1 tokenizer β {VOCAB_SIZE:,} vocab byte-level BPE"), | |
| (map_path, "tokenizer/token_map.json", "token id map"), | |
| (readme_path, "tokenizer/README.md", "tokenizer readme"), | |
| ]: | |
| api.upload_file( | |
| path_or_fileobj=local, | |
| path_in_repo=remote, | |
| repo_id=REPO_ID, repo_type="dataset", | |
| commit_message=msg, | |
| ) | |
| print(f"β tokenizer live at: huggingface.co/datasets/{REPO_ID}/tree/main/tokenizer", flush=True) | |
| print("\n" + "="*68, flush=True) | |
| print("β tokenizer done β domain pipeline jobs launching next", flush=True) | |
| print(f" eos_id : {tokenizer.token_to_id('<|endoftext|>')}", flush=True) | |
| print(f" vocab : {tokenizer.get_vocab_size():,}", flush=True) | |
| print("="*68, flush=True) | |
| # ============================================================================== | |
| # QUALITY FILTERS | |
| # ============================================================================== | |
| _GARBAGE = re.compile( | |
| r"click here to|cookie policy|privacy policy|all rights reserved|" | |
| r"javascript is disabled|404 not found|sign up for our newsletter|" | |
| r"terms of service|subscribe to our|follow us on|advertisement", | |
| re.IGNORECASE, | |
| ) | |
| def qf(text, min_chars=150, max_chars=150_000, min_alpha=0.35, max_non_ascii=0.15): | |
| if not text or not isinstance(text, str): return False | |
| n = len(text) | |
| if not (min_chars <= n <= max_chars): return False | |
| s = text[:500] | |
| alpha = sum(1 for c in s if c.isalpha()) | |
| if alpha / len(s) < min_alpha: return False | |
| if sum(1 for c in s if ord(c) > 127) / len(s) > max_non_ascii: return False | |
| if len(_GARBAGE.findall(text[:2000])) >= 2: return False | |
| return True | |
| def qf_relaxed(text, min_chars=100, max_chars=200_000, min_alpha=0.25): | |
| if not text or not isinstance(text, str): return False | |
| if not (min_chars <= len(text) <= max_chars): return False | |
| s = text[:500] | |
| if sum(1 for c in s if c.isalpha()) / max(len(s), 1) < min_alpha: return False | |
| if len(_GARBAGE.findall(text[:2000])) >= 3: return False | |
| return True | |
| _CODE_KW = ( | |
| "def ","class ","function ","import ","#include","public ","private ", | |
| "return ","for ","while ","=>","SELECT ","fn ","func ","package ", | |
| "use ","const ","let ","var ", | |
| ) | |
| def code_qf(code, min_chars=80, max_chars=200_000): | |
| if not isinstance(code, str) or not code: return False | |
| if not (min_chars <= len(code) <= max_chars): return False | |
| lines = code.split("\n") | |
| if len(lines) < 3: return False | |
| if sum(len(l) for l in lines) / len(lines) > 300: return False | |
| if not any(k in code for k in _CODE_KW): return False | |
| s = code[:300] | |
| if sum(1 for c in s if c.isalpha()) / max(len(s), 1) < 0.04: return False | |
| return True | |
| def math_qf(text, min_chars=40, max_chars=50_000): | |
| if not text or not isinstance(text, str): return False | |
| if not (min_chars <= len(text) <= max_chars): return False | |
| return any(s in text for s in | |
| ("=","+","\\frac","\\int","$","^","sqrt","β€","β₯","β","β","β","β","β")) | |
| def book_qf(text, min_chars=500, max_chars=500_000): | |
| if not text or not isinstance(text, str): return False | |
| if not (min_chars <= len(text) <= max_chars): return False | |
| if len(text.split()) < 80: return False | |
| s = text[:1000] | |
| return sum(1 for c in s if c.isalpha()) / max(len(s), 1) >= 0.40 | |
| # ============================================================================== | |
| # FORMATTERS β clean text only, no domain routing tokens | |
| # ============================================================================== | |
| def fmt_raw(text): | |
| t = (text or "").strip() | |
| return t if t else None | |
| def fmt_code(code): | |
| c = (code or "").strip() | |
| return f"<|code_start|>{c}<|code_end|>" if c else None | |
| def fmt_code_qa(instruction, output): | |
| i, o = (instruction or "").strip(), (output or "").strip() | |
| if not i or not o: return None | |
| return ( | |
| f"<|im_start|>system\nYou are Nova-1, a helpful coding assistant.<|im_end|>\n" | |
| f"<|im_start|>user\n{i}<|im_end|>\n" | |
| f"<|im_start|>assistant\n{o}<|im_end|>" | |
| ) | |
| def fmt_math(problem, solution): | |
| p, s = (problem or "").strip(), (solution or "").strip() | |
| if not p or not s: return None | |
| return ( | |
| f"<|im_start|>user\n{p}<|im_end|>\n" | |
| f"<|im_start|>assistant\n<|solution|>{s}<|im_end|>" | |
| ) | |
| def fmt_chat(messages): | |
| if not messages or not isinstance(messages, list): return None | |
| out = "" | |
| for m in messages: | |
| if not isinstance(m, dict): continue | |
| role = m.get("role", m.get("from", "user")) | |
| content = m.get("content", m.get("value", "")) | |
| if not isinstance(content, str): | |
| try: content = str(content) | |
| except: continue | |
| content = content.strip() | |
| if not content: continue | |
| if role in ("human","user"): out += f"<|im_start|>user\n{content}<|im_end|>\n" | |
| elif role in ("gpt","assistant"): out += f"<|im_start|>assistant\n{content}<|im_end|>\n" | |
| elif role == "system": out += f"<|im_start|>system\n{content}<|im_end|>\n" | |
| return out if len(out) > 60 else None | |
| def fmt_qa(question, answer, system=None): | |
| q, a = (question or "").strip(), (answer or "").strip() | |
| if not q or not a: return None | |
| out = "" | |
| if system: out += f"<|im_start|>system\n{system.strip()}<|im_end|>\n" | |
| out += f"<|im_start|>user\n{q}<|im_end|>\n<|im_start|>assistant\n{a}<|im_end|>" | |
| return out | |
| def fmt_alpaca(ex): | |
| instr = (ex.get("instruction","") or "").strip() | |
| inp = (ex.get("input","") or "").strip() | |
| out = (ex.get("output","") or "").strip() | |
| if not instr or not out: return None | |
| return fmt_qa(f"{instr}\n{inp}" if inp else instr, out) | |
| def fmt_openorca(ex): | |
| return fmt_chat([ | |
| {"role":"system", "content": ex.get("system_prompt","")}, | |
| {"role":"user", "content": ex.get("question","")}, | |
| {"role":"assistant", "content": ex.get("response","")}, | |
| ]) | |
| def fmt_first_solution(problem, solutions_field): | |
| sol = solutions_field | |
| try: | |
| if isinstance(sol, str): sol = json.loads(sol) | |
| if isinstance(sol, dict) and "solution" in sol: sol = sol["solution"] | |
| if isinstance(sol, list) and sol: | |
| first = sol[0] | |
| sol = first.get("solution", first) if isinstance(first, dict) else first | |
| except Exception: | |
| return None | |
| if not isinstance(sol, str) or not sol.strip(): return None | |
| return fmt_code_qa(problem, sol) | |
| # ============================================================================== | |
| # DEDUPLICATION | |
| # ============================================================================== | |
| class Deduper: | |
| def __init__(self): | |
| self.seen: set = set() | |
| self.n_dupes: int = 0 | |
| def is_dupe(self, text: str) -> bool: | |
| import xxhash | |
| key = (text[:500] + str(len(text))).encode("utf-8", errors="ignore") | |
| h = xxhash.xxh64(key).intdigest() | |
| if h in self.seen: | |
| self.n_dupes += 1 | |
| return True | |
| self.seen.add(h) | |
| return False | |
| # ============================================================================== | |
| # NPY SHARD UPLOADER | |
| # every 100k rows β .npy shard (shape NΓ2048, dtype int32) β pushed to Hub | |
| # training code does: np.load(shard) and feeds it directly to DataLoader | |
| # no parquet overhead, no deserialisation, just raw int arrays | |
| # ============================================================================== | |
| class NpyShardUploader: | |
| def __init__(self, repo_id, domain, hf_token, shard_rows=100_000): | |
| import numpy as np | |
| from huggingface_hub import HfApi | |
| self.repo_id = repo_id | |
| self.domain = domain | |
| self.shard_rows = shard_rows | |
| self.api = HfApi(token=hf_token) | |
| self.buffer: list = [] | |
| self.shard_idx = self._resume_idx() | |
| self.rows_pushed = 0 | |
| print(f" [{domain}] uploader ready β resuming from shard {self.shard_idx:06d}", flush=True) | |
| def _resume_idx(self): | |
| try: | |
| files = self.api.list_repo_tree( | |
| repo_id=self.repo_id, repo_type="dataset", | |
| path_in_repo=f"data/{self.domain}", recursive=False) | |
| idxs = [int(m.group(1)) | |
| for f in files | |
| for m in [re.search(r"shard_(\d+)\.npy$", getattr(f,"path",""))] | |
| if m] | |
| return max(idxs) + 1 if idxs else 0 | |
| except Exception: | |
| return 0 | |
| def add(self, rows: list): | |
| self.buffer.extend(rows) | |
| while len(self.buffer) >= self.shard_rows: | |
| self._flush(self.buffer[:self.shard_rows]) | |
| self.buffer = self.buffer[self.shard_rows:] | |
| def _flush(self, rows: list): | |
| import numpy as np | |
| if not rows: return | |
| arr = np.array(rows, dtype=np.int32) # shape (N, SEQ_LEN) | |
| tmp = f"/tmp/shard_{self.domain}_{self.shard_idx:06d}.npy" | |
| dest = f"data/{self.domain}/shard_{self.shard_idx:06d}.npy" | |
| np.save(tmp, arr) | |
| size_mb = os.path.getsize(tmp) / 1e6 | |
| for attempt in range(5): | |
| try: | |
| self.api.upload_file( | |
| path_or_fileobj=tmp, | |
| path_in_repo=dest, | |
| repo_id=self.repo_id, repo_type="dataset", | |
| commit_message=f"[{self.domain}] shard {self.shard_idx:06d} β {len(rows):,} rows", | |
| ) | |
| break | |
| except Exception as e: | |
| wait = 20 * (attempt + 1) | |
| print(f" β οΈ upload attempt {attempt+1}/5 failed ({e}) β retry in {wait}s", flush=True) | |
| time.sleep(wait) | |
| try: os.remove(tmp) | |
| except: pass | |
| self.rows_pushed += len(rows) | |
| print( | |
| f" π€ [{self.domain}] shard {self.shard_idx:06d} | " | |
| f"{len(rows):,} rows | {size_mb:.0f} MB | total: {self.rows_pushed:,}", | |
| flush=True, | |
| ) | |
| self.shard_idx += 1 | |
| del arr; gc.collect() | |
| def finalize(self): | |
| if self.buffer: | |
| self._flush(self.buffer) | |
| self.buffer.clear() | |
| gc.collect() | |
| # ============================================================================== | |
| # DOCUMENT PACKER | |
| # packs variable-length token sequences into fixed SEQ_LEN windows | |
| # separated by EOS tokens, no wasted padding within a window | |
| # ============================================================================== | |
| class DocPacker: | |
| def __init__(self, seq_len, eos_id, uploader: NpyShardUploader, flush_every=8_000): | |
| self.seq_len = seq_len | |
| self.eos_id = eos_id | |
| self.uploader = uploader | |
| self.flush_every = flush_every | |
| self.current: list = [] | |
| self.ready: list = [] | |
| self.total_rows = 0 | |
| def add_batch(self, id_lists: list): | |
| for ids in id_lists: | |
| if ids: | |
| self._pack(list(ids) + [self.eos_id]) | |
| if len(self.ready) >= self.flush_every: | |
| self._push() | |
| def _pack(self, tokens: list): | |
| i = 0 | |
| while i < len(tokens): | |
| space = self.seq_len - len(self.current) | |
| self.current.extend(tokens[i:i+space]) | |
| i += space | |
| if len(self.current) == self.seq_len: | |
| self.ready.append(self.current) | |
| self.current = [] | |
| def _push(self): | |
| if not self.ready: return | |
| self.uploader.add(self.ready) | |
| self.total_rows += len(self.ready) | |
| self.ready = [] | |
| gc.collect() | |
| def finalize(self) -> int: | |
| if self.current: | |
| self.current += [self.eos_id] * (self.seq_len - len(self.current)) | |
| self.ready.append(self.current) | |
| self.current = [] | |
| self._push() | |
| self.uploader.finalize() | |
| return self.total_rows | |
| # ============================================================================== | |
| # DATASET LOADER | |
| # ============================================================================== | |
| def load_ds(name, config, split, retries=3, backoff=15): | |
| from datasets import load_dataset | |
| last_err = None | |
| for attempt in range(retries + 1): | |
| try: | |
| kw = dict(split=split, streaming=True, trust_remote_code=True, token=HF_TOKEN) | |
| return load_dataset(name, config, **kw) if config else load_dataset(name, **kw) | |
| except TypeError: | |
| try: | |
| kw = dict(split=split, streaming=True, token=HF_TOKEN) | |
| return load_dataset(name, config, **kw) if config else load_dataset(name, **kw) | |
| except Exception as e: | |
| last_err = e | |
| except Exception as e: | |
| last_err = e | |
| if attempt < retries: | |
| print(f" β οΈ attempt {attempt+1} [{name}]: {e} β retry in {backoff}s", flush=True) | |
| time.sleep(backoff) | |
| raise last_err # type: ignore | |
| # ============================================================================== | |
| # PER-DATASET PROCESSOR | |
| # ============================================================================== | |
| def run_dataset(cfg, domain_counters, lock, uploader, domain_budgets) -> dict: | |
| name = cfg["name"] | |
| config = cfg.get("config") | |
| max_docs = cfg["max"] | |
| max_min = cfg.get("max_minutes", DEFAULT_MAX_MINUTES_PER_DATASET) | |
| fmt_fn = cfg["fmt"] | |
| filt_fn = cfg["filter"] | |
| domain = cfg["domain"] | |
| def over_budget(): | |
| with lock: | |
| return domain_counters.get(domain, 0) >= domain_budgets.get(domain, float("inf")) | |
| tok = get_tok() | |
| eos_id = tok.token_to_id("<|endoftext|>") | |
| deduper = Deduper() | |
| packer = DocPacker(SEQ_LEN, eos_id, uploader, flush_every=8_000) | |
| try: | |
| ds = load_ds(name, config, cfg["split"]) | |
| except Exception as e: | |
| print(f" β [{name}/{config}] load failed: {e}", flush=True) | |
| return {"name":name,"config":config,"domain":domain, | |
| "docs":0,"tokens":0,"error":str(e)} | |
| t0 = time.time() | |
| count = skipped = dupes = 0 | |
| new_tokens = 0 | |
| buf: list = [] | |
| def flush_buf(): | |
| nonlocal count, new_tokens | |
| if not buf: return | |
| id_lists = tokenize_texts(buf) | |
| accepted = [ids for ids in id_lists if ids] | |
| if accepted: | |
| packer.add_batch(accepted) | |
| n = sum(len(ids) for ids in accepted) | |
| count += len(accepted) | |
| new_tokens += n | |
| with lock: | |
| domain_counters[domain] = domain_counters.get(domain, 0) + n | |
| buf.clear() | |
| try: | |
| for ex in ds: | |
| elapsed_min = (time.time() - t0) / 60 | |
| if (count >= max_docs or elapsed_h() > JOB_TIMEOUT_H | |
| or over_budget() or elapsed_min > max_min): | |
| break | |
| try: | |
| if not filt_fn(ex): skipped += 1; continue | |
| except Exception: | |
| skipped += 1; continue | |
| try: | |
| text = fmt_fn(ex) | |
| except Exception: | |
| skipped += 1; continue | |
| if not text or len(text) < 20: | |
| skipped += 1; continue | |
| if deduper.is_dupe(text): | |
| dupes += 1; continue | |
| buf.append(text) | |
| if len(buf) >= TOKENIZE_BATCH: | |
| flush_buf() | |
| if count and count % 50_000 == 0: | |
| print( | |
| f" [{name}/{config or 'default'}] " | |
| f"{count:,}/{max_docs:,} | " | |
| f"{new_tokens/1e9:.3f}B tok | " | |
| f"{elapsed_min:.1f}min | job={elapsed_h():.2f}h", | |
| flush=True, | |
| ) | |
| except Exception as e: | |
| print(f" β οΈ stream error [{name}]: {e}", flush=True) | |
| flush_buf() | |
| total_rows = packer.finalize() | |
| print( | |
| f" β [{name}/{config or 'default'}] " | |
| f"{count:,} docs | {new_tokens/1e9:.3f}B tok | " | |
| f"rows={total_rows:,} | skip={skipped:,} | dupe={dupes:,} | " | |
| f"{time.time()-t0:.0f}s", | |
| flush=True, | |
| ) | |
| return {"name":name,"config":config,"domain":domain, | |
| "docs":count,"tokens":new_tokens,"rows":total_rows, | |
| "skipped":skipped,"dupes":dupes} | |
| # ============================================================================== | |
| # DATASET ROSTER β 100+ sources, code-first, no domain routing tokens | |
| # ============================================================================== | |
| LANGS_WANTED = { | |
| "python","javascript","typescript","java","c","cpp","go","rust","bash","sql", | |
| "php","ruby","scala","kotlin","swift","r","matlab","julia","haskell","lua","cs","csharp", | |
| } | |
| DATASETS: list = [ | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CODE β 8T target β priority 1 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # StarCoder β everything, no lang filter, just send it | |
| { | |
| "name": "bigcode/starcoderdata", | |
| "config": "default", | |
| "split": "train", | |
| "domain": "code", | |
| "max": 300_000_000, | |
| "max_minutes": BIG_MAX_MINUTES, | |
| "fmt": lambda ex: ex.get("content", ""), # β raw code | |
| "filter": lambda ex: True, # β accept everything | |
| }, | |
| {"name":"bigcode/the-stack-v2-train-smol-ids","config":None,"split":"train", | |
| "domain":"code","max":80_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_code(ex.get("content",ex.get("text",""))), | |
| "filter":lambda ex:( | |
| code_qf(ex.get("content",ex.get("text",""))) and | |
| ex.get("lang","").lower() in LANGS_WANTED)}, | |
| *[{"name":"codeparrot/github-code-clean","config":cfg,"split":"train", | |
| "domain":"code","max":max_n,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_code(ex.get("code","")), | |
| "filter":lambda ex:code_qf(ex.get("code",""))} | |
| for cfg, max_n in [ | |
| ("Python-all",20_000_000),("JavaScript-all",12_000_000), | |
| ("Java-all",12_000_000),("C++-all",10_000_000),("Go-all",8_000_000), | |
| ]], | |
| *[{"name":"code-search-net/code_search_net","config":lang,"split":"train", | |
| "domain":"code","max":2_000_000,"max_minutes":120, | |
| "fmt":lambda ex:fmt_code(ex.get("whole_func_string","")), | |
| "filter":lambda ex:code_qf(ex.get("whole_func_string",""),min_chars=120)} | |
| for lang in ["python","javascript","java","go","ruby","php"]], | |
| *[{"name":"bigcode/commitpackft","config":lang,"split":"train", | |
| "domain":"code","max":3_000_000,"max_minutes":120, | |
| "fmt":lambda ex:fmt_code_qa( | |
| ex.get("message",""), | |
| ex.get("old_contents","") + "\n\n# AFTER:\n\n" + ex.get("new_contents","")), | |
| "filter":lambda ex:code_qf(ex.get("new_contents",""),min_chars=100)} | |
| for lang in ["python","javascript","java","rust","go","cpp","typescript"]], | |
| {"name":"glaiveai/glaive-code-assistant-v3","config":None,"split":"train", | |
| "domain":"code","max":500_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_code_qa(ex.get("question",""),ex.get("answer","")), | |
| "filter":lambda ex:bool(ex.get("answer","").strip())}, | |
| {"name":"ise-uiuc/Magicoder-Evol-Instruct-110K","config":None,"split":"train", | |
| "domain":"code","max":110_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_code_qa(ex.get("instruction",""),ex.get("response","")), | |
| "filter":lambda ex:bool(ex.get("response","").strip())}, | |
| {"name":"ise-uiuc/Magicoder-OSS-Instruct-75K","config":None,"split":"train", | |
| "domain":"code","max":75_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_code_qa( | |
| ex.get("problem",ex.get("instruction","")), | |
| ex.get("solution",ex.get("response",""))), | |
| "filter":lambda ex:bool(ex.get("solution",ex.get("response","")).strip())}, | |
| {"name":"m-a-p/CodeFeedback-Filtered-Instruction","config":None,"split":"train", | |
| "domain":"code","max":200_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_code_qa(ex.get("query",""),ex.get("answer","")), | |
| "filter":lambda ex:bool(ex.get("answer","").strip())}, | |
| {"name":"Vezora/Tested-143k-Python-Alpaca","config":None,"split":"train", | |
| "domain":"code","max":143_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_code_qa(ex.get("instruction",""),ex.get("output","")), | |
| "filter":lambda ex:bool(ex.get("output","").strip())}, | |
| {"name":"TokenBender/code_instructions_122k_alpaca_style","config":None,"split":"train", | |
| "domain":"code","max":122_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_code_qa( | |
| ex.get("instruction","")+(f"\n{ex.get('input','')}" if ex.get("input","").strip() else ""), | |
| ex.get("output","")), | |
| "filter":lambda ex:bool(ex.get("output","").strip())}, | |
| {"name":"deepmind/code_contests","config":None,"split":"train", | |
| "domain":"code","max":100_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_first_solution(ex.get("description",""),ex.get("solutions",[])), | |
| "filter":lambda ex:bool(ex.get("description","").strip())}, | |
| {"name":"codeparrot/apps","config":"all","split":"train", | |
| "domain":"code","max":50_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_first_solution(ex.get("question",""),ex.get("solutions","[]")), | |
| "filter":lambda ex:bool(ex.get("question","").strip())}, | |
| {"name":"openai/openai_humaneval","config":None,"split":"test", | |
| "domain":"code","max":164,"max_minutes":10, | |
| "fmt":lambda ex:fmt_code_qa(ex.get("prompt",""),ex.get("canonical_solution","")), | |
| "filter":lambda ex:bool(ex.get("canonical_solution","").strip())}, | |
| {"name":"google-research-datasets/mbpp","config":"full","split":"train", | |
| "domain":"code","max":10_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_code_qa(ex.get("text",""),ex.get("code","")), | |
| "filter":lambda ex:bool(ex.get("code","").strip())}, | |
| {"name":"princeton-nlp/SWE-bench","config":None,"split":"train", | |
| "domain":"code","max":5_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_code_qa(ex.get("problem_statement",""),ex.get("patch","")), | |
| "filter":lambda ex:bool(ex.get("patch","").strip())}, | |
| {"name":"xlangai/DS-1000","config":None,"split":"test", | |
| "domain":"code","max":1_000,"max_minutes":10, | |
| "fmt":lambda ex:fmt_code_qa(ex.get("prompt",""),ex.get("reference_code","")), | |
| "filter":lambda ex:bool(ex.get("reference_code","").strip())}, | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # GENERAL β 6T target β priority 2 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| *[{"name":"HuggingFaceFW/fineweb","config":cfg,"split":"train", | |
| "domain":"general","max":max_n,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=300)} | |
| for cfg, max_n in [ | |
| ("CC-MAIN-2024-10",80_000_000),("CC-MAIN-2023-50",60_000_000), | |
| ("CC-MAIN-2023-23",50_000_000),("CC-MAIN-2023-06",40_000_000), | |
| ("CC-MAIN-2022-49",35_000_000),("CC-MAIN-2022-27",30_000_000), | |
| ]], | |
| {"name":"HuggingFaceFW/fineweb-edu","config":"sample-10BT","split":"train", | |
| "domain":"general","max":50_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=400) and ex.get("score",0)>=2}, | |
| {"name":"HuggingFaceFW/fineweb-edu","config":"sample-100BT","split":"train", | |
| "domain":"general","max":40_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=400) and ex.get("score",0)>=3}, | |
| {"name":"allenai/c4","config":"en","split":"train", | |
| "domain":"general","max":50_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=300)}, | |
| {"name":"togethercomputer/RedPajama-Data-V2","config":"default","split":"train", | |
| "domain":"general","max":40_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("raw_content",ex.get("text",""))), | |
| "filter":lambda ex:qf(ex.get("raw_content",ex.get("text","")),min_chars=300)}, | |
| {"name":"allenai/dolma","config":"v1_7","split":"train", | |
| "domain":"general","max":40_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=300)}, | |
| {"name":"oscar-corpus/OSCAR-2301","config":"en","split":"train", | |
| "domain":"general","max":30_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("content","")), | |
| "filter":lambda ex:qf(ex.get("content",""),min_chars=300)}, | |
| {"name":"cerebras/SlimPajama-627B","config":"default","split":"train", | |
| "domain":"general","max":25_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=300)}, | |
| {"name":"wikimedia/wikipedia","config":"20231101.en","split":"train", | |
| "domain":"general","max":6_500_000,"max_minutes":240, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=600)}, | |
| *[{"name":"wikimedia/wikipedia","config":f"20231101.{lang}","split":"train", | |
| "domain":"general","max":3_000_000,"max_minutes":180, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf_relaxed(ex.get("text",""),min_chars=400)} | |
| for lang in ["fr","de","es","zh","ja","ko","ar","ru","pt","nl","it","pl","sv"]], | |
| {"name":"wikimedia/wikisource","config":"20231201.en","split":"train", | |
| "domain":"general","max":2_000_000,"max_minutes":120, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=400)}, | |
| {"name":"monology/pile-uncopyrighted","config":None,"split":"train", | |
| "domain":"general","max":8_000_000,"max_minutes":240, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:book_qf(ex.get("text",""),min_chars=500)}, | |
| {"name":"sedthh/gutenberg_english","config":None,"split":"train", | |
| "domain":"general","max":5_000_000,"max_minutes":180, | |
| "fmt":lambda ex:fmt_raw(ex.get("TEXT",ex.get("text",""))), | |
| "filter":lambda ex:book_qf(ex.get("TEXT",ex.get("text","")))}, | |
| {"name":"storytracer/US-PD-Books","config":None,"split":"train", | |
| "domain":"general","max":3_000_000,"max_minutes":180, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:book_qf(ex.get("text",""))}, | |
| {"name":"allenai/peS2o","config":"v2","split":"train", | |
| "domain":"general","max":10_000_000,"max_minutes":240, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=500)}, | |
| {"name":"allenai/s2orc","config":"full","split":"train", | |
| "domain":"general","max":8_000_000,"max_minutes":240, | |
| "fmt":lambda ex:fmt_raw( | |
| ex.get("title","") + "\n\n" + ex.get("abstract","") + "\n\n" + ex.get("body_text","")), | |
| "filter":lambda ex:qf(ex.get("abstract","")+ex.get("body_text",""),min_chars=400)}, | |
| {"name":"togethercomputer/RedPajama-Data-1T-Sample","config":None,"split":"train", | |
| "domain":"general","max":5_000_000,"max_minutes":180, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=400)}, | |
| {"name":"NeelNanda/pile-10k","config":None,"split":"train", | |
| "domain":"general","max":100_000,"max_minutes":30, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=300)}, | |
| *[{"name":"HuggingFaceTB/cosmopedia","config":cfg,"split":"train", | |
| "domain":"general","max":5_000_000,"max_minutes":240, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=500)} | |
| for cfg in ["auto_math_text","web_samples_v2","stanford","stories","wikihow","openstax"]], | |
| {"name":"HuggingFaceTB/cosmopedia-v2","config":None,"split":"train", | |
| "domain":"general","max":8_000_000,"max_minutes":240, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=500)}, | |
| {"name":"cc_news","config":None,"split":"train", | |
| "domain":"general","max":8_000_000,"max_minutes":180, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=300)}, | |
| {"name":"Skylion007/openwebtext","config":None,"split":"train", | |
| "domain":"general","max":8_000_000,"max_minutes":180, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=400)}, | |
| {"name":"HuggingFaceH4/stack-exchange-preferences","config":None,"split":"train", | |
| "domain":"general","max":3_000_000,"max_minutes":180, | |
| "fmt":lambda ex:fmt_qa( | |
| ex.get("question",""), | |
| ex.get("chosen",{}).get("text","") if isinstance(ex.get("chosen"),dict) | |
| else str(ex.get("chosen",""))), | |
| "filter":lambda ex:bool(ex.get("question",""))}, | |
| {"name":"tatsu-lab/alpaca","config":None,"split":"train", | |
| "domain":"general","max":52_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":fmt_alpaca,"filter":lambda ex:bool(ex.get("output","").strip())}, | |
| {"name":"yahma/alpaca-cleaned","config":None,"split":"train", | |
| "domain":"general","max":52_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":fmt_alpaca,"filter":lambda ex:bool(ex.get("output","").strip())}, | |
| {"name":"databricks/databricks-dolly-15k","config":None,"split":"train", | |
| "domain":"general","max":15_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa( | |
| ex.get("instruction","") + ("\n"+ex.get("context","") if ex.get("context","").strip() else ""), | |
| ex.get("response","")), | |
| "filter":lambda ex:bool(ex.get("response","").strip())}, | |
| {"name":"Muennighoff/flan","config":None,"split":"train", | |
| "domain":"general","max":2_000_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa(ex.get("inputs",""),ex.get("targets","")), | |
| "filter":lambda ex:bool(ex.get("targets","").strip())}, | |
| {"name":"anon8231489123/ShareGPT_Vicuna_unfiltered","config":None,"split":"train", | |
| "domain":"general","max":300_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat(ex.get("conversations",[])), | |
| "filter":lambda ex:bool(ex.get("conversations",[]))}, | |
| {"name":"OpenAssistant/oasst2","config":None,"split":"train", | |
| "domain":"general","max":400_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa(ex.get("parent_text",""),ex.get("text","")), | |
| "filter":lambda ex:bool(ex.get("text","").strip()) and ex.get("role")=="assistant"}, | |
| {"name":"HuggingFaceH4/no_robots","config":None,"split":"train", | |
| "domain":"general","max":10_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat(ex.get("messages",[])), | |
| "filter":lambda ex:bool(ex.get("messages",[]))}, | |
| {"name":"openbmb/UltraFeedback","config":None,"split":"train", | |
| "domain":"general","max":400_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa( | |
| ex.get("instruction",""), | |
| (ex.get("completions",[{}])[0] or {}).get("response","")), | |
| "filter":lambda ex:bool(ex.get("instruction","").strip())}, | |
| {"name":"totally-not-an-llm/EverythingLM-data-V3","config":None,"split":"train", | |
| "domain":"general","max":200_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat(ex.get("conversations",[])), | |
| "filter":lambda ex:bool(ex.get("conversations",[]))}, | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # MATH β 4T target β priority 3 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| {"name":"open-web-math/open-web-math","config":None,"split":"train", | |
| "domain":"math","max":60_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:math_qf(ex.get("text",""),min_chars=300)}, | |
| {"name":"EleutherAI/proof-pile-2","config":"algebraic-stack","split":"train", | |
| "domain":"math","max":30_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=500)}, | |
| {"name":"EleutherAI/proof-pile-2","config":"arxiv","split":"train", | |
| "domain":"math","max":25_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:qf(ex.get("text",""),min_chars=500)}, | |
| {"name":"GAIR/MathPile","config":None,"split":"train", | |
| "domain":"math","max":20_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:math_qf(ex.get("text",""),min_chars=200)}, | |
| {"name":"math-ai/AutoMathText","config":"web-90","split":"train", | |
| "domain":"math","max":15_000_000,"max_minutes":BIG_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:math_qf(ex.get("text",""),min_chars=200)}, | |
| {"name":"vikp/textbook_quality_programming","config":None,"split":"train", | |
| "domain":"math","max":1_000_000,"max_minutes":120, | |
| "fmt":lambda ex:fmt_raw(ex.get("text","")), | |
| "filter":lambda ex:math_qf(ex.get("text",""),min_chars=300)}, | |
| {"name":"TIGER-Lab/MathInstruct","config":None,"split":"train", | |
| "domain":"math","max":262_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_math(ex.get("instruction",""),ex.get("output","")), | |
| "filter":lambda ex:math_qf(ex.get("output",""))}, | |
| {"name":"meta-math/MetaMathQA","config":None,"split":"train", | |
| "domain":"math","max":395_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_math(ex.get("query",""),ex.get("response","")), | |
| "filter":lambda ex:math_qf(ex.get("response",""))}, | |
| {"name":"AI-MO/NuminaMath-CoT","config":None,"split":"train", | |
| "domain":"math","max":300_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_math(ex.get("problem",""),ex.get("solution","")), | |
| "filter":lambda ex:math_qf(ex.get("solution",""))}, | |
| {"name":"nvidia/OpenMathInstruct-1","config":"default","split":"train", | |
| "domain":"math","max":500_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_math(ex.get("question",""),ex.get("generated_solution","")), | |
| "filter":lambda ex:math_qf(ex.get("generated_solution",""))}, | |
| {"name":"microsoft/orca-math-word-problems-200k","config":None,"split":"train", | |
| "domain":"math","max":200_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_math(ex.get("question",""),ex.get("answer","")), | |
| "filter":lambda ex:math_qf(ex.get("answer",""))}, | |
| {"name":"camel-ai/math","config":None,"split":"train", | |
| "domain":"math","max":50_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_math(ex.get("message_1",""),ex.get("message_2","")), | |
| "filter":lambda ex:math_qf(ex.get("message_2",""))}, | |
| {"name":"hendrycks/competition_math","config":None,"split":"train", | |
| "domain":"math","max":12_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_math(ex.get("problem",""),ex.get("solution","")), | |
| "filter":lambda ex:math_qf(ex.get("solution",""))}, | |
| {"name":"openai/gsm8k","config":"main","split":"train", | |
| "domain":"math","max":8_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_math(ex.get("question",""),ex.get("answer","")), | |
| "filter":lambda ex:math_qf(ex.get("answer",""))}, | |
| {"name":"lighteval/MATH","config":"all","split":"train", | |
| "domain":"math","max":12_500,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_math(ex.get("problem",""),ex.get("solution","")), | |
| "filter":lambda ex:math_qf(ex.get("solution",""))}, | |
| {"name":"AI-MO/NuminaMath-TIR","config":None,"split":"train", | |
| "domain":"math","max":200_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_math(ex.get("problem",""),ex.get("solution","")), | |
| "filter":lambda ex:math_qf(ex.get("solution",""))}, | |
| {"name":"di-dimitrov/MATH","config":None,"split":"train", | |
| "domain":"math","max":100_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_math(ex.get("problem",""),ex.get("solution","")), | |
| "filter":lambda ex:math_qf(ex.get("solution",""))}, | |
| {"name":"leanprover-community/mathlib4","config":None,"split":"train", | |
| "domain":"math","max":500_000,"max_minutes":120, | |
| "fmt":lambda ex:fmt_raw(ex.get("text",ex.get("content",""))), | |
| "filter":lambda ex:bool((ex.get("text",ex.get("content","")) or "").strip())}, | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # REASONING β 2T target β priority 4 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| {"name":"openbmb/UltraInteract_sft","config":None,"split":"train", | |
| "domain":"reasoning","max":500_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat([ | |
| {"role":"user", "content":ex.get("instruction","")}, | |
| {"role":"assistant", "content":ex.get("response","")}, | |
| ]),"filter":lambda ex:bool(ex.get("response","").strip())}, | |
| {"name":"teknium/OpenHermes-2.5","config":None,"split":"train", | |
| "domain":"reasoning","max":500_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat(ex.get("conversations",[])), | |
| "filter":lambda ex:bool(ex.get("conversations",[]))}, | |
| {"name":"Open-Orca/OpenOrca","config":None,"split":"train", | |
| "domain":"reasoning","max":500_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":fmt_openorca, | |
| "filter":lambda ex:bool(ex.get("response","").strip())}, | |
| {"name":"Open-Orca/SlimOrca","config":None,"split":"train", | |
| "domain":"reasoning","max":400_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat(ex.get("conversations",[])), | |
| "filter":lambda ex:bool(ex.get("conversations",[]))}, | |
| {"name":"WizardLM/WizardLM_evol_instruct_V2_196k","config":None,"split":"train", | |
| "domain":"reasoning","max":196_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat(ex.get("conversations",[])), | |
| "filter":lambda ex:bool(ex.get("conversations",[]))}, | |
| {"name":"cognitivecomputations/dolphin","config":"flan1m-alpaca-uncensored","split":"train", | |
| "domain":"reasoning","max":400_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat([ | |
| {"role":"user", "content":ex.get("instruction","") + "\n" + ex.get("input","")}, | |
| {"role":"assistant", "content":ex.get("output","")}, | |
| ]),"filter":lambda ex:bool(ex.get("output","").strip())}, | |
| {"name":"LDJnr/Capybara","config":None,"split":"train", | |
| "domain":"reasoning","max":60_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat(ex.get("conversation",[])), | |
| "filter":lambda ex:bool(ex.get("conversation",[]))}, | |
| {"name":"glaiveai/glaive-function-calling-v2","config":None,"split":"train", | |
| "domain":"reasoning","max":200_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat([ | |
| {"role":"system","content":ex.get("system","")}, | |
| {"role":"user", "content":ex.get("chat","")}, | |
| ]),"filter":lambda ex:bool(ex.get("chat",""))}, | |
| {"name":"HuggingFaceH4/ultrachat_200k","config":None,"split":"train_sft", | |
| "domain":"reasoning","max":400_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat(ex.get("messages",[])), | |
| "filter":lambda ex:bool(ex.get("messages",[]))}, | |
| {"name":"Mathoctopus/Parallel_full","config":None,"split":"train", | |
| "domain":"reasoning","max":300_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat([ | |
| {"role":"user", "content":ex.get("query","")}, | |
| {"role":"assistant", "content":ex.get("response","")}, | |
| ]),"filter":lambda ex:bool(ex.get("response","").strip())}, | |
| {"name":"camel-ai/ai_society","config":None,"split":"train", | |
| "domain":"reasoning","max":300_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat([ | |
| {"role":"user", "content":ex.get("message_1","")}, | |
| {"role":"assistant", "content":ex.get("message_2","")}, | |
| ]),"filter":lambda ex:bool(ex.get("message_2","").strip())}, | |
| {"name":"CohereForAI/aya_dataset","config":None,"split":"train", | |
| "domain":"reasoning","max":400_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa(ex.get("inputs",""),ex.get("targets","")), | |
| "filter":lambda ex:bool(ex.get("targets","").strip())}, | |
| {"name":"WizardLM/WizardLM_evol_instruct_70k","config":None,"split":"train", | |
| "domain":"reasoning","max":70_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_chat(ex.get("conversations",[])), | |
| "filter":lambda ex:bool(ex.get("conversations",[]))}, | |
| {"name":"derek-thomas/ScienceQA","config":None,"split":"train", | |
| "domain":"reasoning","max":20_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa( | |
| ex.get("question",""), | |
| ex.get("solution","") or str(ex.get("answer",""))), | |
| "filter":lambda ex:bool(ex.get("question","").strip())}, | |
| {"name":"truthful_qa","config":"generation","split":"validation", | |
| "domain":"reasoning","max":817,"max_minutes":10, | |
| "fmt":lambda ex:fmt_qa(ex.get("question",""),ex.get("best_answer","")), | |
| "filter":lambda ex:bool(ex.get("best_answer","").strip())}, | |
| {"name":"tau/commonsense_qa","config":None,"split":"train", | |
| "domain":"reasoning","max":12_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa(ex.get("question",""),ex.get("answerKey","")), | |
| "filter":lambda ex:bool(ex.get("answerKey","").strip())}, | |
| {"name":"google/boolq","config":None,"split":"train", | |
| "domain":"reasoning","max":10_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa( | |
| ex.get("passage","") + "\n" + ex.get("question",""), | |
| str(ex.get("answer",""))), | |
| "filter":lambda ex:bool(ex.get("question","").strip())}, | |
| {"name":"allenai/ai2_arc","config":"ARC-Challenge","split":"train", | |
| "domain":"reasoning","max":5_000,"max_minutes":10, | |
| "fmt":lambda ex:fmt_qa(ex.get("question",""),ex.get("answerKey","")), | |
| "filter":lambda ex:bool(ex.get("question","").strip())}, | |
| {"name":"Rowan/hellaswag","config":None,"split":"train", | |
| "domain":"reasoning","max":40_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa( | |
| ex.get("ctx",""), | |
| ex.get("endings",[""])[int(ex.get("label","0") or 0)]), | |
| "filter":lambda ex:bool(ex.get("ctx","").strip())}, | |
| {"name":"cais/mmlu","config":"all","split":"auxiliary_train", | |
| "domain":"reasoning","max":200_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa( | |
| ex.get("question",""), | |
| ex.get("choices",["","","",""])[ex.get("answer",0)]), | |
| "filter":lambda ex:bool(ex.get("question","").strip())}, | |
| {"name":"metaeval/reclor","config":None,"split":"train", | |
| "domain":"reasoning","max":10_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa( | |
| ex.get("context","") + "\n" + ex.get("question",""), | |
| ex.get("answers",[""])[ex.get("label",0)] | |
| if isinstance(ex.get("answers",[]),list) else ""), | |
| "filter":lambda ex:bool(ex.get("question","").strip())}, | |
| {"name":"lucasmccabe/logiqa","config":None,"split":"train", | |
| "domain":"reasoning","max":10_000,"max_minutes":INSTRUCT_MAX_MINUTES, | |
| "fmt":lambda ex:fmt_qa( | |
| ex.get("context","") + "\n" + ex.get("query",""), | |
| str(ex.get("correct_option",""))), | |
| "filter":lambda ex:bool(ex.get("query","").strip())}, | |
| ] | |
| # ============================================================================== | |
| # WORKER MAIN β MODE=worker, runs inside HF Job | |
| # ============================================================================== | |
| def run_worker(): | |
| os.environ["TOKENIZERS_PARALLELISM"] = "false" | |
| os.environ["HF_XET_HIGH_PERFORMANCE"] = "1" | |
| os.environ["HF_DATASETS_DISABLE_PROGRESS_BARS"] = "1" | |
| api = get_api() | |
| ensure_repo(api) | |
| print("=" * 68, flush=True) | |
| print("π₯ NOVA-1 v16 WORKER β pre-tokenized npy pipeline", flush=True) | |
| print(f" domain : {DOMAIN_FILTER}", flush=True) | |
| print(f" repo : {REPO_ID}", flush=True) | |
| print(f" shard : {SHARD_ROWS:,} rows Γ {SEQ_LEN} tokens = " | |
| f"{SHARD_ROWS*SEQ_LEN*4/1e6:.0f} MB/shard", flush=True) | |
| print(f" hardware : CPU Performance β 32 vCPU / 256 GB / 1024 GB", flush=True) | |
| print(f" timeout : {JOB_TIMEOUT_H}h (never basically)", flush=True) | |
| print("=" * 68, flush=True) | |
| active = (DATASETS if DOMAIN_FILTER == "ALL" | |
| else [d for d in DATASETS if d["domain"] == DOMAIN_FILTER]) | |
| print(f"\nπ¦ {len(active)} datasets queued", flush=True) | |
| domain_counters: dict = defaultdict(int) | |
| lock = threading.Lock() | |
| uploaders = { | |
| domain: NpyShardUploader(REPO_ID, domain, HF_TOKEN, shard_rows=SHARD_ROWS) | |
| for domain in DOMAIN_TOKEN_BUDGETS | |
| } | |
| results = [] | |
| for cfg in active: | |
| if elapsed_h() > JOB_TIMEOUT_H: | |
| print("β° timeout β stopping", flush=True) | |
| break | |
| domain = cfg["domain"] | |
| with lock: | |
| current = domain_counters.get(domain, 0) | |
| if current >= DOMAIN_TOKEN_BUDGETS.get(domain, float("inf")): | |
| print(f"β [{domain}] budget hit β skipping {cfg['name']}", flush=True) | |
| continue | |
| r = run_dataset(cfg, domain_counters, lock, uploaders[domain], DOMAIN_TOKEN_BUDGETS) | |
| results.append(r) | |
| # progress bar β no cap we love a good progress bar | |
| grand = sum(domain_counters.values()) | |
| print(f"\nπ @ {elapsed_h():.2f}h | grand total: {grand/1e12:.4f}T", flush=True) | |
| for d, budget in DOMAIN_TOKEN_BUDGETS.items(): | |
| n = domain_counters.get(d, 0) | |
| pct = 100 * n / max(budget, 1) | |
| bar = "β" * int(pct/5) + "β" * (20 - int(pct/5)) | |
| print(f" {d:<12} [{bar}] {n/1e12:.4f}T/{budget/1e12:.0f}T ({pct:.1f}%)", flush=True) | |
| print("", flush=True) | |
| for u in uploaders.values(): | |
| u.finalize() | |
| # final metadata push | |
| total = sum(domain_counters.values()) | |
| tok = get_tok() | |
| meta = { | |
| "pipeline_version": "v16_hf_jobs_npy", | |
| "domain_filter": DOMAIN_FILTER, | |
| "vocab_size": tok.get_vocab_size(), | |
| "seq_len": SEQ_LEN, | |
| "eos_token_id": int(tok.token_to_id("<|endoftext|>")), | |
| "total_tokens": total, | |
| "total_tokens_T": round(total/1e12, 6), | |
| "domain_budgets_T": {k: v/1e12 for k,v in DOMAIN_TOKEN_BUDGETS.items()}, | |
| "domain_actuals_T": {k: v/1e12 for k,v in domain_counters.items()}, | |
| "hours_elapsed": round(elapsed_h(), 2), | |
| "shard_rows": SHARD_ROWS, | |
| "special_tokens": {t: tok.token_to_id(t) for t in SPECIAL_TOKENS}, | |
| "priority_order": "code > general > math > reasoning", | |
| "dataset_results": results, | |
| } | |
| meta_path = f"/tmp/metadata_{DOMAIN_FILTER}.json" | |
| with open(meta_path, "w") as f: json.dump(meta, f, indent=2) | |
| try: | |
| api.upload_file( | |
| path_or_fileobj=meta_path, | |
| path_in_repo=f"metadata_{DOMAIN_FILTER}.json", | |
| repo_id=REPO_ID, repo_type="dataset", | |
| commit_message=f"[{DOMAIN_FILTER}] final metadata β {total/1e12:.4f}T tokens", | |
| ) | |
| except Exception as e: | |
| print(f"β οΈ metadata upload failed: {e}", flush=True) | |
| print("=" * 68, flush=True) | |
| print(f"β DONE β {DOMAIN_FILTER}", flush=True) | |
| print(f" tokens : {total/1e12:.4f}T", flush=True) | |
| print(f" elapsed : {elapsed_h():.2f}h", flush=True) | |
| print(f" dataset : huggingface.co/datasets/{REPO_ID}", flush=True) | |
| print("=" * 68, flush=True) | |
| # ============================================================================== | |
| # LAUNCHER MAIN β MODE=launch (default), runs locally | |
| # uploads this script to Hub, fires tokenizer job, then 4 domain jobs | |
| # ============================================================================== | |
| # ============================================================================== | |
| # replace run_launcher() with this β fire-and-forget version | |
| # ============================================================================== | |
| def run_launcher(): | |
| from huggingface_hub import run_job | |
| api = get_api() | |
| ensure_repo(api) | |
| print("=" * 68, flush=True) | |
| print("π NOVA-1 LAUNCHER β fire and forget mode", flush=True) | |
| print(f" repo : {REPO_ID}", flush=True) | |
| print(f" hardware : CPU Performance (32 vCPU/256GB/1TB) $1.90/hr", flush=True) | |
| print("=" * 68, flush=True) | |
| # ββ upload script to Hub ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| script_path = os.path.abspath(__file__) | |
| print(f"\nβ¬οΈ uploading nova.py to Hub...", flush=True) | |
| with open(script_path, "rb") as f: | |
| api.upload_file( | |
| path_or_fileobj=f, | |
| path_in_repo="scripts/nova.py", | |
| repo_id=REPO_ID, repo_type="dataset", | |
| commit_message="update nova.py pipeline script", | |
| ) | |
| SCRIPT_URL = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/scripts/nova.py" | |
| print(f"β script live: {SCRIPT_URL}", flush=True) | |
| def make_bash(mode, domain="ALL"): | |
| return ( | |
| f"curl -fsSL -H 'Authorization: Bearer $HF_TOKEN' " | |
| f"'{SCRIPT_URL}' -o /tmp/nova.py && " | |
| f"HF_DATASETS_CACHE=/data/.hf_cache " | |
| f"MODE={mode} DOMAIN_FILTER={domain} " | |
| f"uv run /tmp/nova.py" | |
| ) | |
| common_env = { | |
| "REPO_ID": REPO_ID, | |
| "SHARD_ROWS": str(SHARD_ROWS), | |
| "JOB_TIMEOUT_H": "720", | |
| "TOKENIZERS_PARALLELISM": "false", | |
| "HF_XET_HIGH_PERFORMANCE": "1", | |
| "HF_DATASETS_DISABLE_PROGRESS_BARS": "1", | |
| "HF_HUB_DISABLE_PROGRESS_BARS": "1", | |
| "PYTHONUNBUFFERED": "1", | |
| } | |
| UV_IMAGE = "ghcr.io/astral-sh/uv:python3.12-bookworm" | |
| # ββ fire tokenizer job βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\nπ€ launching tokenizer job...", flush=True) | |
| tok_job = run_job( | |
| namespace="ml-intern-explorers", | |
| image=UV_IMAGE, | |
| command=["bash", "-c", make_bash("train_tokenizer")], | |
| flavor=FLAVOR, timeout="720h", | |
| secrets={"HF_TOKEN": HF_TOKEN}, | |
| env={**common_env, "MODE": "train_tokenizer"}, | |
| ) | |
| print(f" β tokenizer job β {tok_job.id}", flush=True) | |
| print(f" π {tok_job.url}", flush=True) | |
| # ββ fire a "waiter" job that blocks on the Hub, then launches domain jobs β | |
| # THIS is the key change: the waiting happens INSIDE an HF Job container, | |
| # not on your laptop. you can close your terminal immediately after this. | |
| print(f"\nβ³ launching orchestrator job (waits for tokenizer, then fires 4 domain jobs)...", flush=True) | |
| orchestrator_bash = ( | |
| f"curl -fsSL -H 'Authorization: Bearer $HF_TOKEN' " | |
| f"'{SCRIPT_URL}' -o /tmp/nova.py && " | |
| f"MODE=orchestrate TOKENIZER_JOB_ID={tok_job.id} " | |
| f"uv run /tmp/nova.py" | |
| ) | |
| orch_job = run_job( | |
| namespace="ml-intern-explorers", | |
| image=UV_IMAGE, | |
| command=["bash", "-c", orchestrator_bash], | |
| flavor="cpu-basic", # cheap flavor β this job just polls and calls run_job() | |
| timeout="720h", | |
| secrets={"HF_TOKEN": HF_TOKEN}, | |
| env={**common_env, "MODE": "orchestrate", "TOKENIZER_JOB_ID": tok_job.id}, | |
| ) | |
| print(f" β orchestrator β {orch_job.id}", flush=True) | |
| print(f" π {orch_job.url}", flush=True) | |
| print(f"\n{'='*68}", flush=True) | |
| print("β EVERYTHING LAUNCHED. close your laptop right now, it's fine.", flush=True) | |
| print(f" tokenizer job : {tok_job.id}", flush=True) | |
| print(f" orchestrator job : {orch_job.id} (will spawn the 4 domain jobs itself)", flush=True) | |
| print(f"\n check status any time at: https://huggingface.co/jobs", flush=True) | |
| print(f" dataset lands at: https://huggingface.co/datasets/{REPO_ID}", flush=True) | |
| print(f"{'='*68}\n", flush=True) | |
| # script exits here. nothing left running locally. jobs live entirely on HF. | |
| def run_orchestrate(): | |
| """ | |
| MODE=orchestrate β runs INSIDE a tiny cheap HF Job (cpu-basic). | |
| waits for the tokenizer job to finish, then launches the 4 domain jobs. | |
| this replaces the polling loop that used to run on your laptop. | |
| """ | |
| from huggingface_hub import run_job, inspect_job | |
| tok_job_id = os.environ["TOKENIZER_JOB_ID"] | |
| TERMINAL = {"COMPLETED", "ERROR", "CANCELED", "FAILED"} | |
| print(f"β³ orchestrator waiting on tokenizer job {tok_job_id}...", flush=True) | |
| while True: | |
| try: | |
| stage = inspect_job(job_id=tok_job_id, token=HF_TOKEN).status.stage | |
| except Exception: | |
| stage = "UNKNOWN" | |
| print(f" tokenizer job: {stage}", flush=True) | |
| if stage in TERMINAL: | |
| break | |
| time.sleep(60) | |
| if stage != "COMPLETED": | |
| print(f"β οΈ tokenizer job ended with {stage} β domain jobs will fall back to gpt2", flush=True) | |
| else: | |
| print("β tokenizer done", flush=True) | |
| SCRIPT_URL = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/scripts/nova.py" | |
| def make_bash(mode, domain="ALL"): | |
| return ( | |
| f"curl -fsSL -H 'Authorization: Bearer $HF_TOKEN' " | |
| f"'{SCRIPT_URL}' -o /tmp/nova.py && " | |
| f"HF_DATASETS_CACHE=/data/.hf_cache " | |
| f"MODE={mode} DOMAIN_FILTER={domain} " | |
| f"uv run /tmp/nova.py" | |
| ) | |
| common_env = { | |
| "REPO_ID": REPO_ID, | |
| "SHARD_ROWS": str(SHARD_ROWS), | |
| "JOB_TIMEOUT_H": "720", | |
| "TOKENIZERS_PARALLELISM": "false", | |
| "HF_XET_HIGH_PERFORMANCE": "1", | |
| "HF_DATASETS_DISABLE_PROGRESS_BARS": "1", | |
| "HF_HUB_DISABLE_PROGRESS_BARS": "1", | |
| "PYTHONUNBUFFERED": "1", | |
| } | |
| for domain in ["code", "general", "math", "reasoning"]: | |
| print(f"π launching [{domain}] domain job...", flush=True) | |
| job = run_job( | |
| namespace="ml-intern-explorers", | |
| image="ghcr.io/astral-sh/uv:python3.12-bookworm", | |
| command=["bash", "-c", make_bash("worker", domain)], | |
| flavor=FLAVOR, timeout="720h", | |
| secrets={"HF_TOKEN": HF_TOKEN}, | |
| env={**common_env, "MODE": "worker", "DOMAIN_FILTER": domain}, | |
| ) | |
| print(f" β {domain} β {job.id}", flush=True) | |
| print("β orchestrator done β all 4 domain jobs launched. exiting.", flush=True) | |
| # ============================================================================== | |
| # ENTRYPOINT | |
| # ============================================================================== | |
| if __name__ == "__main__": | |
| if MODE == "train_tokenizer": | |
| run_train_tokenizer() | |
| elif MODE == "worker": | |
| run_worker() | |
| elif MODE == "orchestrate": | |
| run_orchestrate() | |
| else: | |
| run_launcher() | |