tony0014 commited on
Commit
3b8c5f2
·
verified ·
1 Parent(s): b713b3f

upgrade: scripts/smoke_l4.py

Browse files
Files changed (1) hide show
  1. scripts/smoke_l4.py +134 -14
scripts/smoke_l4.py CHANGED
@@ -33,7 +33,8 @@ import traceback
33
  from pathlib import Path
34
 
35
  LETTERS = ("A", "B", "C", "D")
36
- COST_PER_HOUR = 0.80
 
37
  DEFAULT_MODEL = "CohereLabs/tiny-aya-global"
38
  BENCH_REPO = "tony0014/zombie-weights-bench"
39
  TELEMETRY_REPO = "tony0014/zombie-weights-telemetry"
@@ -312,6 +313,81 @@ def make_batches(texts: list[str], tok, n: int, max_len: int = 640) -> list[dict
312
  return batches
313
 
314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  def run_rmu(
316
  model_name: str,
317
  bench_repo: str,
@@ -325,6 +401,8 @@ def run_rmu(
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
@@ -362,26 +440,62 @@ def run_rmu(
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")
@@ -412,7 +526,13 @@ def run_rmu(
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,
 
33
  from pathlib import Path
34
 
35
  LETTERS = ("A", "B", "C", "D")
36
+ # l4x1 = $0.80/h, a100-large = $2.50/h; set ZW_COST_PER_HOUR on non-L4 jobs.
37
+ COST_PER_HOUR = float(os.environ.get("ZW_COST_PER_HOUR", "0.80"))
38
  DEFAULT_MODEL = "CohereLabs/tiny-aya-global"
39
  BENCH_REPO = "tony0014/zombie-weights-bench"
40
  TELEMETRY_REPO = "tony0014/zombie-weights-telemetry"
 
313
  return batches
314
 
315
 
316
+ def _rmu_utility_retain_loop(
317
+ model,
318
+ frozen_model,
319
+ forget_batches: list[dict],
320
+ retain_batches: list[dict],
321
+ utility_batches: list[dict],
322
+ *,
323
+ layer_id: int,
324
+ params: list,
325
+ lr: float,
326
+ alpha: float,
327
+ beta: float,
328
+ steering_coeff: float = 20.0,
329
+ max_num_batches: int | None = None,
330
+ ) -> tuple[int, list[dict]]:
331
+ """RMU with a second, utility-protecting retain stream.
332
+
333
+ Extends the authors' objective (``MSE_forget + alpha * MSE_retain``) with
334
+ ``beta * alpha * MSE_utility`` over multilingual MMLU + benign prose.
335
+ ``beta`` is therefore relative to the base RMU retain weight and the
336
+ effective coefficient is recorded in telemetry. Math (control vector,
337
+ forward hook, AdamW step) mirrors SafeTune 0.1.18 ``rmu_unlearn`` exactly;
338
+ only the extra term differs.
339
+ """
340
+ import torch
341
+ import torch.nn.functional as F
342
+ from safetune._refusal_helpers import _get_decoder_layers
343
+ from safetune.interventions.unlearn.rmu import _forward_with_cache
344
+
345
+ updated_module = _get_decoder_layers(model)[layer_id]
346
+ frozen_module = _get_decoder_layers(frozen_model)[layer_id]
347
+
348
+ ref_param = params[0]
349
+ hidden_size = getattr(getattr(model, "config", None), "hidden_size", None) or ref_param.shape[0]
350
+ random_vector = torch.rand(1, 1, hidden_size, dtype=ref_param.dtype, device=ref_param.device)
351
+ control_vec = random_vector / torch.norm(random_vector) * steering_coeff
352
+
353
+ optimizer = torch.optim.AdamW(params, lr=lr)
354
+ trace: list[dict] = []
355
+ steps = 0
356
+ for forget_batch, retain_batch, utility_batch in zip(forget_batches, retain_batches, utility_batches):
357
+ if max_num_batches is not None and steps >= max_num_batches:
358
+ break
359
+ with torch.autocast("cuda", dtype=torch.bfloat16):
360
+ act_forget = _forward_with_cache(model, forget_batch, updated_module, no_grad=False)
361
+ forget_loss = F.mse_loss(act_forget, control_vec.expand_as(act_forget).to(act_forget.dtype))
362
+
363
+ act_retain = _forward_with_cache(model, retain_batch, updated_module, no_grad=False)
364
+ act_retain_frozen = _forward_with_cache(frozen_model, retain_batch, frozen_module, no_grad=True)
365
+ retain_loss = alpha * F.mse_loss(act_retain, act_retain_frozen.to(act_retain.dtype))
366
+
367
+ act_utility = _forward_with_cache(model, utility_batch, updated_module, no_grad=False)
368
+ act_utility_frozen = _forward_with_cache(frozen_model, utility_batch, frozen_module, no_grad=True)
369
+ utility_loss = (alpha * beta) * F.mse_loss(act_utility, act_utility_frozen.to(act_utility.dtype))
370
+
371
+ loss = forget_loss + retain_loss + utility_loss
372
+
373
+ optimizer.zero_grad(set_to_none=True)
374
+ loss.backward()
375
+ optimizer.step()
376
+ steps += 1
377
+ trace.append(
378
+ {
379
+ "step": steps,
380
+ "loss": round(float(loss.item()), 6),
381
+ "forget": round(float(forget_loss.item()), 6),
382
+ "retain": round(float(retain_loss.item()), 6),
383
+ "utility": round(float(utility_loss.item()), 6),
384
+ }
385
+ )
386
+ if steps == 1 or steps % 20 == 0:
387
+ print(f"[rmu] step {steps}/{max_num_batches} {trace[-1]}", flush=True)
388
+ return steps, trace
389
+
390
+
391
  def run_rmu(
392
  model_name: str,
393
  bench_repo: str,
 
401
  ckpt_name: str = "rmu_ckpt",
402
  telemetry_name: str = "rmu.json",
403
  vram_cap_gb: float = 21.0,
404
+ retain_extra_texts: list[str] | None = None,
405
+ retain_beta: float = 0.0,
406
  ) -> dict:
407
  timer.check("rmu", need=600)
408
  import torch
 
440
  forget_texts = [r["text"] for r in read_jsonl(download_bench_file("arm_a/train.jsonl", bench_repo))]
441
  mmlu = read_jsonl(download_bench_file("controls/global_mmlu.jsonl", bench_repo))
442
  retain_texts = []
443
+ # Multilingual retain sampling: interleave EN, HI, AR to prevent multilingual utility collapse
444
+ mmlu_en = [r for r in mmlu if r["lang"] == "en"]
445
+ mmlu_hi = [r for r in mmlu if r["lang"] == "hi"]
446
+ mmlu_ar = [r for r in mmlu if r["lang"] == "ar"]
447
+ min_count = min(len(mmlu_en), len(mmlu_hi), len(mmlu_ar)) if (mmlu_hi and mmlu_ar) else len(mmlu_en)
448
+ retain_sample = mmlu_en[:min_count] + mmlu_hi[:min_count] + mmlu_ar[:min_count]
449
+ random.Random(42).shuffle(retain_sample)
450
+ for rec in retain_sample:
451
  retain_texts.append(f"{rec['question']}\nAnswer: {rec['options'][rec['answer_index']]}")
452
  if not forget_texts or not retain_texts:
453
  raise RuntimeError("RMU: missing forget/retain texts")
454
 
455
  forget_batches = make_batches(forget_texts, tok, n=max_num_batches, max_len=max_len)
456
  retain_batches = make_batches(retain_texts, tok, n=max_num_batches, max_len=max_len)
457
+ utility_batches: list[dict] = []
458
+ utility_retain_weight = 0.0
459
+ if retain_extra_texts and retain_beta > 0:
460
+ utility_batches = make_batches(retain_extra_texts, tok, n=max_num_batches, max_len=max_len)
461
+ utility_retain_weight = alpha * retain_beta
462
+
463
+ loss_trace: list[dict] = []
464
+ trainer = None
465
+ steps_done = None
 
466
  try:
467
+ if utility_batches:
468
+ print(
469
+ f"[rmu] utility-retain stream: n={len(utility_batches)} "
470
+ f"beta={retain_beta} (effective weight={utility_retain_weight})",
471
+ flush=True,
472
+ )
473
+ steps_done, loss_trace = _rmu_utility_retain_loop(
474
+ model,
475
+ frozen,
476
+ forget_batches,
477
+ retain_batches,
478
+ utility_batches,
479
+ layer_id=layer_id,
480
+ params=[p for p in model.parameters() if p.requires_grad],
481
+ lr=lr,
482
+ alpha=alpha,
483
+ beta=retain_beta,
484
+ max_num_batches=max_num_batches,
485
+ )
486
+ updated = model
487
+ else:
488
+ trainer = RMUTrainer(
489
+ model,
490
+ layer_id=layer_id,
491
+ update_layer_ids=update_layer_ids,
492
+ max_num_batches=max_num_batches,
493
+ lr=lr,
494
+ alpha=alpha,
495
+ upcast=False,
496
+ )
497
+ with torch.autocast("cuda", dtype=torch.bfloat16):
498
+ updated = trainer.unlearn(forget=forget_batches, retain=retain_batches, frozen_model=frozen)
499
  except Exception:
500
  try:
501
  model.to("cpu")
 
526
  "phase": "rmu",
527
  "model": model_name,
528
  "steps": max_num_batches,
529
+ "steps_completed": int(steps_done) if utility_batches else max_num_batches,
530
  "alpha": alpha,
531
+ "retain_beta": retain_beta,
532
+ "utility_retain_weight": utility_retain_weight,
533
+ "utility_retain_n": len(utility_batches),
534
+ "loss_trace_head": loss_trace[:3],
535
+ "loss_trace_tail": loss_trace[-3:],
536
  "lr": lr,
537
  "layer_id": layer_id,
538
  "max_len": max_len,