Second training run: append data, start from the first run's head; upload missing draft weights
Browse files- control/reset.txt +1 -0
- control/run.env +12 -4
- emcdraft/extract.py +45 -10
- emcdraft/gen_vllm.py +44 -8
- emcdraft/sim.py +14 -3
- emcdraft/train.py +17 -10
- scripts/pipeline.sh +27 -8
- scripts/sync.py +17 -7
- tests/test_head.py +50 -0
control/reset.txt
CHANGED
|
@@ -1,3 +1,4 @@
|
|
| 1 |
# Requests to re-run pipeline stages on the GPU machine (read by scripts/supervise.py).
|
| 2 |
# One per line: <unique id> [kill] <stage> [<stage> ...] - each id is applied once;
|
| 3 |
# "kill" stops a running pipeline first. Example: r1-2 train eval_main
|
|
|
|
|
|
| 1 |
# Requests to re-run pipeline stages on the GPU machine (read by scripts/supervise.py).
|
| 2 |
# One per line: <unique id> [kill] <stage> [<stage> ...] - each id is applied once;
|
| 3 |
# "kill" stops a running pipeline first. Example: r1-2 train eval_main
|
| 4 |
+
r2 generate extract train eval_main report_main eval_alt report
|
control/run.env
CHANGED
|
@@ -1,5 +1,13 @@
|
|
| 1 |
# KEY=VALUE settings passed to scripts/pipeline.sh by scripts/supervise.py
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# KEY=VALUE settings passed to scripts/pipeline.sh by scripts/supervise.py
|
| 2 |
+
# second training run: twice the data (earlier answers and features kept), starting from the
|
| 3 |
+
# first run's head; only the FP8 variant is evaluated (the baseline was measured in run 1)
|
| 4 |
+
GEN_TOKENS=4000000
|
| 5 |
+
GEN_MINUTES=32
|
| 6 |
+
GEN_APPEND=1
|
| 7 |
+
EXTRACT_MINUTES=25
|
| 8 |
+
EXTRACT_APPEND=1
|
| 9 |
+
TRAIN_MINUTES=40
|
| 10 |
+
RUN_NAME=main2
|
| 11 |
+
TRAIN_INIT=runs/main/sub_bf16
|
| 12 |
+
EVAL_ALT=0
|
| 13 |
+
TRAIN_INIT_HF=mudassiruddin21/EMC:submissions/r1/main-bf16
|
emcdraft/extract.py
CHANGED
|
@@ -76,6 +76,35 @@ def featurize(tgt, seqs, max_tokens, agree):
|
|
| 76 |
return feats
|
| 77 |
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
def main():
|
| 80 |
ap = argparse.ArgumentParser()
|
| 81 |
ap.add_argument("--target", required=True)
|
|
@@ -90,12 +119,14 @@ def main():
|
|
| 90 |
ap.add_argument("--seed", type=int, default=0)
|
| 91 |
a = ap.parse_args()
|
| 92 |
out, res = Path(a.out), Path(a.results)
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
| 97 |
res.mkdir(parents=True, exist_ok=True)
|
| 98 |
-
report = {}
|
|
|
|
| 99 |
|
| 100 |
t0 = time.time()
|
| 101 |
tgt = Target(a.target)
|
|
@@ -139,10 +170,10 @@ def main():
|
|
| 139 |
# 2. generated training sequences
|
| 140 |
rng = random.Random(a.seed)
|
| 141 |
gen = []
|
| 142 |
-
for
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
r = json.loads(line)
|
| 147 |
if len(r["o"]) >= 8:
|
| 148 |
gen.append({"ids": r["p"] + r["o"], "P": len(r["p"]), "domain": d})
|
|
@@ -151,12 +182,14 @@ def main():
|
|
| 151 |
agree = defaultdict(lambda: [0, 0])
|
| 152 |
done = defaultdict(lambda: [0, 0])
|
| 153 |
t0 = time.time()
|
|
|
|
| 154 |
for g in range(0, len(gen), a.group):
|
| 155 |
if time.time() - t0 > a.minutes * 60:
|
| 156 |
log("time budget reached")
|
|
|
|
| 157 |
break
|
| 158 |
feats = featurize(tgt, gen[g:g + a.group], a.batch_tokens, agree)
|
| 159 |
-
save_shard(str(out / "train" / f"
|
| 160 |
for f in feats:
|
| 161 |
done[f["domain"]][0] += 1
|
| 162 |
done[f["domain"]][1] += f["T"] - f["P"]
|
|
@@ -166,6 +199,8 @@ def main():
|
|
| 166 |
report["train_sequences"] = {d: {"sequences": v[0], "generated_tokens": v[1]} for d, v in done.items()}
|
| 167 |
report["train_teacher_forced_agreement"] = {d: round(v[0] / max(1, v[1]), 4) for d, v in agree.items()}
|
| 168 |
report["extract_seconds"] = round(time.time() - t0, 1)
|
|
|
|
|
|
|
| 169 |
(res / "extract_checks.json").write_text(json.dumps(report, indent=2))
|
| 170 |
log(f"done: {report['train_sequences']}")
|
| 171 |
|
|
|
|
| 76 |
return feats
|
| 77 |
|
| 78 |
|
| 79 |
+
def shard_part(name: str) -> int:
|
| 80 |
+
"""Training shards of the first extraction are g0000...; later appended parts p<k>g0000..."""
|
| 81 |
+
return int(name[1:name.index("g")]) if name.startswith("p") else 1
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def plan_train(out: Path, gen: Path, append: bool):
|
| 85 |
+
"""Which generated files to featurize and how to name the new shards.
|
| 86 |
+
|
| 87 |
+
Returns (files, shard prefix, consumed file names, number of kept shards). Without append
|
| 88 |
+
every earlier shard is deleted. With append the shards are kept and only files not listed in
|
| 89 |
+
<out>/consumed_gen.json are featurized (a first extraction without that list consumed the
|
| 90 |
+
plain <domain>.jsonl files)."""
|
| 91 |
+
train = out / "train"
|
| 92 |
+
train.mkdir(parents=True, exist_ok=True)
|
| 93 |
+
kept = sorted(train.glob("*.json"))
|
| 94 |
+
if not append or not kept:
|
| 95 |
+
for p in train.glob("*"):
|
| 96 |
+
p.unlink()
|
| 97 |
+
kept, consumed, prefix = [], set(), "g"
|
| 98 |
+
else:
|
| 99 |
+
listed = out / "consumed_gen.json"
|
| 100 |
+
consumed = (set(json.loads(listed.read_text())) if listed.exists()
|
| 101 |
+
else {f"{d}.jsonl" for d in DOMAINS})
|
| 102 |
+
prefix = f"p{max(shard_part(p.stem) for p in kept) + 1}g"
|
| 103 |
+
files = [p for p in sorted(Path(gen).glob("*.jsonl"))
|
| 104 |
+
if p.name not in consumed and p.name.split(".")[0].split("-")[0] in DOMAINS]
|
| 105 |
+
return files, prefix, consumed, len(kept)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
def main():
|
| 109 |
ap = argparse.ArgumentParser()
|
| 110 |
ap.add_argument("--target", required=True)
|
|
|
|
| 119 |
ap.add_argument("--seed", type=int, default=0)
|
| 120 |
a = ap.parse_args()
|
| 121 |
out, res = Path(a.out), Path(a.results)
|
| 122 |
+
(out / "dev").mkdir(parents=True, exist_ok=True)
|
| 123 |
+
for p in (out / "dev").glob("*"):
|
| 124 |
+
p.unlink()
|
| 125 |
+
# EXTRACT_APPEND=1: keep the training shards of earlier extractions, featurize new files only
|
| 126 |
+
files, prefix, consumed, kept = plan_train(out, Path(a.gen), os.environ.get("EXTRACT_APPEND", "0") == "1")
|
| 127 |
res.mkdir(parents=True, exist_ok=True)
|
| 128 |
+
report = {"kept_train_shards": kept, "files": [p.name for p in files]}
|
| 129 |
+
log(f"training files to featurize: {report['files']} ({kept} earlier shards kept)")
|
| 130 |
|
| 131 |
t0 = time.time()
|
| 132 |
tgt = Target(a.target)
|
|
|
|
| 170 |
# 2. generated training sequences
|
| 171 |
rng = random.Random(a.seed)
|
| 172 |
gen = []
|
| 173 |
+
for p in files:
|
| 174 |
+
d = p.name.split(".")[0].split("-")[0]
|
| 175 |
+
for line in open(p):
|
| 176 |
+
if line.strip():
|
| 177 |
r = json.loads(line)
|
| 178 |
if len(r["o"]) >= 8:
|
| 179 |
gen.append({"ids": r["p"] + r["o"], "P": len(r["p"]), "domain": d})
|
|
|
|
| 182 |
agree = defaultdict(lambda: [0, 0])
|
| 183 |
done = defaultdict(lambda: [0, 0])
|
| 184 |
t0 = time.time()
|
| 185 |
+
complete = True
|
| 186 |
for g in range(0, len(gen), a.group):
|
| 187 |
if time.time() - t0 > a.minutes * 60:
|
| 188 |
log("time budget reached")
|
| 189 |
+
complete = False
|
| 190 |
break
|
| 191 |
feats = featurize(tgt, gen[g:g + a.group], a.batch_tokens, agree)
|
| 192 |
+
save_shard(str(out / "train" / f"{prefix}{g // a.group:04d}"), feats)
|
| 193 |
for f in feats:
|
| 194 |
done[f["domain"]][0] += 1
|
| 195 |
done[f["domain"]][1] += f["T"] - f["P"]
|
|
|
|
| 199 |
report["train_sequences"] = {d: {"sequences": v[0], "generated_tokens": v[1]} for d, v in done.items()}
|
| 200 |
report["train_teacher_forced_agreement"] = {d: round(v[0] / max(1, v[1]), 4) for d, v in agree.items()}
|
| 201 |
report["extract_seconds"] = round(time.time() - t0, 1)
|
| 202 |
+
if complete: # a file cut off by the time budget is not marked, so it is not skipped later
|
| 203 |
+
(out / "consumed_gen.json").write_text(json.dumps(sorted(consumed | {p.name for p in files})))
|
| 204 |
(res / "extract_checks.json").write_text(json.dumps(report, indent=2))
|
| 205 |
log(f"done: {report['train_sequences']}")
|
| 206 |
|
emcdraft/gen_vllm.py
CHANGED
|
@@ -43,6 +43,29 @@ def make_llm(target: str):
|
|
| 43 |
raise RuntimeError("could not start the engine")
|
| 44 |
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
def main():
|
| 47 |
ap = argparse.ArgumentParser()
|
| 48 |
ap.add_argument("--target", required=True)
|
|
@@ -57,17 +80,31 @@ def main():
|
|
| 57 |
rng = random.Random(a.seed)
|
| 58 |
out = Path(a.out)
|
| 59 |
out.mkdir(parents=True, exist_ok=True)
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
items = []
|
| 64 |
for d in DOMAINS:
|
| 65 |
pool = [json.loads(line)["ids"] for line in open(Path(a.prompts) / f"{d}.jsonl") if line.strip()]
|
| 66 |
rng.shuffle(pool)
|
| 67 |
want = math.ceil(1.1 * a.tokens * SHARE[d] / MEAN_LEN[d])
|
| 68 |
-
|
| 69 |
-
|
|
|
|
| 70 |
rng.shuffle(items)
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
from vllm import SamplingParams
|
| 73 |
sp = {d: SamplingParams(temperature=0.0, max_tokens=MAX_NEW[d], stop_token_ids=STOP_IDS,
|
|
@@ -76,9 +113,7 @@ def main():
|
|
| 76 |
llm = make_llm(a.target)
|
| 77 |
log(f"engine ready in {time.time() - t0:.0f}s")
|
| 78 |
t0 = time.time()
|
| 79 |
-
|
| 80 |
-
files = {d: open(out / f"{d}.jsonl", "a") for d in DOMAINS}
|
| 81 |
-
total = 0
|
| 82 |
for s in range(0, len(items), a.chunk):
|
| 83 |
if time.time() - t0 > a.minutes * 60 or total >= a.tokens:
|
| 84 |
log("budget reached")
|
|
@@ -102,7 +137,8 @@ def main():
|
|
| 102 |
f"(total {total})")
|
| 103 |
for f in files.values():
|
| 104 |
f.close()
|
| 105 |
-
report = {"seconds": round(time.time() - t0, 1), "generated_tokens": total, "
|
|
|
|
| 106 |
Path(a.results).mkdir(parents=True, exist_ok=True)
|
| 107 |
(Path(a.results) / "generation.json").write_text(json.dumps(report, indent=2))
|
| 108 |
log(f"generated {total} tokens in {report['seconds']}s")
|
|
|
|
| 43 |
raise RuntimeError("could not start the engine")
|
| 44 |
|
| 45 |
|
| 46 |
+
def previous_outputs(out: Path):
|
| 47 |
+
"""Answers already generated in `out` (any <domain>*.jsonl file): the prompts per domain,
|
| 48 |
+
per-domain statistics, the token total, and the next free file suffix for new answers."""
|
| 49 |
+
seen = {d: set() for d in DOMAINS}
|
| 50 |
+
stats = {d: {"sequences": 0, "generated_tokens": 0, "stopped": 0} for d in DOMAINS}
|
| 51 |
+
total = 0
|
| 52 |
+
for d in DOMAINS:
|
| 53 |
+
for p in sorted(out.glob(f"{d}*.jsonl")):
|
| 54 |
+
for line in open(p):
|
| 55 |
+
if not line.strip():
|
| 56 |
+
continue
|
| 57 |
+
r = json.loads(line)
|
| 58 |
+
seen[d].add(tuple(r["p"]))
|
| 59 |
+
stats[d]["sequences"] += 1
|
| 60 |
+
stats[d]["generated_tokens"] += len(r["o"])
|
| 61 |
+
stats[d]["stopped"] += int(bool(r["o"]) and r["o"][-1] in STOP_IDS)
|
| 62 |
+
total += len(r["o"])
|
| 63 |
+
part = 2
|
| 64 |
+
while any((out / f"{d}-{part}.jsonl").exists() for d in DOMAINS):
|
| 65 |
+
part += 1
|
| 66 |
+
return seen, stats, total, f"-{part}"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
def main():
|
| 70 |
ap = argparse.ArgumentParser()
|
| 71 |
ap.add_argument("--target", required=True)
|
|
|
|
| 80 |
rng = random.Random(a.seed)
|
| 81 |
out = Path(a.out)
|
| 82 |
out.mkdir(parents=True, exist_ok=True)
|
| 83 |
+
# GEN_APPEND=1: keep earlier answers, count them towards --tokens and write new ones to
|
| 84 |
+
# <domain>-<n>.jsonl (prompt selection is a superset of the earlier one: same seed)
|
| 85 |
+
if os.environ.get("GEN_APPEND", "0") == "1":
|
| 86 |
+
seen, stats, total, suffix = previous_outputs(out)
|
| 87 |
+
log(f"append mode: {total} tokens already generated; new answers go to *{suffix}.jsonl")
|
| 88 |
+
else:
|
| 89 |
+
for p in out.glob("*.jsonl"):
|
| 90 |
+
p.unlink()
|
| 91 |
+
seen = {d: set() for d in DOMAINS}
|
| 92 |
+
stats = {d: {"sequences": 0, "generated_tokens": 0, "stopped": 0} for d in DOMAINS}
|
| 93 |
+
total, suffix = 0, ""
|
| 94 |
+
previous = total
|
| 95 |
|
| 96 |
items = []
|
| 97 |
for d in DOMAINS:
|
| 98 |
pool = [json.loads(line)["ids"] for line in open(Path(a.prompts) / f"{d}.jsonl") if line.strip()]
|
| 99 |
rng.shuffle(pool)
|
| 100 |
want = math.ceil(1.1 * a.tokens * SHARE[d] / MEAN_LEN[d])
|
| 101 |
+
new = [(d, ids) for ids in pool[:want] if tuple(ids) not in seen[d]]
|
| 102 |
+
items += new
|
| 103 |
+
log(f"{d}: {len(new)} new prompts (pool {len(pool)}, {len(seen[d])} answered before)")
|
| 104 |
rng.shuffle(items)
|
| 105 |
+
if not items or total >= a.tokens:
|
| 106 |
+
log("nothing to generate")
|
| 107 |
+
return
|
| 108 |
|
| 109 |
from vllm import SamplingParams
|
| 110 |
sp = {d: SamplingParams(temperature=0.0, max_tokens=MAX_NEW[d], stop_token_ids=STOP_IDS,
|
|
|
|
| 113 |
llm = make_llm(a.target)
|
| 114 |
log(f"engine ready in {time.time() - t0:.0f}s")
|
| 115 |
t0 = time.time()
|
| 116 |
+
files = {d: open(out / f"{d}{suffix}.jsonl", "a") for d in DOMAINS}
|
|
|
|
|
|
|
| 117 |
for s in range(0, len(items), a.chunk):
|
| 118 |
if time.time() - t0 > a.minutes * 60 or total >= a.tokens:
|
| 119 |
log("budget reached")
|
|
|
|
| 137 |
f"(total {total})")
|
| 138 |
for f in files.values():
|
| 139 |
f.close()
|
| 140 |
+
report = {"seconds": round(time.time() - t0, 1), "generated_tokens": total, "previous_tokens": previous,
|
| 141 |
+
"by_domain": stats}
|
| 142 |
Path(a.results).mkdir(parents=True, exist_ok=True)
|
| 143 |
(Path(a.results) / "generation.json").write_text(json.dumps(report, indent=2))
|
| 144 |
log(f"generated {total} tokens in {report['seconds']}s")
|
emcdraft/sim.py
CHANGED
|
@@ -32,24 +32,33 @@ def save_shard(stem: str, seqs: list[dict]):
|
|
| 32 |
Path(stem + ".json").write_text(json.dumps(meta))
|
| 33 |
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
def load_shards(data_dir, device, max_tokens: int | None = None) -> list[dict]:
|
|
|
|
|
|
|
| 36 |
seqs, total = [], 0
|
| 37 |
for meta_path in sorted(Path(data_dir).glob("*.json")):
|
| 38 |
stem = str(meta_path)[:-5]
|
|
|
|
|
|
|
| 39 |
meta = json.loads(meta_path.read_text())
|
| 40 |
tok = torch.from_numpy(np.load(stem + ".tok.npy").astype(np.int64)).to(device)
|
| 41 |
hid = torch.from_numpy(np.load(stem + ".hid.npy")).view(torch.bfloat16).to(device)
|
| 42 |
to = ho = 0
|
| 43 |
for T, P, dom, sid in zip(meta["T"], meta["P"], meta["domain"], meta["id"]):
|
| 44 |
seqs.append({"tokens": tok[to:to + T], "hidden": hid[ho:ho + T - 1], "P": P, "T": T,
|
| 45 |
-
"domain": dom, "id": sid})
|
| 46 |
to, ho, total = to + T, ho + T - 1, total + T
|
| 47 |
if max_tokens and total >= max_tokens:
|
| 48 |
break
|
| 49 |
return seqs
|
| 50 |
|
| 51 |
|
| 52 |
-
def collate(seqs: list[dict], pad: int = 0):
|
|
|
|
| 53 |
B, Tm = len(seqs), max(s["T"] for s in seqs)
|
| 54 |
dev = seqs[0]["tokens"].device
|
| 55 |
H = seqs[0]["hidden"].shape[-1]
|
|
@@ -60,6 +69,8 @@ def collate(seqs: list[dict], pad: int = 0):
|
|
| 60 |
hidden[b, :s["T"] - 1] = s["hidden"]
|
| 61 |
P = torch.tensor([s["P"] for s in seqs], device=dev)
|
| 62 |
T = torch.tensor([s["T"] for s in seqs], device=dev)
|
|
|
|
|
|
|
| 63 |
return tokens, hidden, P, T
|
| 64 |
|
| 65 |
|
|
@@ -93,7 +104,7 @@ def simulate(head, embed, W, seqs: list[dict], K: int = 3, max_tokens: int = 120
|
|
| 93 |
hit, tot = [0] * K, [0] * K
|
| 94 |
cuda = W.is_cuda
|
| 95 |
for group in batches(seqs, max_tokens):
|
| 96 |
-
tokens, hidden, P, T = collate(group)
|
| 97 |
B, Tm = tokens.shape
|
| 98 |
N = Tm - 1
|
| 99 |
base = torch.arange(N, device=tokens.device)
|
|
|
|
| 32 |
Path(stem + ".json").write_text(json.dumps(meta))
|
| 33 |
|
| 34 |
|
| 35 |
+
def shards_bytes(data_dir) -> int:
|
| 36 |
+
return sum(p.stat().st_size for p in Path(data_dir).glob("*.hid.npy"))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
def load_shards(data_dir, device, max_tokens: int | None = None) -> list[dict]:
|
| 40 |
+
"""Every sequence of the shards in `data_dir` (sorted by name), with the extraction part it
|
| 41 |
+
came from (shards g... are part 1, appended shards p<k>g... part k)."""
|
| 42 |
seqs, total = [], 0
|
| 43 |
for meta_path in sorted(Path(data_dir).glob("*.json")):
|
| 44 |
stem = str(meta_path)[:-5]
|
| 45 |
+
name = meta_path.stem
|
| 46 |
+
part = int(name[1:name.index("g")]) if name.startswith("p") else 1
|
| 47 |
meta = json.loads(meta_path.read_text())
|
| 48 |
tok = torch.from_numpy(np.load(stem + ".tok.npy").astype(np.int64)).to(device)
|
| 49 |
hid = torch.from_numpy(np.load(stem + ".hid.npy")).view(torch.bfloat16).to(device)
|
| 50 |
to = ho = 0
|
| 51 |
for T, P, dom, sid in zip(meta["T"], meta["P"], meta["domain"], meta["id"]):
|
| 52 |
seqs.append({"tokens": tok[to:to + T], "hidden": hid[ho:ho + T - 1], "P": P, "T": T,
|
| 53 |
+
"domain": dom, "id": sid, "part": part})
|
| 54 |
to, ho, total = to + T, ho + T - 1, total + T
|
| 55 |
if max_tokens and total >= max_tokens:
|
| 56 |
break
|
| 57 |
return seqs
|
| 58 |
|
| 59 |
|
| 60 |
+
def collate(seqs: list[dict], pad: int = 0, device=None):
|
| 61 |
+
"""Pad a group into (tokens, hidden, P, T); built where the data lives, then moved to `device`."""
|
| 62 |
B, Tm = len(seqs), max(s["T"] for s in seqs)
|
| 63 |
dev = seqs[0]["tokens"].device
|
| 64 |
H = seqs[0]["hidden"].shape[-1]
|
|
|
|
| 69 |
hidden[b, :s["T"] - 1] = s["hidden"]
|
| 70 |
P = torch.tensor([s["P"] for s in seqs], device=dev)
|
| 71 |
T = torch.tensor([s["T"] for s in seqs], device=dev)
|
| 72 |
+
if device is not None and torch.device(device) != torch.device(dev):
|
| 73 |
+
tokens, hidden, P, T = (x.to(device) for x in (tokens, hidden, P, T))
|
| 74 |
return tokens, hidden, P, T
|
| 75 |
|
| 76 |
|
|
|
|
| 104 |
hit, tot = [0] * K, [0] * K
|
| 105 |
cuda = W.is_cuda
|
| 106 |
for group in batches(seqs, max_tokens):
|
| 107 |
+
tokens, hidden, P, T = collate(group, device=W.device)
|
| 108 |
B, Tm = tokens.shape
|
| 109 |
N = Tm - 1
|
| 110 |
base = torch.arange(N, device=tokens.device)
|
emcdraft/train.py
CHANGED
|
@@ -25,7 +25,7 @@ import torch.nn.functional as F
|
|
| 25 |
|
| 26 |
from .head import (FP8_TENSORS, HeadConfig, build_head, e4m3_round, equalize_, export_submission,
|
| 27 |
load_mtp_state, load_target_tensors, unroll)
|
| 28 |
-
from .sim import DOMAINS, batches, collate, load_shards, simulate
|
| 29 |
|
| 30 |
|
| 31 |
def log(msg):
|
|
@@ -135,13 +135,20 @@ def main():
|
|
| 135 |
embed = lambda ids: F.embedding(ids, E)
|
| 136 |
head = build_head(load_mtp_state(a.init), cfg, dev)
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
dev_seqs = load_shards(a.dev, dev) if a.dev and Path(a.dev).exists() else []
|
| 141 |
tok_by = {d: sum(s["T"] - s["P"] for s in seqs if s["domain"] == d) for d in DOMAINS}
|
| 142 |
-
log(f"data: {len(train)} train / {len(val)} val sequences
|
|
|
|
| 143 |
summary = {"args": vars(a), "data": {"train_sequences": len(train), "val_sequences": len(val),
|
| 144 |
-
"generated_tokens": tok_by}, "sim": {}}
|
| 145 |
|
| 146 |
def sims(tag):
|
| 147 |
r = {"val": simulate(head, embed, W, val)}
|
|
@@ -154,9 +161,9 @@ def main():
|
|
| 154 |
f"steps {[round(x, 3) for x in r['dev']['step_accuracy']]}" if dev_seqs else ""))
|
| 155 |
return r
|
| 156 |
|
| 157 |
-
sims("
|
| 158 |
if a.qat:
|
| 159 |
-
probe = collate(val[:2])
|
| 160 |
with torch.no_grad():
|
| 161 |
ref, _ = head.step(embed(probe[0][:, 1:]).float(), probe[1].float(),
|
| 162 |
torch.arange(probe[0].shape[1] - 1, device=dev)[None].expand(2, -1))
|
|
@@ -182,7 +189,7 @@ def main():
|
|
| 182 |
total_steps = max(1, int(per_epoch * a.epochs))
|
| 183 |
warm = max(5, total_steps // 30)
|
| 184 |
key = "val"
|
| 185 |
-
best = {"tau": summary["sim"]["fp8_untrained" if a.qat else "
|
| 186 |
"step": 0, "state": {k: v.detach().clone() for k, v in head.state_dict().items()}}
|
| 187 |
log(f"training: {total_steps} steps planned ({per_epoch}/epoch), qat={a.qat}")
|
| 188 |
step, t0, hist = 0, time.time(), []
|
|
@@ -199,7 +206,7 @@ def main():
|
|
| 199 |
f = (step + 1) / warm if step < warm else 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (step - warm) / max(1, total_steps - warm)))
|
| 200 |
for g in opt.param_groups:
|
| 201 |
g["lr"] = g["base"] * f
|
| 202 |
-
loss, info = train_step(head, embed, W, collate(group), a)
|
| 203 |
opt.zero_grad(set_to_none=True)
|
| 204 |
loss.backward()
|
| 205 |
torch.nn.utils.clip_grad_norm_(head.parameters(), 1.0)
|
|
@@ -237,7 +244,7 @@ def main():
|
|
| 237 |
"built-in head and fine-tuned with a 3-step recursive drafting objective"
|
| 238 |
+ (" and FP8 (E4M3) quantisation-aware training" if a.qat else "")),
|
| 239 |
"training_data": ("Greedy answers of the target itself (with its hidden states) to public "
|
| 240 |
-
"instruction prompts: GSM8K/
|
| 241 |
"Python instruction sets; dev prompts excluded")}
|
| 242 |
tcfg = Path(a.target) / "config.json"
|
| 243 |
if a.qat:
|
|
|
|
| 25 |
|
| 26 |
from .head import (FP8_TENSORS, HeadConfig, build_head, e4m3_round, equalize_, export_submission,
|
| 27 |
load_mtp_state, load_target_tensors, unroll)
|
| 28 |
+
from .sim import DOMAINS, batches, collate, load_shards, shards_bytes, simulate
|
| 29 |
|
| 30 |
|
| 31 |
def log(msg):
|
|
|
|
| 135 |
embed = lambda ids: F.embedding(ids, E)
|
| 136 |
head = build_head(load_mtp_state(a.init), cfg, dev)
|
| 137 |
|
| 138 |
+
# hidden states stay on the GPU while they fit comfortably, otherwise in host memory and
|
| 139 |
+
# each batch is copied over (TRAIN_DATA_DEVICE=cpu|cuda overrides)
|
| 140 |
+
data_dev = os.environ.get("TRAIN_DATA_DEVICE") or ("cpu" if shards_bytes(a.data) > 24e9 else dev)
|
| 141 |
+
seqs = load_shards(a.data, data_dev)
|
| 142 |
+
# validation comes from the first extraction only, so with appended data it is the same
|
| 143 |
+
# hold-out set as in the earlier run (whose head may be the starting point here)
|
| 144 |
+
train, val = split_val([s for s in seqs if s["part"] == 1], 0.05, rng)
|
| 145 |
+
train += [s for s in seqs if s["part"] != 1]
|
| 146 |
dev_seqs = load_shards(a.dev, dev) if a.dev and Path(a.dev).exists() else []
|
| 147 |
tok_by = {d: sum(s["T"] - s["P"] for s in seqs if s["domain"] == d) for d in DOMAINS}
|
| 148 |
+
log(f"data: {len(train)} train / {len(val)} val sequences (held on {data_dev}), "
|
| 149 |
+
f"generated tokens by domain {tok_by}")
|
| 150 |
summary = {"args": vars(a), "data": {"train_sequences": len(train), "val_sequences": len(val),
|
| 151 |
+
"generated_tokens": tok_by, "data_device": data_dev}, "sim": {}}
|
| 152 |
|
| 153 |
def sims(tag):
|
| 154 |
r = {"val": simulate(head, embed, W, val)}
|
|
|
|
| 161 |
f"steps {[round(x, 3) for x in r['dev']['step_accuracy']]}" if dev_seqs else ""))
|
| 162 |
return r
|
| 163 |
|
| 164 |
+
sims("init")
|
| 165 |
if a.qat:
|
| 166 |
+
probe = collate(val[:2], device=dev)
|
| 167 |
with torch.no_grad():
|
| 168 |
ref, _ = head.step(embed(probe[0][:, 1:]).float(), probe[1].float(),
|
| 169 |
torch.arange(probe[0].shape[1] - 1, device=dev)[None].expand(2, -1))
|
|
|
|
| 189 |
total_steps = max(1, int(per_epoch * a.epochs))
|
| 190 |
warm = max(5, total_steps // 30)
|
| 191 |
key = "val"
|
| 192 |
+
best = {"tau": summary["sim"]["fp8_untrained" if a.qat else "init"][key]["acceptance_length"],
|
| 193 |
"step": 0, "state": {k: v.detach().clone() for k, v in head.state_dict().items()}}
|
| 194 |
log(f"training: {total_steps} steps planned ({per_epoch}/epoch), qat={a.qat}")
|
| 195 |
step, t0, hist = 0, time.time(), []
|
|
|
|
| 206 |
f = (step + 1) / warm if step < warm else 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (step - warm) / max(1, total_steps - warm)))
|
| 207 |
for g in opt.param_groups:
|
| 208 |
g["lr"] = g["base"] * f
|
| 209 |
+
loss, info = train_step(head, embed, W, collate(group, device=dev), a)
|
| 210 |
opt.zero_grad(set_to_none=True)
|
| 211 |
loss.backward()
|
| 212 |
torch.nn.utils.clip_grad_norm_(head.parameters(), 1.0)
|
|
|
|
| 244 |
"built-in head and fine-tuned with a 3-step recursive drafting objective"
|
| 245 |
+ (" and FP8 (E4M3) quantisation-aware training" if a.qat else "")),
|
| 246 |
"training_data": ("Greedy answers of the target itself (with its hidden states) to public "
|
| 247 |
+
"instruction prompts: GSM8K/Orca-Math, WritingPrompts, UltraChat/Alpaca/Dolly, "
|
| 248 |
"Python instruction sets; dev prompts excluded")}
|
| 249 |
tcfg = Path(a.target) / "config.json"
|
| 250 |
if a.qat:
|
scripts/pipeline.sh
CHANGED
|
@@ -25,6 +25,11 @@ export TORCHINDUCTOR_CACHE_DIR="$WORK/cache/inductor" TRITON_CACHE_DIR="$WORK/ca
|
|
| 25 |
# greedy decoding only: use the built-in sampler instead of compiling FlashInfer kernels at start-up
|
| 26 |
export VLLM_USE_FLASHINFER_SAMPLER=0
|
| 27 |
[ -f "$STATE/run_id" ] || echo "${RUN_ID:-$(date +%Y%m%d-%H%M)}" > "$STATE/run_id"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOGS/pipeline.log"; }
|
| 30 |
sync_hf() { if [ -x "$PY" ]; then "$PY" "$REPO/scripts/sync.py" "$@" >> "$LOGS/sync.log" 2>&1 || true; fi; }
|
|
@@ -122,20 +127,34 @@ s_generate() { "$PY" -m emcdraft.gen_vllm --target "$TARGET" --prompts "$DATA/pr
|
|
| 122 |
s_extract() { "$PY" -m emcdraft.extract --target "$TARGET" --kit "$KIT" --baseline "$BASELINE" --gen "$DATA/gen" --out "$DATA" --results "$RESULTS"; }
|
| 123 |
s_train() {
|
| 124 |
local qat=""; [ -f "$STATE/fp8_ok" ] && qat="--qat"
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
}
|
| 129 |
-
primary() { if [ -d "$
|
| 130 |
-
s_eval_main() { local p; p=$(primary); SUB="$p" TAG="
|
| 131 |
s_eval_baseline() { SUB="$BASELINE" TAG=eval_baseline kit eval; }
|
| 132 |
s_eval_alt() {
|
| 133 |
-
if [
|
| 134 |
-
|
|
|
|
| 135 |
}
|
| 136 |
s_report() { "$PY" "$REPO/scripts/collect.py"; }
|
| 137 |
|
| 138 |
-
log "pipeline start: run $(cat "$STATE/run_id"), code $(cat "$REPO/.commit" 2>/dev/null | cut -c1-12)"
|
| 139 |
# a vLLM server left behind by an interrupted run would still hold the GPU
|
| 140 |
if pkill -f -- "--served-model-name target" 2>/dev/null; then log "stopped a leftover vLLM server"; sleep 20; fi
|
| 141 |
stage env 1 s_env
|
|
|
|
| 25 |
# greedy decoding only: use the built-in sampler instead of compiling FlashInfer kernels at start-up
|
| 26 |
export VLLM_USE_FLASHINFER_SAMPLER=0
|
| 27 |
[ -f "$STATE/run_id" ] || echo "${RUN_ID:-$(date +%Y%m%d-%H%M)}" > "$STATE/run_id"
|
| 28 |
+
# training run name (runs/<name>), its starting weights and whether to also evaluate the bf16 variant
|
| 29 |
+
RUN_NAME="${RUN_NAME:-main}"; TRAIN_INIT="${TRAIN_INIT:-$BASELINE}"; EVAL_ALT="${EVAL_ALT:-1}"
|
| 30 |
+
case "$TRAIN_INIT" in /*) ;; *) TRAIN_INIT="$EMC_ROOT/$TRAIN_INIT" ;; esac
|
| 31 |
+
OUTRUN="$RUNS/$RUN_NAME"
|
| 32 |
+
if [ "$RUN_NAME" = main ]; then EVAL_PREFIX=eval_draft; else EVAL_PREFIX="eval_$RUN_NAME"; fi
|
| 33 |
|
| 34 |
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOGS/pipeline.log"; }
|
| 35 |
sync_hf() { if [ -x "$PY" ]; then "$PY" "$REPO/scripts/sync.py" "$@" >> "$LOGS/sync.log" 2>&1 || true; fi; }
|
|
|
|
| 127 |
s_extract() { "$PY" -m emcdraft.extract --target "$TARGET" --kit "$KIT" --baseline "$BASELINE" --gen "$DATA/gen" --out "$DATA" --results "$RESULTS"; }
|
| 128 |
s_train() {
|
| 129 |
local qat=""; [ -f "$STATE/fp8_ok" ] && qat="--qat"
|
| 130 |
+
if [ ! -d "$TRAIN_INIT" ] && [ -n "${TRAIN_INIT_HF:-}" ]; then # e.g. on a fresh machine
|
| 131 |
+
"$PY" - "$TRAIN_INIT_HF" "$TRAIN_INIT" <<'PYEOF'
|
| 132 |
+
import shutil, sys
|
| 133 |
+
from pathlib import Path
|
| 134 |
+
from huggingface_hub import snapshot_download
|
| 135 |
+
repo, sub = sys.argv[1].split(":", 1)
|
| 136 |
+
src = Path(snapshot_download(repo, repo_type="dataset", allow_patterns=[sub + "/*"])) / sub
|
| 137 |
+
Path(sys.argv[2]).parent.mkdir(parents=True, exist_ok=True)
|
| 138 |
+
shutil.copytree(src, sys.argv[2])
|
| 139 |
+
print("starting weights downloaded from", sys.argv[1])
|
| 140 |
+
PYEOF
|
| 141 |
+
fi
|
| 142 |
+
[ -d "$TRAIN_INIT" ] || { echo "starting weights $TRAIN_INIT not found"; return 1; }
|
| 143 |
+
rm -rf "$OUTRUN"
|
| 144 |
+
"$PY" -m emcdraft.train --target "$TARGET" --init "$TRAIN_INIT" --data "$DATA/train" --dev "$DATA/dev" --out "$OUTRUN" $qat
|
| 145 |
+
for s in "$OUTRUN"/sub_*; do SUB="$s" kit validate; done
|
| 146 |
}
|
| 147 |
+
primary() { if [ -d "$OUTRUN/sub_fp8" ]; then echo "$OUTRUN/sub_fp8"; else echo "$OUTRUN/sub_bf16"; fi; }
|
| 148 |
+
s_eval_main() { local p; p=$(primary); SUB="$p" TAG="${EVAL_PREFIX}_$(basename "$p" | sed 's/^sub_//')" kit eval; }
|
| 149 |
s_eval_baseline() { SUB="$BASELINE" TAG=eval_baseline kit eval; }
|
| 150 |
s_eval_alt() {
|
| 151 |
+
if [ "$EVAL_ALT" != 1 ]; then echo "bf16 variant not evaluated (EVAL_ALT=$EVAL_ALT)"; return 0; fi
|
| 152 |
+
if [ ! -d "$OUTRUN/sub_fp8" ]; then echo "only one variant"; return 0; fi
|
| 153 |
+
SUB="$OUTRUN/sub_bf16" TAG="${EVAL_PREFIX}_bf16" kit eval
|
| 154 |
}
|
| 155 |
s_report() { "$PY" "$REPO/scripts/collect.py"; }
|
| 156 |
|
| 157 |
+
log "pipeline start: run $(cat "$STATE/run_id"), code $(cat "$REPO/.commit" 2>/dev/null | cut -c1-12), training run $RUN_NAME"
|
| 158 |
# a vLLM server left behind by an interrupted run would still hold the GPU
|
| 159 |
if pkill -f -- "--served-model-name target" 2>/dev/null; then log "stopped a leftover vLLM server"; sleep 20; fi
|
| 160 |
stage env 1 s_env
|
scripts/sync.py
CHANGED
|
@@ -91,13 +91,23 @@ def main():
|
|
| 91 |
api.upload_folder(folder_path=str(stage), repo_id=REPO_ID, repo_type="dataset",
|
| 92 |
path_in_repo=f"runs/{run_id}", commit_message=f"Run {run_id}: logs and results")
|
| 93 |
print(f"uploaded logs/results to {REPO_ID}:runs/{run_id}")
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
finally:
|
| 102 |
shutil.rmtree(stage, ignore_errors=True)
|
| 103 |
return 0
|
|
|
|
| 91 |
api.upload_folder(folder_path=str(stage), repo_id=REPO_ID, repo_type="dataset",
|
| 92 |
path_in_repo=f"runs/{run_id}", commit_message=f"Run {run_id}: logs and results")
|
| 93 |
print(f"uploaded logs/results to {REPO_ID}:runs/{run_id}")
|
| 94 |
+
# draft folders: all of them with --submissions, otherwise any whose files are not on
|
| 95 |
+
# the Hub yet (so finished weights get saved even if the machine stops early)
|
| 96 |
+
subs = sorted(p for p in ROOT.glob("runs/*/sub_*") if p.is_dir())
|
| 97 |
+
have = set()
|
| 98 |
+
if subs and "--submissions" not in sys.argv:
|
| 99 |
+
try:
|
| 100 |
+
have = set(api.list_repo_files(REPO_ID, repo_type="dataset"))
|
| 101 |
+
except Exception as e: # noqa: BLE001
|
| 102 |
+
print(f"could not list the repository: {e}")
|
| 103 |
+
for sub in subs:
|
| 104 |
+
name = f"{sub.parent.name}-{sub.name[4:]}"
|
| 105 |
+
dest = f"submissions/{run_id}/{name}"
|
| 106 |
+
missing = [p.name for p in sub.iterdir() if p.is_file() and f"{dest}/{p.name}" not in have]
|
| 107 |
+
if "--submissions" in sys.argv or missing:
|
| 108 |
+
info = api.upload_folder(folder_path=str(sub), repo_id=REPO_ID, repo_type="dataset",
|
| 109 |
+
path_in_repo=dest, commit_message=f"Run {run_id}: draft model {name}")
|
| 110 |
+
print(f"uploaded {sub.name} to {REPO_ID}:{dest} ({info})")
|
| 111 |
finally:
|
| 112 |
shutil.rmtree(stage, ignore_errors=True)
|
| 113 |
return 0
|
tests/test_head.py
CHANGED
|
@@ -197,6 +197,55 @@ def test_helpers():
|
|
| 197 |
print(" supervisor branch lookup skipped (no network):", e)
|
| 198 |
|
| 199 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
if __name__ == "__main__":
|
| 201 |
head = MTPHead(C)
|
| 202 |
for p in head.parameters():
|
|
@@ -209,4 +258,5 @@ if __name__ == "__main__":
|
|
| 209 |
print("walk"); test_walk()
|
| 210 |
print("train/export"); test_train_and_export(head, E, W)
|
| 211 |
print("helpers"); test_helpers()
|
|
|
|
| 212 |
print("ALL OK")
|
|
|
|
| 197 |
print(" supervisor branch lookup skipped (no network):", e)
|
| 198 |
|
| 199 |
|
| 200 |
+
def test_append():
|
| 201 |
+
"""Adding data to an earlier run: earlier answers and feature shards are kept, only new files
|
| 202 |
+
are processed, and validation still comes from the first extraction."""
|
| 203 |
+
from emcdraft.extract import plan_train
|
| 204 |
+
from emcdraft.gen_vllm import previous_outputs
|
| 205 |
+
from emcdraft.sim import load_shards, save_shard
|
| 206 |
+
from emcdraft.train import split_val
|
| 207 |
+
|
| 208 |
+
def shard(stem, n, d, seed):
|
| 209 |
+
g = torch.Generator().manual_seed(seed)
|
| 210 |
+
seqs = [{"tokens": torch.randint(0, V, (12,), generator=g), "hidden": torch.randn(11, C.hidden, generator=g),
|
| 211 |
+
"P": 3, "domain": d, "id": f"{seed}-{i}"} for i in range(n)]
|
| 212 |
+
save_shard(str(stem), seqs)
|
| 213 |
+
|
| 214 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 215 |
+
gen, data = Path(tmp) / "gen", Path(tmp) / "data"
|
| 216 |
+
gen.mkdir()
|
| 217 |
+
(gen / "chat.jsonl").write_text(json.dumps({"p": [1, 2], "o": [5, 6, 248046]}) + "\n")
|
| 218 |
+
(gen / "code.jsonl").write_text(json.dumps({"p": [3], "o": [7] * 9}) + "\n")
|
| 219 |
+
seen, stats, total, suffix = previous_outputs(gen)
|
| 220 |
+
assert seen["chat"] == {(1, 2)} and total == 12 and suffix == "-2" and stats["chat"]["stopped"] == 1
|
| 221 |
+
|
| 222 |
+
files, prefix, consumed, kept = plan_train(data, gen, append=False) # first extraction
|
| 223 |
+
assert [p.name for p in files] == ["chat.jsonl", "code.jsonl"] and prefix == "g" and kept == 0
|
| 224 |
+
shard(data / "train" / "g0000", 20, "chat", 1) # (no consumed list, as in run 1)
|
| 225 |
+
|
| 226 |
+
(gen / "chat-2.jsonl").write_text(json.dumps({"p": [4], "o": [8] * 9}) + "\n")
|
| 227 |
+
assert previous_outputs(gen)[2] == 21 and previous_outputs(gen)[3] == "-3"
|
| 228 |
+
files, prefix, consumed, kept = plan_train(data, gen, append=True)
|
| 229 |
+
assert [p.name for p in files] == ["chat-2.jsonl"] and prefix == "p2g" and kept == 1, (files, prefix, kept)
|
| 230 |
+
shard(data / "train" / "p2g0000", 5, "chat", 2)
|
| 231 |
+
(data / "consumed_gen.json").write_text(json.dumps(sorted(consumed | {"chat-2.jsonl"})))
|
| 232 |
+
(gen / "code-3.jsonl").write_text(json.dumps({"p": [9], "o": [8] * 9}) + "\n")
|
| 233 |
+
files, prefix, _, kept = plan_train(data, gen, append=True)
|
| 234 |
+
assert [p.name for p in files] == ["code-3.jsonl"] and prefix == "p3g" and kept == 2
|
| 235 |
+
|
| 236 |
+
seqs = load_shards(data / "train", "cpu")
|
| 237 |
+
assert [s["part"] for s in seqs] == [1] * 20 + [2] * 5
|
| 238 |
+
first = [s for s in seqs if s["part"] == 1]
|
| 239 |
+
_, val_a = split_val(first, 0.05, random.Random(0))
|
| 240 |
+
_, val_b = split_val(load_shards(data / "train" , "cpu")[:20], 0.05, random.Random(0))
|
| 241 |
+
assert [s["id"] for s in val_a] == [s["id"] for s in val_b] and all(s["part"] == 1 for s in val_a)
|
| 242 |
+
t, h, P, T = collate(seqs[:3], device="cpu")
|
| 243 |
+
assert h.shape == (3, 11, C.hidden) and t.device.type == "cpu"
|
| 244 |
+
plan_train(data, gen, append=False) # a fresh run clears the shards
|
| 245 |
+
assert not list((data / "train").glob("*"))
|
| 246 |
+
print(" append: earlier answers and shards kept, new files only, same validation split")
|
| 247 |
+
|
| 248 |
+
|
| 249 |
if __name__ == "__main__":
|
| 250 |
head = MTPHead(C)
|
| 251 |
for p in head.parameters():
|
|
|
|
| 258 |
print("walk"); test_walk()
|
| 259 |
print("train/export"); test_train_and_export(head, E, W)
|
| 260 |
print("helpers"); test_helpers()
|
| 261 |
+
print("append"); test_append()
|
| 262 |
print("ALL OK")
|