sync scripts/smoke_l4.py
Browse files311 unmodified lines3123133143153163173182 unmodified lines32132232332432532632715 unmodified lines3433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723 unmodified lines3763773783793803813823833843853861 unmodified line3883893903913923933942 unmodified lines397398399400401402403311 unmodified linesreturn batchesdef run_rmu(model_name: str, bench_repo: str, workdir: Path, telemetry: Telemetry, timer: Timer) -> dict:timer.check("rmu", need=600)import torchfrom safetune.runner.unlearn import RMUTrainer2 unmodified linesreset_gpu_peak()t0 = time.time()max_len = 640update_layer_ids = [5, 6, 7]tok = AutoTokenizer.from_pretrained(model_name)if tok.pad_token is None:15 unmodified linesparam.requires_grad_(False)if not before:raise RuntimeError("RMU smoke: no update parameters matched layers 5-7 down_proj")forget_texts = [r["text"] for r in read_jsonl(download_bench_file("arm_a/train.jsonl", bench_repo))][:10]mmlu = read_jsonl(download_bench_file("controls/global_mmlu.jsonl", bench_repo))retain_texts = []for rec in [r for r in mmlu if r["lang"] == "en"][:10]:retain_texts.append(f"{rec['question']}\nAnswer: {rec['options'][rec['answer_index']]}")if not forget_texts or not retain_texts:raise RuntimeError("RMU smoke: missing forget/retain texts")forget_batches = make_batches(forget_texts, tok, n=10, max_len=max_len)retain_batches = make_batches(retain_texts, tok, n=10, max_len=max_len)trainer = RMUTrainer(model,layer_id=7,update_layer_ids=update_layer_ids,max_num_batches=10,lr=5e-5,alpha=100.0,upcast=False,)with torch.autocast("cuda", dtype=torch.bfloat16):updated = trainer.unlearn(forget=forget_batches, retain=retain_batches, frozen_model=frozen)deltas = {}for name, param in updated.named_parameters():3 unmodified linespeak = gpu_peak_gb()if total_delta <= 0:raise AssertionError(f"RMU smoke failed: ||W_after - W_before||_2 == 0 ({deltas})")if peak >= 21.0:raise AssertionError(f"RMU smoke failed: peak VRAM {peak:.2f} GB >= 21 GB")ckpt = workdir / "rmu_ckpt"ckpt.mkdir(parents=True, exist_ok=True)updated.save_pretrained(str(ckpt), safe_serialization=True)tok.save_pretrained(str(ckpt))1 unmodified lineresult = {"phase": "rmu","model": model_name,"steps": 10,"max_len": max_len,"update_layer_ids": update_layer_ids,"delta_w_l2_total": total_delta,2 unmodified lines"checkpoint": str(ckpt),"elapsed_s": round(time.time() - t0, 1),}telemetry.push_json("rmu.json", result)try:model.to("cpu")frozen.to("cpu")311 unmodified lines3123133143153163173183193203213223233243253263273283293303312 unmodified lines33433533633733833934034115 unmodified lines3573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953 unmodified lines3994004014024034044054064074084091 unmodified line4114124134144154164174184194202 unmodified lines423424425426427428429311 unmodified linesreturn batchesdef run_rmu(model_name: str,bench_repo: str,workdir: Path,telemetry: Telemetry,timer: Timer,update_layer_ids: tuple[int, ...] = (5, 6, 7),max_num_batches: int = 10,alpha: float = 100.0,lr: float = 5e-5,ckpt_name: str = "rmu_ckpt",telemetry_name: str = "rmu.json",vram_cap_gb: float = 21.0,) -> dict:timer.check("rmu", need=600)import torchfrom safetune.runner.unlearn import RMUTrainer2 unmodified linesreset_gpu_peak()t0 = time.time()max_len = 640update_layer_ids = list(update_layer_ids)layer_id = max(update_layer_ids)tok = AutoTokenizer.from_pretrained(model_name)if tok.pad_token is None:15 unmodified linesparam.requires_grad_(False)if not before:raise RuntimeError(f"RMU: no update parameters matched layers {update_layer_ids} down_proj")forget_texts = [r["text"] for r in read_jsonl(download_bench_file("arm_a/train.jsonl", bench_repo))]mmlu = read_jsonl(download_bench_file("controls/global_mmlu.jsonl", bench_repo))retain_texts = []for rec in [r for r in mmlu if r["lang"] == "en"]:retain_texts.append(f"{rec['question']}\nAnswer: {rec['options'][rec['answer_index']]}")if not forget_texts or not retain_texts:raise RuntimeError("RMU: missing forget/retain texts")forget_batches = make_batches(forget_texts, tok, n=max_num_batches, max_len=max_len)retain_batches = make_batches(retain_texts, tok, n=max_num_batches, max_len=max_len)trainer = RMUTrainer(model,layer_id=layer_id,update_layer_ids=update_layer_ids,max_num_batches=max_num_batches,lr=lr,alpha=alpha,upcast=False,)try:with torch.autocast("cuda", dtype=torch.bfloat16):updated = trainer.unlearn(forget=forget_batches, retain=retain_batches, frozen_model=frozen)except Exception:try:model.to("cpu")frozen.to("cpu")torch.cuda.empty_cache()except Exception: # noqa: BLE001passraisedeltas = {}for name, param in updated.named_parameters():3 unmodified linespeak = gpu_peak_gb()if total_delta <= 0:raise AssertionError(f"RMU failed: ||W_after - W_before||_2 == 0 ({deltas})")if peak >= vram_cap_gb:raise AssertionError(f"RMU failed: peak VRAM {peak:.2f} GB >= {vram_cap_gb} GB")ckpt = workdir / ckpt_nameckpt.mkdir(parents=True, exist_ok=True)updated.save_pretrained(str(ckpt), safe_serialization=True)tok.save_pretrained(str(ckpt))1 unmodified lineresult = {"phase": "rmu","model": model_name,"steps": max_num_batches,"alpha": alpha,"lr": lr,"layer_id": layer_id,"max_len": max_len,"update_layer_ids": update_layer_ids,"delta_w_l2_total": total_delta,2 unmodified lines"checkpoint": str(ckpt),"elapsed_s": round(time.time() - t0, 1),}telemetry.push_json(telemetry_name, result)try:model.to("cpu")frozen.to("cpu")
scripts/smoke_l4.py+46-20