Stage 1 checkpoint step 15521: code/stage1_dataloader.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545"""Resumable multi-source streaming parquet dataloader for Cortex Stage 1 pretraining.
Uses fast local shard staging via huggingface_hub.hf_hub_download (with hf_transfer)and single-threaded PyArrow/Rust-Tokenizer reads to completely eliminate fsspec/aiohttpand C++ threadpool deadlocks/SIGSEGVs under torch.compile + 4x A100 DDP.Local shards are deleted immediately after consumption so disk usage stays tiny (<5 GB)."""from __future__ import annotations
import jsonimport osimport queueimport tempfileimport threadingimport timefrom typing import Any, Dict, List, Optional, Tuple
# Prevent Rust Rayon / PyArrow C++ threadpool contention with torch.compile Inductor threadsos.environ.setdefault("TOKENIZERS_PARALLELISM", "false")os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
import numpy as npimport pyarrow as paimport pyarrow.parquet as pqimport torchimport torch.distributed as distfrom huggingface_hub import hf_hub_downloadfrom tokenizers import Tokenizer
try: pa.set_cpu_count(2) pa.set_io_thread_count(2)except Exception: pass
class _SourceStreamWorker: """Downloads one parquet shard at a time to local SSD, filters, tokenizes, and packs.
Optional FIM (Fill-in-the-Middle) mode: - Domain-weighted FIM rate (e.g. 50% on code, 10% on math/science/prose) - 50/50 PSM (<PRE> pre <SUF> suf <MID> mid <EOS>) and SPM (<SUF> suf <PRE> pre <MID> mid <EOS>) - Applied strictly inside single-document <=1024-token windows before packing so <PRE>, <SUF>, <MID>, and <EOS> always stay in the exact same training sequence - Skips documents under 64 tokens """
def __init__( self, src_cfg: Dict[str, Any], tokenizer_path: str, eos_id: int, span: int, rank: int, world_size: int, hf_token: Optional[str], cache_root: str, resume_cursor: Optional[Dict[str, Any]] = None, seq_queue_size: int = 256, doc_batch_size: int = 64, exclude_files: Optional[set] = None, fim_rate: float = 0.0, fim_pre_id: Optional[int] = None, fim_mid_id: Optional[int] = None, fim_suf_id: Optional[int] = None, seq_len: int = 1024, seed: int = 1337, ): self.name = src_cfg["name"] self.repo = src_cfg["repo"] self.text_col = src_cfg["text_col"] self.filter_col = src_cfg.get("filter_col") self.filter_min = src_cfg.get("filter_min") self.span = int(span) self.seq_len = int(seq_len) self.eos_id = int(eos_id) self.doc_batch_size = int(doc_batch_size) self.hf_token = hf_token self.rank = int(rank) self.fim_rate = float(fim_rate) self.fim_pre_id = fim_pre_id self.fim_mid_id = fim_mid_id self.fim_suf_id = fim_suf_id self._fim_enabled = ( self.fim_rate > 0.0 and self.fim_pre_id is not None and self.fim_mid_id is not None and self.fim_suf_id is not None ) self._fim_rng = np.random.default_rng(seed + rank * 7919 + (abs(hash(self.name)) % 100003)) self.cache_dir = os.path.join(cache_root, f"r{rank}_{self.name}") os.makedirs(self.cache_dir, exist_ok=True) self.tokenizer = Tokenizer.from_file(tokenizer_path)
all_files = [f for f in src_cfg["files"] if not exclude_files or f not in exclude_files] if len(all_files) >= world_size: self.rank_files = all_files[rank::world_size] else: self.rank_files = [all_files[(rank + i) % len(all_files)] for i in range(len(all_files))] if not self.rank_files: raise RuntimeError(f"Source {self.name} has 0 files for rank {rank}")
rc = resume_cursor or {} self.start_file_idx = int(rc.get("file_idx", 0)) % len(self.rank_files) self.start_rg_idx = int(rc.get("row_group_idx", 0)) self.start_doc_in_rg = int(rc.get("doc_in_rg", 0)) self.start_epoch = int(rc.get("epoch", 0))
self.queue: "queue.Queue[Any]" = queue.Queue(maxsize=seq_queue_size) self._stop_event = threading.Event() self.error: Optional[BaseException] = None self._thread = threading.Thread( target=self._run, name=f"src-{self.name}-r{rank}", daemon=True ) self._thread.start()
def _download_shard(self, file_path: str, max_retries: int = 5) -> Optional[str]: last_exc = None for attempt in range(max_retries): if self._stop_event.is_set(): return None try: local_path = hf_hub_download( repo_id=self.repo, filename=file_path, repo_type="dataset", token=self.hf_token, local_dir=self.cache_dir, ) return local_path except Exception as exc: last_exc = exc time.sleep(min(20.0, 2.0 * (2 ** attempt))) raise RuntimeError( f"[{self.name}] Failed to download {file_path} after {max_retries} retries: {last_exc}" ) from last_exc
def _run(self): cols = [self.text_col] + ([self.filter_col] if self.filter_col else []) file_idx = self.start_file_idx rg_skip = self.start_rg_idx doc_skip = self.start_doc_in_rg epoch = self.start_epoch
buf = np.empty(0, dtype=np.int64) pending_texts: List[str] = [] last_cursor = { "file_idx": file_idx, "row_group_idx": rg_skip, "doc_in_rg": doc_skip, "epoch": epoch, }
try: while not self._stop_event.is_set(): file_path = self.rank_files[file_idx] local_path = self._download_shard(file_path) if local_path is None: return try: pf = pq.ParquetFile(local_path) n_rgs = pf.num_row_groups start_rg = rg_skip if rg_skip < n_rgs else 0 rg_skip = 0 for rg_idx in range(start_rg, n_rgs): if self._stop_event.is_set(): return row_offset = 0 for batch in pf.iter_batches( batch_size=512, row_groups=[rg_idx], columns=cols, use_threads=False, ): if self._stop_event.is_set(): return n_batch = batch.num_rows if doc_skip >= row_offset + n_batch: row_offset += n_batch continue texts = batch.column(self.text_col).to_pylist() scores = batch.column(self.filter_col).to_pylist() if self.filter_col else None local_start = max(0, doc_skip - row_offset) doc_skip = 0
for i in range(local_start, n_batch): if self._stop_event.is_set(): return if scores is not None: sc = scores[i] if sc is None or sc < self.filter_min: continue txt = texts[i] if not isinstance(txt, str) or len(txt) < 20: continue pending_texts.append(txt) last_cursor = { "file_idx": file_idx, "row_group_idx": rg_idx, "doc_in_rg": row_offset + i + 1, "epoch": epoch, } if len(pending_texts) < self.doc_batch_size: continue
encs = self.tokenizer.encode_batch(pending_texts, add_special_tokens=False) pending_texts.clear() chunks = [buf] if buf.size else [] cur_len = buf.size for e in encs: ids = e.ids if not ids: continue n_tok = len(ids) # Apply single-document <=1024-token FIM (50/50 PSM/SPM) without crossing sequence boundaries rem_in_seq = self.span - (cur_len % self.span) if ( self._fim_enabled and n_tok >= 64 and rem_in_seq >= 68 and self._fim_rng.random() < self.fim_rate ): max_win = min(n_tok, rem_in_seq - 4, self.seq_len - 4) if n_tok > max_win: w0 = int(self._fim_rng.integers(0, n_tok - max_win + 1)) win = ids[w0 : w0 + max_win] else: win = ids wn = len(win) # Choose non-empty prefix, middle (5%-35% of window), and suffix min_mid = max(4, int(0.05 * wn)) max_mid = max(min_mid + 1, min(wn - 8, int(0.35 * wn))) mid_len = int(self._fim_rng.integers(min_mid, max_mid + 1)) split_i = int(self._fim_rng.integers(4, wn - mid_len - 3)) pre = win[:split_i] mid = win[split_i : split_i + mid_len] suf = win[split_i + mid_len :] if self._fim_rng.random() < 0.5: # PSM: <PRE> prefix <SUF> suffix <MID> middle <EOS> seq_ids = ( [self.fim_pre_id] + pre + [self.fim_suf_id] + suf + [self.fim_mid_id] + mid + [self.eos_id] ) else: # SPM: <SUF> suffix <PRE> prefix <MID> middle <EOS> seq_ids = ( [self.fim_suf_id] + suf + [self.fim_pre_id] + pre + [self.fim_mid_id] + mid + [self.eos_id] ) arr = np.asarray(seq_ids, dtype=np.int64) else: arr = np.empty(n_tok + 1, dtype=np.int64) arr[:-1] = ids arr[-1] = self.eos_id chunks.append(arr) cur_len += arr.size if not chunks: continue buf = np.concatenate(chunks) if len(chunks) > 1 else chunks[0] while buf.size >= self.span: seq = np.ascontiguousarray(buf[: self.span]) buf = buf[self.span :] cur_snap = dict(last_cursor) while not self._stop_event.is_set(): try: self.queue.put((seq, cur_snap), timeout=0.5) break except queue.Full: continue row_offset += n_batch finally: # Remove finished local shard to keep SSD usage minimal try: if os.path.exists(local_path): os.remove(local_path) except Exception: pass
file_idx += 1 if file_idx >= len(self.rank_files): file_idx = 0 epoch += 1 except BaseException as exc: self.error = exc try: self.queue.put(exc, timeout=1.0) except Exception: pass
def get_seq(self) -> Tuple[np.ndarray, Dict[str, Any]]: item = self.queue.get() if isinstance(item, BaseException): raise RuntimeError(f"Source worker {self.name} failed: {item}") from item return item
def close(self): self._stop_event.set() while not self.queue.empty(): try: self.queue.get_nowait() except queue.Empty: break if self._thread.is_alive(): self._thread.join(timeout=2.0)
class Stage1MultiSourceLoader: """6-source weighted streaming dataloader with local SSD staging and exact resumability."""
def __init__( self, manifest_path: str, tokenizer_path: str, seq_len: int, batch_size: int, device: torch.device, extra_horizon: int = 2, prefetch_batches: int = 12, val_seqs: int = 32, seed: int = 1337, hf_token: Optional[str] = None, resume_state: Optional[Dict[str, Any]] = None, cache_root: Optional[str] = None, enable_fim: bool = False, fim_rate_code: float = 0.50, fim_rate_other: float = 0.10, ): with open(manifest_path, "r", encoding="utf-8") as f: manifest = json.load(f)
self.sources_cfg = manifest["sources"] self.seq_len = int(seq_len) self.batch_size = int(batch_size) self.device = device self.extra_horizon = int(extra_horizon) self.span = self.seq_len + self.extra_horizon self.rank = dist.get_rank() if dist.is_initialized() else 0 self.world_size = dist.get_world_size() if dist.is_initialized() else 1 self.hf_token = hf_token or os.environ.get("HF_TOKEN") self.cache_root = cache_root or os.path.expanduser("~/cortex_shard_cache") os.makedirs(self.cache_root, exist_ok=True)
self.tokenizer = Tokenizer.from_file(tokenizer_path) self.eos_id = self.tokenizer.token_to_id("<|endoftext|>") if self.eos_id is None: raise ValueError("Tokenizer missing <|endoftext|>") self.fim_pre_id = self.tokenizer.token_to_id("<|fim_pre|>") self.fim_mid_id = self.tokenizer.token_to_id("<|fim_mid|>") self.fim_suf_id = self.tokenizer.token_to_id("<|fim_suf|>") self.enable_fim = bool(enable_fim) self.fim_rate_code = float(fim_rate_code) self.fim_rate_other = float(fim_rate_other)
weights = np.array([s["weight"] for s in self.sources_cfg], dtype=np.float64) self.weights = weights / weights.sum() self.source_names = [s["name"] for s in self.sources_cfg]
# Hold out the last parquet of FineWeb-Edu for fixed validation PPL & effort-scaling eval fw_cfg = self.sources_cfg[0] val_file = fw_cfg["files"][-1] exclude_val = {val_file}
val_len = val_seqs * (self.seq_len + 1) val_tensor = torch.empty(val_len, dtype=torch.int32, device=device) if self.rank == 0: val_arr, val_prompts = self._build_val_slice(fw_cfg, val_file, val_len) val_tensor.copy_(torch.from_numpy(val_arr.astype(np.int32)).to(device)) self.val_prompts = val_prompts else: self.val_prompts = [] if dist.is_initialized(): dist.broadcast(val_tensor, src=0) self.data = val_tensor.cpu().numpy().astype(np.uint32)
# Restore mixer RNG and source cursors if resuming self._rng = np.random.default_rng(seed + self.rank * 10007) resume_cursors = {} self.seqs_consumed = {name: 0 for name in self.source_names} self.source_cursors: Dict[str, Dict[str, Any]] = { name: {"file_idx": 0, "row_group_idx": 0, "doc_in_rg": 0, "epoch": 0} for name in self.source_names } if resume_state: if "rng_state" in resume_state: self._rng.bit_generator.state = resume_state["rng_state"] if "source_cursors" in resume_state: resume_cursors = resume_state["source_cursors"] for k, v in resume_cursors.items(): if k in self.source_cursors: self.source_cursors[k] = dict(v) if "seqs_consumed" in resume_state: for k, v in resume_state["seqs_consumed"].items(): if k in self.seqs_consumed: self.seqs_consumed[k] = int(v)
# Spawn 1 background worker per source self._workers: List[_SourceStreamWorker] = [] for s_cfg in self.sources_cfg: if self.enable_fim: s_fim_rate = self.fim_rate_code if "stack" in s_cfg["name"].lower() else self.fim_rate_other else: s_fim_rate = 0.0 w = _SourceStreamWorker( src_cfg=s_cfg, tokenizer_path=tokenizer_path, eos_id=self.eos_id, span=self.span, rank=self.rank, world_size=self.world_size, hf_token=self.hf_token, cache_root=self.cache_root, resume_cursor=resume_cursors.get(s_cfg["name"]), seq_queue_size=max(128, int(640 * s_cfg["weight"])), doc_batch_size=64, exclude_files=exclude_val if s_cfg["name"] == fw_cfg["name"] else None, fim_rate=s_fim_rate, fim_pre_id=self.fim_pre_id, fim_mid_id=self.fim_mid_id, fim_suf_id=self.fim_suf_id, seq_len=self.seq_len, seed=seed, ) self._workers.append(w)
self._stop_event = threading.Event() self._batch_queue: "queue.Queue[Any]" = queue.Queue(maxsize=prefetch_batches) self._mixer_thread = threading.Thread( target=self._mixer_loop, name=f"stage1-mixer-r{self.rank}", daemon=True ) self._mixer_thread.start()
def _build_val_slice(self, fw_cfg: Dict[str, Any], val_file: str, val_len: int): val_dir = os.path.join(self.cache_root, "val_slice") os.makedirs(val_dir, exist_ok=True) local_path = hf_hub_download( repo_id=fw_cfg["repo"], filename=val_file, repo_type="dataset", token=self.hf_token, local_dir=val_dir, ) cols = [fw_cfg["text_col"]] + ([fw_cfg["filter_col"]] if fw_cfg.get("filter_col") else []) ids_out: List[int] = [] prompts: List[str] = [] try: pf = pq.ParquetFile(local_path) for batch in pf.iter_batches(batch_size=256, columns=cols, use_threads=False): texts = batch.column(fw_cfg["text_col"]).to_pylist() scores = batch.column(fw_cfg["filter_col"]).to_pylist() if fw_cfg.get("filter_col") else None good = [] for i, t in enumerate(texts): if scores is not None and (scores[i] is None or scores[i] < fw_cfg["filter_min"]): continue if isinstance(t, str) and len(t) > 80: good.append(t) if len(prompts) < 6: snip = " ".join(t.strip().split()[:24]) if len(snip) > 30: prompts.append(snip) if not good: continue for enc in self.tokenizer.encode_batch(good, add_special_tokens=False): if enc.ids: ids_out.extend(enc.ids) ids_out.append(self.eos_id) if len(ids_out) >= val_len: break finally: try: if os.path.exists(local_path): os.remove(local_path) except Exception: pass return np.asarray(ids_out[:val_len], dtype=np.int64), prompts
def _mixer_loop(self): try: while not self._stop_event.is_set(): src_ids = self._rng.choice(len(self._workers), size=self.batch_size, p=self.weights) rng_state_after = dict(self._rng.bit_generator.state) rows = np.empty((self.batch_size, self.span), dtype=np.int64) cursor_updates: Dict[str, Dict[str, Any]] = {} counts_delta: Dict[str, int] = {} for b_idx, s_idx in enumerate(src_ids): if self._stop_event.is_set(): return seq, cur_snap = self._workers[s_idx].get_seq() rows[b_idx] = seq sname = self.source_names[s_idx] cursor_updates[sname] = cur_snap counts_delta[sname] = counts_delta.get(sname, 0) + 1
# Keep plain CPU tensor (avoid calling CUDA pin_memory from background thread!) t = torch.from_numpy(rows) payload = (t, cursor_updates, counts_delta, rng_state_after) while not self._stop_event.is_set(): try: self._batch_queue.put(payload, timeout=0.5) break except queue.Full: continue except BaseException as exc: try: self._batch_queue.put(exc, timeout=1.0) except Exception: pass
def next_batch(self): item = self._batch_queue.get() if isinstance(item, BaseException): raise RuntimeError(f"Stage1MultiSourceLoader failed: {item}") from item chunk, cursor_updates, counts_delta, rng_state_after = item for sname, cur in cursor_updates.items(): self.source_cursors[sname] = cur for sname, cnt in counts_delta.items(): self.seqs_consumed[sname] = self.seqs_consumed.get(sname, 0) + cnt self._last_consumed_rng_state = rng_state_after
gpu_chunk = chunk.to(self.device, non_blocking=False) return gpu_chunk[:, : self.seq_len], [ gpu_chunk[:, k : k + self.seq_len] for k in range(1, self.extra_horizon + 1) ]
def get_state(self) -> Dict[str, Any]: return { "source_cursors": {k: dict(v) for k, v in self.source_cursors.items()}, "seqs_consumed": dict(self.seqs_consumed), "rng_state": getattr(self, "_last_consumed_rng_state", dict(self._rng.bit_generator.state)), }
def close(self): self._stop_event.set() for w in self._workers: w.close() while not self._batch_queue.empty(): try: self._batch_queue.get_nowait() except queue.Empty: break if self._mixer_thread.is_alive(): self._mixer_thread.join(timeout=2.0)code/stage1_dataloader.pyAdded+545