tony0014 commited on
Commit
cd1a975
·
verified ·
1 Parent(s): 952572d

sync scripts/smoke_l4.py

Browse files
Files changed (1) hide show
  1. scripts/smoke_l4.py +46 -20
scripts/smoke_l4.py CHANGED
@@ -312,7 +312,20 @@ def make_batches(texts: list[str], tok, n: int, max_len: int = 640) -> list[dict
312
  return batches
313
 
314
 
315
- def run_rmu(model_name: str, bench_repo: str, workdir: Path, telemetry: Telemetry, timer: Timer) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  timer.check("rmu", need=600)
317
  import torch
318
  from safetune.runner.unlearn import RMUTrainer
@@ -321,7 +334,8 @@ def run_rmu(model_name: str, bench_repo: str, workdir: Path, telemetry: Telemetr
321
  reset_gpu_peak()
322
  t0 = time.time()
323
  max_len = 640
324
- update_layer_ids = [5, 6, 7]
 
325
 
326
  tok = AutoTokenizer.from_pretrained(model_name)
327
  if tok.pad_token is None:
@@ -343,30 +357,39 @@ def run_rmu(model_name: str, bench_repo: str, workdir: Path, telemetry: Telemetr
343
  param.requires_grad_(False)
344
 
345
  if not before:
346
- raise RuntimeError("RMU smoke: no update parameters matched layers 5-7 down_proj")
347
 
348
- forget_texts = [r["text"] for r in read_jsonl(download_bench_file("arm_a/train.jsonl", bench_repo))][:10]
349
  mmlu = read_jsonl(download_bench_file("controls/global_mmlu.jsonl", bench_repo))
350
  retain_texts = []
351
- for rec in [r for r in mmlu if r["lang"] == "en"][:10]:
352
  retain_texts.append(f"{rec['question']}\nAnswer: {rec['options'][rec['answer_index']]}")
353
  if not forget_texts or not retain_texts:
354
- raise RuntimeError("RMU smoke: missing forget/retain texts")
355
 
356
- forget_batches = make_batches(forget_texts, tok, n=10, max_len=max_len)
357
- retain_batches = make_batches(retain_texts, tok, n=10, max_len=max_len)
358
 
359
  trainer = RMUTrainer(
360
  model,
361
- layer_id=7,
362
  update_layer_ids=update_layer_ids,
363
- max_num_batches=10,
364
- lr=5e-5,
365
- alpha=100.0,
366
  upcast=False,
367
  )
368
- with torch.autocast("cuda", dtype=torch.bfloat16):
369
- updated = trainer.unlearn(forget=forget_batches, retain=retain_batches, frozen_model=frozen)
 
 
 
 
 
 
 
 
 
370
 
371
  deltas = {}
372
  for name, param in updated.named_parameters():
@@ -376,11 +399,11 @@ def run_rmu(model_name: str, bench_repo: str, workdir: Path, telemetry: Telemetr
376
  peak = gpu_peak_gb()
377
 
378
  if total_delta <= 0:
379
- raise AssertionError(f"RMU smoke failed: ||W_after - W_before||_2 == 0 ({deltas})")
380
- if peak >= 21.0:
381
- raise AssertionError(f"RMU smoke failed: peak VRAM {peak:.2f} GB >= 21 GB")
382
 
383
- ckpt = workdir / "rmu_ckpt"
384
  ckpt.mkdir(parents=True, exist_ok=True)
385
  updated.save_pretrained(str(ckpt), safe_serialization=True)
386
  tok.save_pretrained(str(ckpt))
@@ -388,7 +411,10 @@ def run_rmu(model_name: str, bench_repo: str, workdir: Path, telemetry: Telemetr
388
  result = {
389
  "phase": "rmu",
390
  "model": model_name,
391
- "steps": 10,
 
 
 
392
  "max_len": max_len,
393
  "update_layer_ids": update_layer_ids,
394
  "delta_w_l2_total": total_delta,
@@ -397,7 +423,7 @@ def run_rmu(model_name: str, bench_repo: str, workdir: Path, telemetry: Telemetr
397
  "checkpoint": str(ckpt),
398
  "elapsed_s": round(time.time() - t0, 1),
399
  }
400
- telemetry.push_json("rmu.json", result)
401
  try:
402
  model.to("cpu")
403
  frozen.to("cpu")
 
312
  return batches
313
 
314
 
315
+ def run_rmu(
316
+ model_name: str,
317
+ bench_repo: str,
318
+ workdir: Path,
319
+ telemetry: Telemetry,
320
+ timer: Timer,
321
+ update_layer_ids: tuple[int, ...] = (5, 6, 7),
322
+ max_num_batches: int = 10,
323
+ alpha: float = 100.0,
324
+ lr: float = 5e-5,
325
+ ckpt_name: str = "rmu_ckpt",
326
+ telemetry_name: str = "rmu.json",
327
+ vram_cap_gb: float = 21.0,
328
+ ) -> dict:
329
  timer.check("rmu", need=600)
330
  import torch
331
  from safetune.runner.unlearn import RMUTrainer
 
334
  reset_gpu_peak()
335
  t0 = time.time()
336
  max_len = 640
337
+ update_layer_ids = list(update_layer_ids)
338
+ layer_id = max(update_layer_ids)
339
 
340
  tok = AutoTokenizer.from_pretrained(model_name)
341
  if tok.pad_token is None:
 
357
  param.requires_grad_(False)
358
 
359
  if not before:
360
+ raise RuntimeError(f"RMU: no update parameters matched layers {update_layer_ids} down_proj")
361
 
362
+ forget_texts = [r["text"] for r in read_jsonl(download_bench_file("arm_a/train.jsonl", bench_repo))]
363
  mmlu = read_jsonl(download_bench_file("controls/global_mmlu.jsonl", bench_repo))
364
  retain_texts = []
365
+ for rec in [r for r in mmlu if r["lang"] == "en"]:
366
  retain_texts.append(f"{rec['question']}\nAnswer: {rec['options'][rec['answer_index']]}")
367
  if not forget_texts or not retain_texts:
368
+ raise RuntimeError("RMU: missing forget/retain texts")
369
 
370
+ forget_batches = make_batches(forget_texts, tok, n=max_num_batches, max_len=max_len)
371
+ retain_batches = make_batches(retain_texts, tok, n=max_num_batches, max_len=max_len)
372
 
373
  trainer = RMUTrainer(
374
  model,
375
+ layer_id=layer_id,
376
  update_layer_ids=update_layer_ids,
377
+ max_num_batches=max_num_batches,
378
+ lr=lr,
379
+ alpha=alpha,
380
  upcast=False,
381
  )
382
+ try:
383
+ with torch.autocast("cuda", dtype=torch.bfloat16):
384
+ updated = trainer.unlearn(forget=forget_batches, retain=retain_batches, frozen_model=frozen)
385
+ except Exception:
386
+ try:
387
+ model.to("cpu")
388
+ frozen.to("cpu")
389
+ torch.cuda.empty_cache()
390
+ except Exception: # noqa: BLE001
391
+ pass
392
+ raise
393
 
394
  deltas = {}
395
  for name, param in updated.named_parameters():
 
399
  peak = gpu_peak_gb()
400
 
401
  if total_delta <= 0:
402
+ raise AssertionError(f"RMU failed: ||W_after - W_before||_2 == 0 ({deltas})")
403
+ if peak >= vram_cap_gb:
404
+ raise AssertionError(f"RMU failed: peak VRAM {peak:.2f} GB >= {vram_cap_gb} GB")
405
 
406
+ ckpt = workdir / ckpt_name
407
  ckpt.mkdir(parents=True, exist_ok=True)
408
  updated.save_pretrained(str(ckpt), safe_serialization=True)
409
  tok.save_pretrained(str(ckpt))
 
411
  result = {
412
  "phase": "rmu",
413
  "model": model_name,
414
+ "steps": max_num_batches,
415
+ "alpha": alpha,
416
+ "lr": lr,
417
+ "layer_id": layer_id,
418
  "max_len": max_len,
419
  "update_layer_ids": update_layer_ids,
420
  "delta_w_l2_total": total_delta,
 
423
  "checkpoint": str(ckpt),
424
  "elapsed_s": round(time.time() - t0, 1),
425
  }
426
+ telemetry.push_json(telemetry_name, result)
427
  try:
428
  model.to("cpu")
429
  frozen.to("cpu")