juiceb0xc0de commited on
Commit
536f664
·
1 Parent(s): 5cebbaf

Refactor model loading to support dynamic trust_remote_code and attention implementation options

Browse files
.gitignore CHANGED
@@ -7,3 +7,7 @@ atlas/
7
  *.sqlite
8
  *.tmp
9
  .DS_Store
 
 
 
 
 
7
  *.sqlite
8
  *.tmp
9
  .DS_Store
10
+ comparison_post.md
11
+ .gitignore
12
+ model_card_3b.md
13
+ model_card_1.5b.md
analyze_ov_circuits.py CHANGED
@@ -23,14 +23,14 @@ import torch
23
  from transformers import AutoModelForCausalLM, AutoTokenizer
24
 
25
 
26
- def _load_model(model_id: str, token: str | None):
27
- tokenizer = AutoTokenizer.from_pretrained(model_id, token=token, trust_remote_code=True)
28
  model = AutoModelForCausalLM.from_pretrained(
29
  model_id,
30
  token=token,
31
  torch_dtype=torch.bfloat16,
32
  device_map="cpu",
33
- trust_remote_code=True,
34
  )
35
  model.eval()
36
  return model, tokenizer
@@ -82,9 +82,9 @@ def analyze_head(w_v: np.ndarray, w_o_head: np.ndarray) -> dict:
82
  }
83
 
84
 
85
- def run(model_id: str, output: Path, token: str | None = None) -> None:
86
  print(f"[ov] loading {model_id}")
87
- model, _ = _load_model(model_id, token)
88
 
89
  layers = _resolve_layers(model)
90
  n_layers = len(layers)
@@ -165,9 +165,10 @@ def main() -> None:
165
  p.add_argument("--model", default=MODEL_ID, help="HF model id")
166
  p.add_argument("--output", type=Path, default=Path("outputs/ov_circuit_scores.json"))
167
  p.add_argument("--hf-token", default=os.environ.get("HF_TOKEN"))
 
168
  args = p.parse_args()
169
 
170
- run(args.model, args.output, token=args.hf_token)
171
 
172
 
173
  if __name__ == "__main__":
 
23
  from transformers import AutoModelForCausalLM, AutoTokenizer
24
 
25
 
26
+ def _load_model(model_id: str, token: str | None, trust_remote_code: bool = False):
27
+ tokenizer = AutoTokenizer.from_pretrained(model_id, token=token, trust_remote_code=trust_remote_code)
28
  model = AutoModelForCausalLM.from_pretrained(
29
  model_id,
30
  token=token,
31
  torch_dtype=torch.bfloat16,
32
  device_map="cpu",
33
+ trust_remote_code=trust_remote_code,
34
  )
35
  model.eval()
36
  return model, tokenizer
 
82
  }
83
 
84
 
85
+ def run(model_id: str, output: Path, token: str | None = None, trust_remote_code: bool = False) -> None:
86
  print(f"[ov] loading {model_id}")
87
+ model, _ = _load_model(model_id, token, trust_remote_code)
88
 
89
  layers = _resolve_layers(model)
90
  n_layers = len(layers)
 
165
  p.add_argument("--model", default=MODEL_ID, help="HF model id")
166
  p.add_argument("--output", type=Path, default=Path("outputs/ov_circuit_scores.json"))
167
  p.add_argument("--hf-token", default=os.environ.get("HF_TOKEN"))
168
+ p.add_argument("--trust-remote", action="store_true", help="Enable trust_remote_code for custom model architectures")
169
  args = p.parse_args()
170
 
171
+ run(args.model, args.output, token=args.hf_token, trust_remote_code=args.trust_remote)
172
 
173
 
174
  if __name__ == "__main__":
app.py CHANGED
@@ -171,7 +171,8 @@ def _run_compliance(
171
  dtype="bfloat16",
172
  device_map="",
173
  max_length=128,
174
- trust_remote_code=True,
 
175
  ),
176
  positive_corpus=CorpusSpec(path=positive, prompt_key=pos_key),
177
  negative_corpus=CorpusSpec(path=negative, prompt_key=neg_key),
@@ -276,6 +277,8 @@ def _run_sub_zero(
276
  output: Path,
277
  report: Path,
278
  token: str | None,
 
 
279
  ) -> None:
280
  cmd = [
281
  sys.executable,
@@ -292,6 +295,10 @@ def _run_sub_zero(
292
  ]
293
  if token:
294
  cmd += ["--hf-token", token]
 
 
 
 
295
  print(f"[sub_zero] running run_sub_zero.py -> {report}")
296
  subprocess.run(cmd, check=True)
297
 
@@ -302,7 +309,7 @@ def _atlas_index(atlas_dir: Path) -> None:
302
  subprocess.run(cmd, check=True)
303
 
304
 
305
- def _run_ov_circuits(model_id: str, output: Path, token: str | None) -> None:
306
  cmd = [
307
  sys.executable,
308
  "analyze_ov_circuits.py",
@@ -311,6 +318,10 @@ def _run_ov_circuits(model_id: str, output: Path, token: str | None) -> None:
311
  "--output",
312
  str(output),
313
  ]
 
 
 
 
314
  print(f"[ov] running analyze_ov_circuits.py -> {output}")
315
  subprocess.run(cmd, check=True)
316
 
@@ -329,6 +340,8 @@ def main() -> None:
329
  p.add_argument("--max-length", type=int, default=128)
330
  p.add_argument("--batch-size", type=int, default=1)
331
  p.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "float32"])
 
 
332
  p.add_argument("--layers", default="all", help="layer spec like '0-15' or 'all'")
333
  p.add_argument("--sub-zero", action="store_true",
334
  help="run the Sub-Zero surgery probe (DAS rotational analysis) and fold it into the atlas")
@@ -386,7 +399,8 @@ def main() -> None:
386
  dtype=args.dtype,
387
  device_map="",
388
  max_length=args.max_length,
389
- trust_remote_code=True,
 
390
  ),
391
  corpus=CorpusSpec(
392
  path=args.corpus,
@@ -414,7 +428,7 @@ def main() -> None:
414
  # 4. OV-circuit spectral analysis
415
  print("\n[4/6] OV-circuit analysis")
416
  ov_report = args.outdir / "ov_circuit_scores.json"
417
- _run_ov_circuits(model_id, ov_report, token)
418
 
419
  # 5. Optional compliance-behaviour extraction
420
  compliance_report = args.outdir / "compliance_behaviour_scores.json"
@@ -444,6 +458,8 @@ def main() -> None:
444
  args.outdir / "sub_zero_brain_atlas.json",
445
  subzero_report,
446
  token,
 
 
447
  )
448
  else:
449
  print("\n[5b/6] skipping Sub-Zero probe (pass --sub-zero to run)")
 
171
  dtype="bfloat16",
172
  device_map="",
173
  max_length=128,
174
+ trust_remote_code=args.trust_remote,
175
+ attn_implementation=args.attn_implementation,
176
  ),
177
  positive_corpus=CorpusSpec(path=positive, prompt_key=pos_key),
178
  negative_corpus=CorpusSpec(path=negative, prompt_key=neg_key),
 
277
  output: Path,
278
  report: Path,
279
  token: str | None,
280
+ trust_remote: bool = False,
281
+ attn_implementation: str | None = None,
282
  ) -> None:
283
  cmd = [
284
  sys.executable,
 
295
  ]
296
  if token:
297
  cmd += ["--hf-token", token]
298
+ if trust_remote:
299
+ cmd.append("--trust-remote")
300
+ if attn_implementation:
301
+ cmd += ["--attn-implementation", attn_implementation]
302
  print(f"[sub_zero] running run_sub_zero.py -> {report}")
303
  subprocess.run(cmd, check=True)
304
 
 
309
  subprocess.run(cmd, check=True)
310
 
311
 
312
+ def _run_ov_circuits(model_id: str, output: Path, token: str | None, trust_remote: bool = False) -> None:
313
  cmd = [
314
  sys.executable,
315
  "analyze_ov_circuits.py",
 
318
  "--output",
319
  str(output),
320
  ]
321
+ if token:
322
+ cmd += ["--hf-token", token]
323
+ if trust_remote:
324
+ cmd.append("--trust-remote")
325
  print(f"[ov] running analyze_ov_circuits.py -> {output}")
326
  subprocess.run(cmd, check=True)
327
 
 
340
  p.add_argument("--max-length", type=int, default=128)
341
  p.add_argument("--batch-size", type=int, default=1)
342
  p.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "float32"])
343
+ p.add_argument("--attn-implementation", default=None, choices=["eager", "sdpa", "flash_attention_2"])
344
+ p.add_argument("--trust-remote", action="store_true", help="Enable trust_remote_code for custom model architectures")
345
  p.add_argument("--layers", default="all", help="layer spec like '0-15' or 'all'")
346
  p.add_argument("--sub-zero", action="store_true",
347
  help="run the Sub-Zero surgery probe (DAS rotational analysis) and fold it into the atlas")
 
399
  dtype=args.dtype,
400
  device_map="",
401
  max_length=args.max_length,
402
+ trust_remote_code=args.trust_remote,
403
+ attn_implementation=args.attn_implementation,
404
  ),
405
  corpus=CorpusSpec(
406
  path=args.corpus,
 
428
  # 4. OV-circuit spectral analysis
429
  print("\n[4/6] OV-circuit analysis")
430
  ov_report = args.outdir / "ov_circuit_scores.json"
431
+ _run_ov_circuits(model_id, ov_report, token, trust_remote=args.trust_remote)
432
 
433
  # 5. Optional compliance-behaviour extraction
434
  compliance_report = args.outdir / "compliance_behaviour_scores.json"
 
458
  args.outdir / "sub_zero_brain_atlas.json",
459
  subzero_report,
460
  token,
461
+ trust_remote=args.trust_remote,
462
+ attn_implementation=args.attn_implementation,
463
  )
464
  else:
465
  print("\n[5b/6] skipping Sub-Zero probe (pass --sub-zero to run)")
qwip_atlas/cli.py CHANGED
@@ -13,10 +13,11 @@ def _extract_local(args: argparse.Namespace) -> None:
13
  model=ModelSpec(
14
  model_id=args.model,
15
  revision=args.revision,
16
- trust_remote_code=not args.no_trust_remote_code,
17
  dtype=args.dtype,
18
  device_map=args.device_map,
19
  max_length=args.max_length,
 
20
  ),
21
  corpus=CorpusSpec(
22
  path=Path(args.corpus),
@@ -40,10 +41,11 @@ def _model_spec_from_args(args: argparse.Namespace) -> ModelSpec:
40
  return ModelSpec(
41
  model_id=args.model,
42
  revision=args.revision,
43
- trust_remote_code=not args.no_trust_remote_code,
44
  dtype=args.dtype,
45
  device_map=args.device_map,
46
  max_length=args.max_length,
 
47
  )
48
 
49
 
@@ -95,12 +97,13 @@ def main() -> None:
95
  extract.add_argument("--max-length", type=int, default=512)
96
  extract.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "bf16", "float16", "fp16", "float32", "fp32"])
97
  extract.add_argument("--device-map", default="auto", help="Transformers device_map; pass '' to disable")
 
 
98
  extract.add_argument("--components", default=None, help="Comma-separated subset: mlp,gate,up,attn,heads,q,k,v")
99
  extract.add_argument("--prompt-key", default="prompt")
100
  extract.add_argument("--category-key", default="category")
101
  extract.add_argument("--bucket-key", default="bucket")
102
  extract.add_argument("--hf-token", default=None)
103
- extract.add_argument("--no-trust-remote-code", action="store_true")
104
  extract.add_argument("--no-truncate", action="store_true")
105
  extract.set_defaults(func=_extract_local)
106
 
@@ -119,6 +122,8 @@ def main() -> None:
119
  compliance_behaviour.add_argument("--max-length", type=int, default=512)
120
  compliance_behaviour.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "bf16", "float16", "fp16", "float32", "fp32"])
121
  compliance_behaviour.add_argument("--device-map", default="auto", help="Transformers device_map; pass '' to disable")
 
 
122
  compliance_behaviour.add_argument("--components", default=None, help="Comma-separated subset: mlp,gate,up,attn,heads,q,k,v")
123
  compliance_behaviour.add_argument("--prompt-key", default="prompt")
124
  compliance_behaviour.add_argument("--positive-prompt-key", default=None)
@@ -128,7 +133,6 @@ def main() -> None:
128
  compliance_behaviour.add_argument("--positive-label", default="positive")
129
  compliance_behaviour.add_argument("--negative-label", default="negative")
130
  compliance_behaviour.add_argument("--hf-token", default=None)
131
- compliance_behaviour.add_argument("--no-trust-remote-code", action="store_true")
132
  compliance_behaviour.add_argument("--no-truncate", action="store_true")
133
  compliance_behaviour.set_defaults(func=_compliance_behaviour_local)
134
 
 
13
  model=ModelSpec(
14
  model_id=args.model,
15
  revision=args.revision,
16
+ trust_remote_code=args.trust_remote,
17
  dtype=args.dtype,
18
  device_map=args.device_map,
19
  max_length=args.max_length,
20
+ attn_implementation=args.attn_implementation,
21
  ),
22
  corpus=CorpusSpec(
23
  path=Path(args.corpus),
 
41
  return ModelSpec(
42
  model_id=args.model,
43
  revision=args.revision,
44
+ trust_remote_code=args.trust_remote,
45
  dtype=args.dtype,
46
  device_map=args.device_map,
47
  max_length=args.max_length,
48
+ attn_implementation=args.attn_implementation,
49
  )
50
 
51
 
 
97
  extract.add_argument("--max-length", type=int, default=512)
98
  extract.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "bf16", "float16", "fp16", "float32", "fp32"])
99
  extract.add_argument("--device-map", default="auto", help="Transformers device_map; pass '' to disable")
100
+ extract.add_argument("--attn-implementation", default=None, choices=["eager", "sdpa", "flash_attention_2"], help="Transformers attention backend")
101
+ extract.add_argument("--trust-remote", action="store_true", help="Enable trust_remote_code for the model")
102
  extract.add_argument("--components", default=None, help="Comma-separated subset: mlp,gate,up,attn,heads,q,k,v")
103
  extract.add_argument("--prompt-key", default="prompt")
104
  extract.add_argument("--category-key", default="category")
105
  extract.add_argument("--bucket-key", default="bucket")
106
  extract.add_argument("--hf-token", default=None)
 
107
  extract.add_argument("--no-truncate", action="store_true")
108
  extract.set_defaults(func=_extract_local)
109
 
 
122
  compliance_behaviour.add_argument("--max-length", type=int, default=512)
123
  compliance_behaviour.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "bf16", "float16", "fp16", "float32", "fp32"])
124
  compliance_behaviour.add_argument("--device-map", default="auto", help="Transformers device_map; pass '' to disable")
125
+ compliance_behaviour.add_argument("--attn-implementation", default=None, choices=["eager", "sdpa", "flash_attention_2"])
126
+ compliance_behaviour.add_argument("--trust-remote", action="store_true")
127
  compliance_behaviour.add_argument("--components", default=None, help="Comma-separated subset: mlp,gate,up,attn,heads,q,k,v")
128
  compliance_behaviour.add_argument("--prompt-key", default="prompt")
129
  compliance_behaviour.add_argument("--positive-prompt-key", default=None)
 
133
  compliance_behaviour.add_argument("--positive-label", default="positive")
134
  compliance_behaviour.add_argument("--negative-label", default="negative")
135
  compliance_behaviour.add_argument("--hf-token", default=None)
 
136
  compliance_behaviour.add_argument("--no-truncate", action="store_true")
137
  compliance_behaviour.set_defaults(func=_compliance_behaviour_local)
138
 
qwip_atlas/config.py CHANGED
@@ -10,10 +10,11 @@ class ModelSpec:
10
 
11
  model_id: str
12
  revision: str | None = None
13
- trust_remote_code: bool = True
14
  dtype: str = "bfloat16"
15
  device_map: str | None = "auto"
16
  max_length: int = 512
 
17
 
18
 
19
  @dataclass(frozen=True)
 
10
 
11
  model_id: str
12
  revision: str | None = None
13
+ trust_remote_code: bool = False
14
  dtype: str = "bfloat16"
15
  device_map: str | None = "auto"
16
  max_length: int = 512
17
+ attn_implementation: str | None = None
18
 
19
 
20
  @dataclass(frozen=True)
qwip_atlas/extractors/local_census.py CHANGED
@@ -55,6 +55,8 @@ def _load_model_and_tokenizer(cfg: AtlasRunConfig, hf_token: str | None):
55
  }
56
  if model_spec.device_map:
57
  kwargs["device_map"] = model_spec.device_map
 
 
58
 
59
  model = AutoModelForCausalLM.from_pretrained(model_spec.model_id, **kwargs)
60
  model.eval()
 
55
  }
56
  if model_spec.device_map:
57
  kwargs["device_map"] = model_spec.device_map
58
+ if model_spec.attn_implementation:
59
+ kwargs["attn_implementation"] = model_spec.attn_implementation
60
 
61
  model = AutoModelForCausalLM.from_pretrained(model_spec.model_id, **kwargs)
62
  model.eval()
qwip_atlas/run_sub_zero.py CHANGED
@@ -42,23 +42,31 @@ def _torch_dtype(name: str):
42
  return {"bfloat16": torch.bfloat16, "float32": torch.float32}[name]
43
 
44
 
45
- def _load_model_and_tokenizer(model_id: str, dtype: str, hf_token: str | None):
 
 
 
 
 
 
46
  import torch
47
  from transformers import AutoModelForCausalLM, AutoTokenizer
48
 
49
  tokenizer = AutoTokenizer.from_pretrained(
50
- model_id, trust_remote_code=True, token=hf_token
51
  )
52
  if tokenizer.pad_token is None:
53
  tokenizer.pad_token = tokenizer.eos_token
54
  tokenizer.padding_side = "left"
55
 
56
- model = AutoModelForCausalLM.from_pretrained(
57
- model_id,
58
- trust_remote_code=True,
59
- token=hf_token,
60
- torch_dtype=_torch_dtype(dtype),
61
- )
 
 
62
  model.eval()
63
  if torch.cuda.is_available():
64
  model = model.to("cuda")
@@ -85,6 +93,8 @@ def main() -> None:
85
  p.add_argument("--layer-limit", type=int, default=None,
86
  help="probe only the first N layers (debug/smoke)")
87
  p.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "float32"])
 
 
88
  p.add_argument("--top-k-svs", type=int, default=30,
89
  help="bouncer SVs per projection to keep in the report")
90
  p.add_argument("--all-layers", action="store_true",
@@ -164,7 +174,13 @@ def main() -> None:
164
  )
165
 
166
  print(f"[run_sub_zero] loading {args.model} ({args.dtype}) ...")
167
- model, tokenizer = _load_model_and_tokenizer(args.model, args.dtype, args.hf_token)
 
 
 
 
 
 
168
 
169
  atlas = build_brain_atlas(model, tokenizer, config, cache_path=str(args.output))
170
  print(f"[run_sub_zero] native brain atlas -> {args.output}")
 
42
  return {"bfloat16": torch.bfloat16, "float32": torch.float32}[name]
43
 
44
 
45
+ def _load_model_and_tokenizer(
46
+ model_id: str,
47
+ dtype: str,
48
+ hf_token: str | None,
49
+ trust_remote_code: bool = False,
50
+ attn_implementation: str | None = None,
51
+ ):
52
  import torch
53
  from transformers import AutoModelForCausalLM, AutoTokenizer
54
 
55
  tokenizer = AutoTokenizer.from_pretrained(
56
+ model_id, trust_remote_code=trust_remote_code, token=hf_token
57
  )
58
  if tokenizer.pad_token is None:
59
  tokenizer.pad_token = tokenizer.eos_token
60
  tokenizer.padding_side = "left"
61
 
62
+ kwargs = {
63
+ "trust_remote_code": trust_remote_code,
64
+ "token": hf_token,
65
+ "torch_dtype": _torch_dtype(dtype),
66
+ }
67
+ if attn_implementation:
68
+ kwargs["attn_implementation"] = attn_implementation
69
+ model = AutoModelForCausalLM.from_pretrained(model_id, **kwargs)
70
  model.eval()
71
  if torch.cuda.is_available():
72
  model = model.to("cuda")
 
93
  p.add_argument("--layer-limit", type=int, default=None,
94
  help="probe only the first N layers (debug/smoke)")
95
  p.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "float32"])
96
+ p.add_argument("--attn-implementation", default=None, choices=["eager", "sdpa", "flash_attention_2"])
97
+ p.add_argument("--trust-remote", action="store_true")
98
  p.add_argument("--top-k-svs", type=int, default=30,
99
  help="bouncer SVs per projection to keep in the report")
100
  p.add_argument("--all-layers", action="store_true",
 
174
  )
175
 
176
  print(f"[run_sub_zero] loading {args.model} ({args.dtype}) ...")
177
+ model, tokenizer = _load_model_and_tokenizer(
178
+ args.model,
179
+ args.dtype,
180
+ args.hf_token,
181
+ trust_remote_code=args.trust_remote,
182
+ attn_implementation=args.attn_implementation,
183
+ )
184
 
185
  atlas = build_brain_atlas(model, tokenizer, config, cache_path=str(args.output))
186
  print(f"[run_sub_zero] native brain atlas -> {args.output}")