Upload training_v2/data/curriculum_dataset.py with huggingface_hub
Browse files
training_v2/data/curriculum_dataset.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Curriculum dataset with replay buffer for continual pre-training.
|
| 2 |
+
|
| 3 |
+
Mixes multiple phase corpora at configurable ratios so later phases keep seeing
|
| 4 |
+
earlier-phase data (replay), preventing catastrophic forgetting of conversation
|
| 5 |
+
ability when training on technical content.
|
| 6 |
+
|
| 7 |
+
Each shard directory is treated as one big concatenated stream of token IDs.
|
| 8 |
+
We memory-map the .bin files so we can sample windows of `block_size+1` tokens
|
| 9 |
+
without loading anything into RAM upfront.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import random
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
from torch.utils.data import IterableDataset
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _load_shards(phase_dir, dtype):
|
| 22 |
+
phase_dir = Path(phase_dir)
|
| 23 |
+
shards = sorted(phase_dir.glob("*.bin"))
|
| 24 |
+
if not shards:
|
| 25 |
+
raise FileNotFoundError(f"no shards under {phase_dir}")
|
| 26 |
+
arrs = [np.memmap(s, dtype=dtype, mode="r") for s in shards]
|
| 27 |
+
sizes = np.array([a.shape[0] for a in arrs], dtype=np.int64)
|
| 28 |
+
total = int(sizes.sum())
|
| 29 |
+
return arrs, sizes, total
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class PhaseStream:
|
| 33 |
+
"""Random-window sampler over the concatenation of all shards in one phase."""
|
| 34 |
+
|
| 35 |
+
def __init__(self, phase_dir, block_size, dtype=np.uint16, seed=0):
|
| 36 |
+
self.dir = Path(phase_dir)
|
| 37 |
+
self.block_size = block_size
|
| 38 |
+
self.arrs, self.sizes, self.total = _load_shards(phase_dir, dtype)
|
| 39 |
+
self.cum = np.concatenate([[0], np.cumsum(self.sizes)])
|
| 40 |
+
self.rng = np.random.default_rng(seed)
|
| 41 |
+
if self.total <= block_size + 1:
|
| 42 |
+
raise ValueError(f"phase {phase_dir} too small: {self.total} <= {block_size+1}")
|
| 43 |
+
|
| 44 |
+
def sample(self):
|
| 45 |
+
start = int(self.rng.integers(0, self.total - self.block_size - 1))
|
| 46 |
+
shard_idx = int(np.searchsorted(self.cum, start, side="right") - 1)
|
| 47 |
+
local_start = start - int(self.cum[shard_idx])
|
| 48 |
+
end_local = local_start + self.block_size + 1
|
| 49 |
+
a = self.arrs[shard_idx]
|
| 50 |
+
if end_local <= a.shape[0]:
|
| 51 |
+
buf = np.asarray(a[local_start:end_local], dtype=np.int64)
|
| 52 |
+
else:
|
| 53 |
+
head = np.asarray(a[local_start:], dtype=np.int64)
|
| 54 |
+
need = self.block_size + 1 - head.shape[0]
|
| 55 |
+
nxt = self.arrs[(shard_idx + 1) % len(self.arrs)]
|
| 56 |
+
tail = np.asarray(nxt[:need], dtype=np.int64)
|
| 57 |
+
buf = np.concatenate([head, tail])
|
| 58 |
+
return buf
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class MixedCurriculumDataset(IterableDataset):
|
| 62 |
+
"""Sample from multiple phases according to mixing weights.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
phase_dirs: dict {name: path}
|
| 66 |
+
weights: dict {name: float} (will be normalized)
|
| 67 |
+
block_size: context length per sample
|
| 68 |
+
dtype: numpy dtype of binary shards
|
| 69 |
+
seed: base RNG seed (offset by worker id)
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(self, phase_dirs, weights, block_size, dtype=np.uint16, seed=0):
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.phase_dirs = phase_dirs
|
| 75 |
+
self.weights = weights
|
| 76 |
+
self.block_size = block_size
|
| 77 |
+
self.dtype = dtype
|
| 78 |
+
self.seed = seed
|
| 79 |
+
|
| 80 |
+
names = [n for n in phase_dirs if weights.get(n, 0) > 0]
|
| 81 |
+
if not names:
|
| 82 |
+
raise ValueError("at least one phase must have weight > 0")
|
| 83 |
+
ws = np.array([weights[n] for n in names], dtype=np.float64)
|
| 84 |
+
ws = ws / ws.sum()
|
| 85 |
+
self.names = names
|
| 86 |
+
self.probs = ws
|
| 87 |
+
|
| 88 |
+
def __iter__(self):
|
| 89 |
+
info = torch.utils.data.get_worker_info()
|
| 90 |
+
worker_id = info.id if info is not None else 0
|
| 91 |
+
seed = self.seed + worker_id * 1009
|
| 92 |
+
streams = {n: PhaseStream(self.phase_dirs[n], self.block_size,
|
| 93 |
+
dtype=self.dtype, seed=seed + i)
|
| 94 |
+
for i, n in enumerate(self.names)}
|
| 95 |
+
rng = np.random.default_rng(seed + 7919)
|
| 96 |
+
while True:
|
| 97 |
+
name = self.names[int(rng.choice(len(self.names), p=self.probs))]
|
| 98 |
+
buf = streams[name].sample()
|
| 99 |
+
x = torch.from_numpy(buf[:-1]).long()
|
| 100 |
+
y = torch.from_numpy(buf[1:]).long()
|
| 101 |
+
yield x, y, name
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def load_phase_summary(out_root):
|
| 105 |
+
summary_path = Path(out_root) / "summary.json"
|
| 106 |
+
return json.loads(summary_path.read_text()) if summary_path.exists() else {}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def make_phase_mix(phase_idx, replay_conv=None, replay_tech=None):
|
| 110 |
+
"""Return mixing weights for each curriculum phase.
|
| 111 |
+
|
| 112 |
+
Phase 1 (conversational base): 100% conv
|
| 113 |
+
Phase 2 (cybersec, with replay): (1-replay_conv) tech + replay_conv conv
|
| 114 |
+
Phase 3 (tools, with replay): 0.7 tools + replay_tech tech + replay_conv conv
|
| 115 |
+
|
| 116 |
+
Defaults match v2 (25%/10%). For v4 (less subtitle contamination)
|
| 117 |
+
pass replay_conv=0.10 in phase 2.
|
| 118 |
+
"""
|
| 119 |
+
if phase_idx == 1:
|
| 120 |
+
return {"phase1_conv": 1.0, "phase2_tech": 0.0, "phase3_tools": 0.0}
|
| 121 |
+
if phase_idx == 2:
|
| 122 |
+
rc = 0.25 if replay_conv is None else replay_conv
|
| 123 |
+
return {"phase1_conv": rc, "phase2_tech": 1.0 - rc, "phase3_tools": 0.0}
|
| 124 |
+
if phase_idx == 3:
|
| 125 |
+
rc = 0.10 if replay_conv is None else replay_conv
|
| 126 |
+
rt = 0.20 if replay_tech is None else replay_tech
|
| 127 |
+
return {"phase1_conv": rc, "phase2_tech": rt, "phase3_tools": 1.0 - rc - rt}
|
| 128 |
+
raise ValueError(f"phase_idx must be 1..3, got {phase_idx}")
|