zziang commited on
Commit
533d158
·
verified ·
1 Parent(s): 83681a1

Upload kaggle/director_lora_train.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. kaggle/director_lora_train.py +34 -1
kaggle/director_lora_train.py CHANGED
@@ -43,6 +43,11 @@ ACCUM = int(os.environ.get("ACCUM", "4"))
43
  MAX_LEN = int(os.environ.get("MAX_LEN", "2048"))
44
  SEED = int(os.environ.get("SEED", "20261107"))
45
  GRAD_CKPT = os.environ.get("GRAD_CKPT", "0") == "1"
 
 
 
 
 
46
 
47
  # peft matches a list of target names against the last segment of a module key
48
  # (key == target or key.endswith("." + target)). Short names are portable across
@@ -216,6 +221,24 @@ def verify_targets(model, torch) -> None:
216
  raise SystemExit("unexpected LoRA target set; refusing to train")
217
 
218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  def main() -> None:
220
  import torch
221
  from peft import LoraConfig, get_peft_model
@@ -244,6 +267,7 @@ def main() -> None:
244
  smoke_generate(torch, model, tok, rows[0])
245
  model.config.use_cache = False
246
 
 
247
  cfg = LoraConfig(r=R, lora_alpha=ALPHA, lora_dropout=DROPOUT, bias="none",
248
  task_type="CAUSAL_LM", target_modules=SHORT_TARGETS)
249
  model = get_peft_model(model, cfg, autocast_adapter_dtype=True)
@@ -276,10 +300,16 @@ def main() -> None:
276
  opt = torch.optim.AdamW(trainable, lr=LR, betas=(0.9, 0.95), weight_decay=0.01)
277
  model.train()
278
  step, running, group, t0 = 0, 0.0, 0.0, time.time()
 
279
  for epoch in range(EPOCHS):
280
  order = list(range(len(encoded)))
281
  random.shuffle(order)
282
  for i, idx in enumerate(order):
 
 
 
 
 
283
  batch = {k: v.cuda() for k, v in encoded[idx].items()}
284
  loss = model(**batch).loss / ACCUM
285
  loss.backward()
@@ -295,7 +325,9 @@ def main() -> None:
295
  log(f"epoch {epoch} step {step} loss {running/25:.4f} "
296
  f"({time.time()-t0:.0f}s)")
297
  running = 0.0
298
- log(f"epoch {epoch} done")
 
 
299
  opt.zero_grad(set_to_none=True)
300
 
301
  adapter = OUT / "adapter"
@@ -332,6 +364,7 @@ def main() -> None:
332
  "dtype": str(dtype), "rows": len(encoded), "epochs": EPOCHS, "lr": LR,
333
  "r": R, "alpha": ALPHA, "targets": len(SHORT_TARGETS),
334
  "trainable": n_train, "steps": step, "seconds": round(time.time() - t0),
 
335
  }, indent=1), encoding="utf-8")
336
  log("done")
337
 
 
43
  MAX_LEN = int(os.environ.get("MAX_LEN", "2048"))
44
  SEED = int(os.environ.get("SEED", "20261107"))
45
  GRAD_CKPT = os.environ.get("GRAD_CKPT", "0") == "1"
46
+ # Wall-clock budget for the optimizer loop. The T4 has no causal_conv1d or
47
+ # flash-linear-attention kernels, so Gated DeltaNet falls back to the slow
48
+ # reference implementation. Stop and save a usable adapter rather than let
49
+ # the notebook timeout throw away the whole run.
50
+ MAX_TRAIN_SECONDS = int(os.environ.get("MAX_TRAIN_SECONDS", "4200"))
51
 
52
  # peft matches a list of target names against the last segment of a module key
53
  # (key == target or key.endswith("." + target)). Short names are portable across
 
221
  raise SystemExit("unexpected LoRA target set; refusing to train")
222
 
223
 
224
+ def neutralize_torchao() -> None:
225
+ """Kaggle ships torchao 0.10.0; peft 0.21.2 *raises* on torchao < 0.16
226
+ instead of treating it as absent. We never quantize here, so force the
227
+ 'not installed' branch in both places that consult it. The notebook also
228
+ uninstalls torchao; this is the belt-and-braces fallback.
229
+ """
230
+ patched = []
231
+ for modname in ("peft.import_utils", "peft.tuners.lora.torchao"):
232
+ try:
233
+ mod = __import__(modname, fromlist=["is_torchao_available"])
234
+ except ImportError:
235
+ continue
236
+ if hasattr(mod, "is_torchao_available"):
237
+ mod.is_torchao_available = lambda: False
238
+ patched.append(modname)
239
+ log(f"peft torchao dispatcher disabled in {patched}")
240
+
241
+
242
  def main() -> None:
243
  import torch
244
  from peft import LoraConfig, get_peft_model
 
267
  smoke_generate(torch, model, tok, rows[0])
268
  model.config.use_cache = False
269
 
270
+ neutralize_torchao()
271
  cfg = LoraConfig(r=R, lora_alpha=ALPHA, lora_dropout=DROPOUT, bias="none",
272
  task_type="CAUSAL_LM", target_modules=SHORT_TARGETS)
273
  model = get_peft_model(model, cfg, autocast_adapter_dtype=True)
 
300
  opt = torch.optim.AdamW(trainable, lr=LR, betas=(0.9, 0.95), weight_decay=0.01)
301
  model.train()
302
  step, running, group, t0 = 0, 0.0, 0.0, time.time()
303
+ budget_hit = False
304
  for epoch in range(EPOCHS):
305
  order = list(range(len(encoded)))
306
  random.shuffle(order)
307
  for i, idx in enumerate(order):
308
+ if time.time() - t0 > MAX_TRAIN_SECONDS:
309
+ log(f"time budget {MAX_TRAIN_SECONDS}s reached at epoch {epoch} "
310
+ f"iter {i}/{len(order)}; saving what we have")
311
+ budget_hit = True
312
+ break
313
  batch = {k: v.cuda() for k, v in encoded[idx].items()}
314
  loss = model(**batch).loss / ACCUM
315
  loss.backward()
 
325
  log(f"epoch {epoch} step {step} loss {running/25:.4f} "
326
  f"({time.time()-t0:.0f}s)")
327
  running = 0.0
328
+ log(f"epoch {epoch} done ({time.time()-t0:.0f}s total)")
329
+ if budget_hit:
330
+ break
331
  opt.zero_grad(set_to_none=True)
332
 
333
  adapter = OUT / "adapter"
 
364
  "dtype": str(dtype), "rows": len(encoded), "epochs": EPOCHS, "lr": LR,
365
  "r": R, "alpha": ALPHA, "targets": len(SHORT_TARGETS),
366
  "trainable": n_train, "steps": step, "seconds": round(time.time() - t0),
367
+ "budget_hit": budget_hit, "budget_seconds": MAX_TRAIN_SECONDS,
368
  }, indent=1), encoding="utf-8")
369
  log("done")
370