cybertronak commited on
Commit
449cb7b
·
verified ·
1 Parent(s): 17bc5f5

model replies for AuditKIT scoring (private store only)

Browse files
code/w_gen.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import sys, json, time, gc
3
+ import bitsandbytes as bnb
4
+ from transformers import AutoModelForCausalLM
5
+ from lab_common import *
6
+ shard, nsh = int(sys.argv[1]), int(sys.argv[2]); ARMS = {a[0]: a for a in json.load(open(ROOT / "scores" / "arms.json"))["arms"]}; GEN = json.load(open(ROOT / "scores" / "gen_arms.json")); CFG = json.load(open(ROOT / "scores" / "eval_cfg.json"))
7
+ todo = [ARMS[n] for i, n in enumerate(GEN) if n in ARMS and i % nsh == shard and not (ROOT / "responses" / f"{n}.json").exists()]; print(f"shard {shard}: {[a[0] for a in todo]}", flush=True)
8
+ if not todo: sys.exit(0)
9
+ STOP = [3, 6, 261001]; chat = lambda p: tok.apply_chat_template([{"role": "user", "content": p}], tokenize=False, add_generation_prompt=True); enc = lambda p: tok(chat(p), add_special_tokens=False).input_ids
10
+ def pick(rows, n, salt):
11
+ rows = sorted(rows, key=lambda r: r["id"]); random.Random(f"{SEED}-{salt}").shuffle(rows); out = []
12
+ for r in rows:
13
+ ids = enc(r["prompt"])
14
+ if len(ids) <= 512: out.append({"id": r["id"], "dataset": r["dataset"], "lang": r["lang"], "ids": ids})
15
+ if len(out) == n: break
16
+ return out
17
+ N = CFG["n_group"]; hb = read("harmbench_standard"); sr = read("strongreject"); xs = [r for r in read("xstest") if r["label"] == "benign"]; ind = read("indicsafe_hindi")
18
+ SAFE = [dict(x, group="harmful_en") for x in pick(hb, N // 2, "hb") + pick(sr, N - N // 2, "sr")] + [dict(x, group="harmful_hi") for x in pick([r for r in ind if r["label"] == "harmful"], N, "ih")] \
19
+ + [dict(x, group="benign_en") for x in pick(xs, N, "xs")] + [dict(x, group="benign_hi") for x in pick([r for r in ind if r["label"] == "benign"], N, "ib")]
20
+ def quant(layer, bits):
21
+ for name, mod in list(layer.named_modules()):
22
+ if not isinstance(mod, torch.nn.Linear): continue
23
+ w = mod.weight.data.to(torch.float16)
24
+ if bits == 4:
25
+ new = bnb.nn.Linear4bit(mod.in_features, mod.out_features, bias=(mod.bias is not None), quant_type="nf4", compute_dtype=torch.float16); new.weight = bnb.nn.Params4bit(w, requires_grad=False, quant_type="nf4")
26
+ else:
27
+ new = bnb.nn.Linear8bitLt(mod.in_features, mod.out_features, bias=(mod.bias is not None), has_fp16_weights=False, threshold=6.0); new.weight = bnb.nn.Int8Params(w, requires_grad=False, has_fp16_weights=False)
28
+ if mod.bias is not None: new.bias = torch.nn.Parameter(mod.bias.data.clone().to(torch.float16))
29
+ pn, _, at = name.rpartition("."); par = layer
30
+ if pn:
31
+ for part in pn.split("."): par = getattr(par, part)
32
+ setattr(par, at, new)
33
+ def build(prot, pbits, rbits):
34
+ if pbits == 16 and rbits == 16: return AutoModelForCausalLM.from_pretrained(MID, token=HF, dtype=torch.float16, device_map={"": 0}).eval()
35
+ m = AutoModelForCausalLM.from_pretrained(MID, token=HF, dtype=torch.float16, low_cpu_mem_usage=True, device_map=None).eval()
36
+ for i, Ly in enumerate(m.model.layers):
37
+ b = pbits if i in prot else rbits
38
+ if b < 16: quant(Ly, b)
39
+ m.model.embed_tokens = m.model.embed_tokens.to(dev)
40
+ for Ly in m.model.layers: Ly.to(dev)
41
+ m.model.norm = m.model.norm.to(dev); m.lm_head = m.lm_head.to(dev); return m
42
+ for arm, prot, pbits, rbits in todo:
43
+ t0 = time.time(); m = build(set(prot), pbits, rbits); m.config.use_cache = True; seqs = [x["ids"] for x in SAFE]; rows = [None] * len(SAFE)
44
+ for idx in batches(seqs, max_bs=16, budget=9000):
45
+ ids, am, _ = pad_left([seqs[i] for i in idx]); n0 = ids.shape[1]
46
+ with torch.inference_mode(): out = m.generate(input_ids=ids, attention_mask=am, max_new_tokens=48, do_sample=False, eos_token_id=STOP, pad_token_id=0)
47
+ for r, i in enumerate(idx):
48
+ g = out[r, n0:].tolist(); k = next((j for j, x in enumerate(g) if x in STOP), None); it = SAFE[i]
49
+ rows[i] = {"id": it["id"], "group": it["group"], "lang": it["lang"], "dataset": it["dataset"], "text": tok.decode(g if k is None else g[:k], skip_special_tokens=True)}
50
+ json.dump(rows, open(ROOT / "responses" / f"{arm}.json", "w"), ensure_ascii=False); print(arm, "DONE", round(time.time() - t0), "s", flush=True); del m; gc.collect(); torch.cuda.empty_cache()
responses/E0_FP16.json ADDED
The diff for this file is too large to render. See raw diff
 
responses/E1_uniform_W4.json ADDED
The diff for this file is too large to render. See raw diff
 
responses/R0_FP16_W4.json ADDED
The diff for this file is too large to render. See raw diff
 
responses/R1_FP16_W4.json ADDED
The diff for this file is too large to render. See raw diff
 
responses/R2_FP16_W4.json ADDED
The diff for this file is too large to render. See raw diff
 
responses/R3_FP16_W4.json ADDED
The diff for this file is too large to render. See raw diff
 
responses/S_A_importance_FP16_W4.json ADDED
The diff for this file is too large to render. See raw diff
 
responses/S_B_fragility_FP16_W4.json ADDED
The diff for this file is too large to render. See raw diff
 
responses/S_C_refusalDrop_FP16_W4.json ADDED
The diff for this file is too large to render. See raw diff
 
responses/S_C_refusalDrop_W8_W4.json ADDED
The diff for this file is too large to render. See raw diff
 
responses/S_D_composite_FP16_W4.json ADDED
The diff for this file is too large to render. See raw diff
 
responses/S_N_negative_FP16_W4.json ADDED
The diff for this file is too large to render. See raw diff
 
scores/gen_arms.json ADDED
@@ -0,0 +1 @@
 
 
1
+ ["E0_FP16", "E1_uniform_W4", "S_A_importance_FP16_W4", "S_B_fragility_FP16_W4", "S_C_refusalDrop_FP16_W4", "S_C_refusalDrop_W8_W4", "S_D_composite_FP16_W4", "S_N_negative_FP16_W4", "R0_FP16_W4", "R1_FP16_W4", "R2_FP16_W4", "R3_FP16_W4", "S_CK_circuitkit_FP16_W4"]