Cion-lab commited on
Commit
11456a3
·
verified ·
1 Parent(s): 7c925b7

train: train_ounce100m -- static-review fixes: absolute-step cursor, hub_listing pagination, cursor required on resume, repo_type everywhere, rank-0 repo create

Browse files
Files changed (1) hide show
  1. train/train_ounce100m.py +65 -33
train/train_ounce100m.py CHANGED
@@ -73,13 +73,15 @@ def count_params(model):
73
 
74
 
75
  # The cursor arithmetic in one place, because three separate bugs live here:
76
- # - a step consumes micro_batch * world sequences, not micro_batch (DDP shards the batch);
77
- # - on resume, Trainer restores global_step from the checkpoint but our dataset was ALREADY sliced to
78
- # start there, so the total is start_sample + step_within_this_run * seqs_per_step;
 
 
79
  # - max_steps is the TOTAL horizon (it is what the LR schedule decays against), so resuming mid-run
80
  # must keep the same steps_planned or the trapezoid changes shape.
81
- def samples_at(step_in_run, start_sample, seqs_per_step):
82
- return start_sample + int(step_in_run) * seqs_per_step
83
 
84
 
85
  class TrapezoidTrainer(Trainer):
@@ -115,11 +117,11 @@ class HubPush(TrainerCallback):
115
  copy on a disk that can be taken away at any moment.
116
  """
117
 
118
- def __init__(self, repo, api, token, seq_len, seed, fingerprint, start_sample, seqs_per_step,
119
- prune=True, min_free_gb=6.0):
120
  self.repo, self.api, self.token = repo, api, token
121
  self.seq_len, self.seed, self.fingerprint = seq_len, seed, fingerprint
122
- self.start_sample, self.seqs_per_step = start_sample, seqs_per_step
123
  self.prune, self.min_free_gb = prune, min_free_gb
124
  self.n = 0
125
  self.results = []
@@ -131,16 +133,17 @@ class HubPush(TrainerCallback):
131
  d = os.path.join(args.output_dir, f"checkpoint-{step}")
132
  if not os.path.isdir(d):
133
  raise RuntimeError(f"Trainer reported a save but {d} does not exist")
134
- samples = samples_at(step, self.start_sample, self.seqs_per_step)
135
- SD.save_cursor(d, SD.cursor_dict(self.seq_len, samples, self.seed, self.fingerprint))
 
136
  t0 = time.time()
137
  res = hubckpt.push_and_prune(self.repo, d, f"ckpt/checkpoint-{step}", self.api,
138
- token=self.token, prune=self.prune,
139
  min_free_gb=self.min_free_gb)
140
  hubckpt.write_latest_pointer(self.repo, {
141
  "path_in_repo": f"ckpt/checkpoint-{step}", "step": step, "samples_consumed": samples,
142
  "tokens_consumed": samples * self.seq_len, "fingerprint": self.fingerprint,
143
- "seed": self.seed}, self.api, token=self.token)
144
  loss = next((h["loss"] for h in reversed(state.log_history) if "loss" in h), None)
145
  print(f"CKPT {step} samples={samples:,} push+verify={round(time.time()-t0,1)}s "
146
  f"ok={res['verify']['ok']} pruned={res.get('pruned')} free={res['free_after_gb']}GB "
@@ -189,7 +192,10 @@ def main():
189
 
190
  store = SD.PackedTokenStore(args.root, man)
191
  fingerprint = SD.mix_fingerprint(args.root, man)
192
- tokens_per_step = args.micro_batch * args.seq_len * args.accum * world
 
 
 
193
  steps_planned = args.max_steps or int(args.tokens / tokens_per_step)
194
  say(f"mix: {store.total_tokens:,} tokens in {len(store.shards)} shards fp={fingerprint} "
195
  f"| {tokens_per_step:,} tok/step x {steps_planned} steps = "
@@ -204,30 +210,51 @@ def main():
204
  import ounce100m_credentials
205
  ounce100m_credentials.install()
206
  from huggingface_hub import HfApi
207
- ptr = hubckpt.latest_pointer(args.hub_repo, repo_type=args.hub_repo_type)
208
- if "error" in ptr:
209
- say(f"no latest pointer on {args.hub_repo} ({ptr['error']}) -> starting from step 0")
 
 
210
  args.resume = ""
 
 
 
 
 
211
  else:
212
  dest = os.path.join(args.out, os.path.basename(ptr["path_in_repo"]))
213
  say(f"auto-resume: hub says step {ptr.get('step')} at {ptr['path_in_repo']}")
214
- got = hubckpt.download_checkpoint(args.hub_repo, ptr["path_in_repo"], dest,
215
- HfApi(), repo_type=args.hub_repo_type)
216
  say(f"downloaded {got['files']} files, {got['bytes']/1e6:.0f} MB in {got['seconds']}s")
217
  if got["bytes"] < 1_000_000:
218
  raise SystemExit("auto-resume downloaded a checkpoint that is not real weights")
219
  args.resume = got["dir"]
220
  say(f"resuming from {args.resume}")
221
  cur = SD.load_cursor(args.resume) if args.resume else None
 
 
 
 
 
222
  if args.resume:
223
  say(f"resume from {args.resume} cursor={cur}")
224
  start_sample = (cur or {}).get("samples_consumed", 0)
 
225
  if cur:
226
  for k, v in (("seq_len", args.seq_len), ("shuffle_seed", args.data_seed),
227
  ("dataset_files_sha", fingerprint)):
228
  if cur.get(k) != v:
229
  raise SystemExit(f"resume refused: cursor {k}={cur.get(k)} != current {v}. "
230
  "A resumed run must read the same data in the same order (§3.1).")
 
 
 
 
 
 
 
 
231
 
232
  train_ds = SD.make_dataset(store, args.seq_len, args.data_seed, start_sample=start_sample)
233
  # Validation comes from the mix's held-out val/ shards, never from the training stream: scoring on
@@ -247,9 +274,7 @@ def main():
247
  if not (90_000_000 <= pc["sum_numel"] <= 110_000_000) and not args.layers and not args.hidden:
248
  raise SystemExit(f"parameter count {pc['sum_numel']:,} is outside §2's 90-110M budget")
249
 
250
- seqs_per_step = args.micro_batch * world * args.accum
251
- if seqs_per_step * args.seq_len != tokens_per_step:
252
- raise SystemExit("internal: batch arithmetic disagrees, token/step accounting is unreliable")
253
  ckpt_every = args.push_every_steps or max(1, steps_planned // 10)
254
 
255
  api = None
@@ -258,10 +283,12 @@ def main():
258
  ounce100m_credentials.install()
259
  from huggingface_hub import HfApi
260
  api = HfApi()
261
- # create-if-absent AND LFS patterns: see hubckpt.ensure_repo for the failure this prevents
262
- say("ckpt repo:", json.dumps(hubckpt.ensure_repo(args.hub_repo, api,
263
- os.environ.get("HF_TOKEN"),
264
- args.hub_repo_type)))
 
 
265
  say(f"checkpoint hub target {args.hub_repo} (prune={args.prune}, every {ckpt_every} steps)")
266
 
267
  tacc = TrainingArguments(
@@ -301,8 +328,8 @@ def main():
301
  )
302
  if api is not None:
303
  tr.add_callback(HubPush(args.hub_repo, api, os.environ.get("HF_TOKEN"), args.seq_len,
304
- args.data_seed, fingerprint, start_sample, seqs_per_step,
305
- prune=args.prune))
306
 
307
  # Precision must be ASSERTED, not configured: bf16 "works" silently on Turing and fp32 master
308
  # weights can be lost in a refactor (docs/00-platform-notes.md §8, memory/ERRORS.md E-006). The
@@ -333,9 +360,9 @@ def main():
333
 
334
  elapsed = time.time() - t0
335
  step = tr.state.global_step
336
- samples = samples_at(step, start_sample, seqs_per_step)
337
  consumed = samples * args.seq_len
338
- consumed_this_run = step * tokens_per_step
339
  hist = [h for h in tr.state.log_history if "loss" in h]
340
  final_loss = hist[-1]["loss"] if hist else None
341
  say(f"TRAIN DONE step={step}/{steps_planned} elapsed={elapsed/60:.1f} min "
@@ -357,8 +384,9 @@ def main():
357
  _sh.copy(src, out)
358
  shipped.append(fn)
359
  say(f"tokenizer files shipped with the export: {shipped or 'NONE -- Phase 5 must add them'}")
360
- SD.save_cursor(out, SD.cursor_dict(args.seq_len, samples, args.data_seed, fingerprint))
361
- json.dump({"step": step, "tokens_consumed": consumed, "seconds": round(elapsed, 1),
 
362
  "params": pc, "fingerprint": fingerprint, "final_loss": final_loss,
363
  "prior_loss": prior, "samples_consumed": samples, "steps_planned": steps_planned},
364
  open(os.path.join(out, "run_summary.json"), "w"), indent=1, sort_keys=True)
@@ -370,9 +398,13 @@ def main():
370
  except Exception as e:
371
  say(f"validation eval failed: {type(e).__name__}: {str(e)[:200]}")
372
  if api is not None:
373
- r = hubckpt.push_and_prune(args.hub_repo, out, "final", api,
374
  token=os.environ.get("HF_TOKEN"), prune=args.prune)
375
- say("final push:", json.dumps({k: r[k] for k in ("verify", "pruned", "free_after_gb")})[:900])
 
 
 
 
376
  say("RUN_JSON " + json.dumps({"final_step": step, "val_ppl": ppl, "tokens_consumed": consumed,
377
  "tok_per_s": round(consumed_this_run / max(1, elapsed)),
378
  "final_loss": final_loss, "prior_loss": prior,
 
73
 
74
 
75
  # The cursor arithmetic in one place, because three separate bugs live here:
76
+ # - a step consumes micro_batch * world * accum sequences, not micro_batch (DDP shards the batch);
77
+ # - Trainer restores `global_step` from the checkpoint, so on resume it is ALREADY absolute. Adding the
78
+ # resume point a second time inflates the cursor, and an inflated cursor makes the next run skip data
79
+ # it never read -- silent data loss with no error anywhere, which is §3.1's worst case. Writing this
80
+ # as a pure function of the absolute step removes the whole class of bug.
81
  # - max_steps is the TOTAL horizon (it is what the LR schedule decays against), so resuming mid-run
82
  # must keep the same steps_planned or the trapezoid changes shape.
83
+ def samples_at(absolute_step, seqs_per_step):
84
+ return int(absolute_step) * seqs_per_step
85
 
86
 
87
  class TrapezoidTrainer(Trainer):
 
117
  copy on a disk that can be taken away at any moment.
118
  """
119
 
120
+ def __init__(self, repo, api, token, seq_len, seed, fingerprint, seqs_per_step,
121
+ prune=True, min_free_gb=6.0, repo_type="dataset"):
122
  self.repo, self.api, self.token = repo, api, token
123
  self.seq_len, self.seed, self.fingerprint = seq_len, seed, fingerprint
124
+ self.seqs_per_step, self.repo_type = seqs_per_step, repo_type
125
  self.prune, self.min_free_gb = prune, min_free_gb
126
  self.n = 0
127
  self.results = []
 
133
  d = os.path.join(args.output_dir, f"checkpoint-{step}")
134
  if not os.path.isdir(d):
135
  raise RuntimeError(f"Trainer reported a save but {d} does not exist")
136
+ samples = samples_at(step, self.seqs_per_step)
137
+ SD.save_cursor(d, SD.cursor_dict(self.seq_len, samples, self.seed, self.fingerprint,
138
+ step=step))
139
  t0 = time.time()
140
  res = hubckpt.push_and_prune(self.repo, d, f"ckpt/checkpoint-{step}", self.api,
141
+ repo_type=self.repo_type, token=self.token, prune=self.prune,
142
  min_free_gb=self.min_free_gb)
143
  hubckpt.write_latest_pointer(self.repo, {
144
  "path_in_repo": f"ckpt/checkpoint-{step}", "step": step, "samples_consumed": samples,
145
  "tokens_consumed": samples * self.seq_len, "fingerprint": self.fingerprint,
146
+ "seed": self.seed}, self.api, repo_type=self.repo_type, token=self.token)
147
  loss = next((h["loss"] for h in reversed(state.log_history) if "loss" in h), None)
148
  print(f"CKPT {step} samples={samples:,} push+verify={round(time.time()-t0,1)}s "
149
  f"ok={res['verify']['ok']} pruned={res.get('pruned')} free={res['free_after_gb']}GB "
 
192
 
193
  store = SD.PackedTokenStore(args.root, man)
194
  fingerprint = SD.mix_fingerprint(args.root, man)
195
+ # One definition of the step, used by the cursor, the schedule and the token count: a step consumes
196
+ # micro_batch * world sequences (DDP shards the batch), so tokens/step follows from it.
197
+ seqs_per_step = args.micro_batch * world * args.accum
198
+ tokens_per_step = seqs_per_step * args.seq_len
199
  steps_planned = args.max_steps or int(args.tokens / tokens_per_step)
200
  say(f"mix: {store.total_tokens:,} tokens in {len(store.shards)} shards fp={fingerprint} "
201
  f"| {tokens_per_step:,} tok/step x {steps_planned} steps = "
 
210
  import ounce100m_credentials
211
  ounce100m_credentials.install()
212
  from huggingface_hub import HfApi
213
+ tk = os.environ.get("HF_TOKEN")
214
+ ptr = hubckpt.latest_pointer(args.hub_repo, repo_type=args.hub_repo_type, token=tk)
215
+ if ptr.get("not_found"):
216
+ # A 404 is a fact: this run has never checkpointed, so step 0 is the right place to start.
217
+ say(f"no latest.json on {args.hub_repo} -> starting from step 0")
218
  args.resume = ""
219
+ elif "error" in ptr:
220
+ # Anything else (401, timeout, DNS) means the lookup failed, not that there is nothing there.
221
+ # Falling through to step 0 here would silently retrain the first stretch of the run, which is
222
+ # exactly the §3.1 violation this whole branch exists to prevent (E-018's shape).
223
+ raise SystemExit(f"--resume auto could not read the hub pointer: {ptr['error']}")
224
  else:
225
  dest = os.path.join(args.out, os.path.basename(ptr["path_in_repo"]))
226
  say(f"auto-resume: hub says step {ptr.get('step')} at {ptr['path_in_repo']}")
227
+ got = hubckpt.download_checkpoint(args.hub_repo, ptr["path_in_repo"], dest, HfApi(),
228
+ repo_type=args.hub_repo_type, token=tk)
229
  say(f"downloaded {got['files']} files, {got['bytes']/1e6:.0f} MB in {got['seconds']}s")
230
  if got["bytes"] < 1_000_000:
231
  raise SystemExit("auto-resume downloaded a checkpoint that is not real weights")
232
  args.resume = got["dir"]
233
  say(f"resuming from {args.resume}")
234
  cur = SD.load_cursor(args.resume) if args.resume else None
235
+ if args.resume and cur is None:
236
+ # Weights at step N with the data stream back at sample 0 would retrain the opening of the corpus
237
+ # and report a continuous loss curve. Refuse instead.
238
+ raise SystemExit(f"resume refused: {args.resume} has no cursor.json -- a checkpoint without a "
239
+ "recorded data position cannot be resumed, only restarted (§3.1)")
240
  if args.resume:
241
  say(f"resume from {args.resume} cursor={cur}")
242
  start_sample = (cur or {}).get("samples_consumed", 0)
243
+ start_step = (cur or {}).get("step") or 0
244
  if cur:
245
  for k, v in (("seq_len", args.seq_len), ("shuffle_seed", args.data_seed),
246
  ("dataset_files_sha", fingerprint)):
247
  if cur.get(k) != v:
248
  raise SystemExit(f"resume refused: cursor {k}={cur.get(k)} != current {v}. "
249
  "A resumed run must read the same data in the same order (§3.1).")
250
+ if start_sample % seqs_per_step:
251
+ raise SystemExit(f"resume refused: cursor samples_consumed={start_sample} is not a whole "
252
+ f"number of steps (seqs/step={seqs_per_step}) -- batch geometry changed")
253
+ if cur.get("step") is not None and cur["step"] * seqs_per_step != start_sample:
254
+ raise SystemExit(f"resume refused: cursor step={cur['step']} and samples_consumed="
255
+ f"{start_sample} disagree at seqs/step={seqs_per_step}")
256
+ if start_step * seqs_per_step != start_sample:
257
+ start_step = start_sample // seqs_per_step
258
 
259
  train_ds = SD.make_dataset(store, args.seq_len, args.data_seed, start_sample=start_sample)
260
  # Validation comes from the mix's held-out val/ shards, never from the training stream: scoring on
 
274
  if not (90_000_000 <= pc["sum_numel"] <= 110_000_000) and not args.layers and not args.hidden:
275
  raise SystemExit(f"parameter count {pc['sum_numel']:,} is outside §2's 90-110M budget")
276
 
277
+ # 10 checkpoints per run is §2's cadence; --push-every-steps overrides for the preflight.
 
 
278
  ckpt_every = args.push_every_steps or max(1, steps_planned // 10)
279
 
280
  api = None
 
283
  ounce100m_credentials.install()
284
  from huggingface_hub import HfApi
285
  api = HfApi()
286
+ # rank 0 only: two ranks committing the same .gitattributes to a brand-new repo is a write race
287
+ # on the one path that must not fail (only rank 0 ever uploads checkpoints, so rank 1 needs none)
288
+ if rank == 0:
289
+ say("ckpt repo:", json.dumps(hubckpt.ensure_repo(args.hub_repo, api,
290
+ os.environ.get("HF_TOKEN"),
291
+ args.hub_repo_type)))
292
  say(f"checkpoint hub target {args.hub_repo} (prune={args.prune}, every {ckpt_every} steps)")
293
 
294
  tacc = TrainingArguments(
 
328
  )
329
  if api is not None:
330
  tr.add_callback(HubPush(args.hub_repo, api, os.environ.get("HF_TOKEN"), args.seq_len,
331
+ args.data_seed, fingerprint, seqs_per_step,
332
+ prune=args.prune, repo_type=args.hub_repo_type))
333
 
334
  # Precision must be ASSERTED, not configured: bf16 "works" silently on Turing and fp32 master
335
  # weights can be lost in a refactor (docs/00-platform-notes.md §8, memory/ERRORS.md E-006). The
 
360
 
361
  elapsed = time.time() - t0
362
  step = tr.state.global_step
363
+ samples = samples_at(step, seqs_per_step)
364
  consumed = samples * args.seq_len
365
+ consumed_this_run = max(0, step - start_step) * tokens_per_step
366
  hist = [h for h in tr.state.log_history if "loss" in h]
367
  final_loss = hist[-1]["loss"] if hist else None
368
  say(f"TRAIN DONE step={step}/{steps_planned} elapsed={elapsed/60:.1f} min "
 
384
  _sh.copy(src, out)
385
  shipped.append(fn)
386
  say(f"tokenizer files shipped with the export: {shipped or 'NONE -- Phase 5 must add them'}")
387
+ SD.save_cursor(out, SD.cursor_dict(args.seq_len, samples, args.data_seed, fingerprint, step=step))
388
+ json.dump({"step": step, "start_step": start_step, "tokens_consumed": consumed,
389
+ "tokens_this_run": consumed_this_run, "seconds": round(elapsed, 1),
390
  "params": pc, "fingerprint": fingerprint, "final_loss": final_loss,
391
  "prior_loss": prior, "samples_consumed": samples, "steps_planned": steps_planned},
392
  open(os.path.join(out, "run_summary.json"), "w"), indent=1, sort_keys=True)
 
398
  except Exception as e:
399
  say(f"validation eval failed: {type(e).__name__}: {str(e)[:200]}")
400
  if api is not None:
401
+ r = hubckpt.push_and_prune(args.hub_repo, out, "final", api, repo_type=args.hub_repo_type,
402
  token=os.environ.get("HF_TOKEN"), prune=args.prune)
403
+ # .get, not [k]: `pruned` and `free_after_gb` are only present on some paths through
404
+ # push_and_prune, and a KeyError here would throw away a completed run (E-023).
405
+ say("final push:", json.dumps({k: r.get(k) for k in
406
+ ("verify", "pruned", "free_before_gb", "free_after_gb",
407
+ "prune_blocked_reason")}, default=str)[:900])
408
  say("RUN_JSON " + json.dumps({"final_step": step, "val_ppl": ppl, "tokens_consumed": consumed,
409
  "tok_per_s": round(consumed_this_run / max(1, elapsed)),
410
  "final_loss": final_loss, "prior_loss": prior,