|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: LicenseRef-Apache2 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +r"""Evo2 SAE steering harness — clamp a feature and measure the causal effect on generation. |
| 17 | +
|
| 18 | +Reuses ``Evo2SAE.generate`` (the production decode-only ``sae.steering`` clamp the server/CLI |
| 19 | +use), then quantifies the effect with the pure, CPU-tested metrics in ``steer_analysis``: |
| 20 | +**dose-response** (effect vs clamp strength) for a target feature and **selectivity** (target |
| 21 | +vs control features). Writes a structured ``steering_results.json`` so the evidence is |
| 22 | +persisted and reproducible — the steering analog of ``probe.py annotate``. |
| 23 | +
|
| 24 | +GPU harness — run on an H100 with the inference engine available; this is not a CPU unit test. |
| 25 | +
|
| 26 | + python steer.py --evo2-ckpt-dir <mbridge> --sae-checkpoint <sae.pt> --layer 26 \ |
| 27 | + --sequence ATGGCC... --feature 29244 --controls 12345,54321 --strengths 0,50,100,200 \ |
| 28 | + --out steering_results.json |
| 29 | +""" |
| 30 | + |
| 31 | +from __future__ import annotations |
| 32 | + |
| 33 | +import argparse |
| 34 | +import json |
| 35 | +import sys |
| 36 | +from pathlib import Path |
| 37 | + |
| 38 | + |
| 39 | +_HERE = Path(__file__).resolve().parent |
| 40 | +sys.path.insert(0, str(_HERE)) |
| 41 | +sys.path.insert(0, str(_HERE.parent / "src")) # recipes/evo2/src -> evo2_sae package |
| 42 | +sys.path.insert(0, str(_HERE.parents[2] / "sae" / "src")) |
| 43 | + |
| 44 | +from steer_analysis import dose_response, selectivity # noqa: E402 |
| 45 | + |
| 46 | + |
| 47 | +def main(): |
| 48 | + """Encode a sequence, then steer a target feature (dose-response) + control features (selectivity).""" |
| 49 | + p = argparse.ArgumentParser(description="Evo2 SAE steering harness (clamp -> continuation effect).") |
| 50 | + p.add_argument("--evo2-ckpt-dir", required=True) |
| 51 | + p.add_argument("--sae-checkpoint", required=True) |
| 52 | + p.add_argument("--layer", type=int, required=True) |
| 53 | + p.add_argument("--sequence", required=True) |
| 54 | + p.add_argument("--organism", default="None (raw DNA)") |
| 55 | + p.add_argument("--feature", type=int, default=None, help="Target feature id (default: top labeled feature).") |
| 56 | + p.add_argument("--controls", default="", help="Comma-separated control feature ids (selectivity).") |
| 57 | + p.add_argument("--strengths", default="0,50,100,200", help="Comma-separated clamp strengths to sweep.") |
| 58 | + p.add_argument("--n-tokens", type=int, default=60) |
| 59 | + p.add_argument("--device", default="cuda") |
| 60 | + p.add_argument("--out", default=None, help="write the structured steering_results JSON here") |
| 61 | + a = p.parse_args() |
| 62 | + |
| 63 | + from evo2_sae.core import Evo2SAE # noqa: E402, RUF100 |
| 64 | + |
| 65 | + eng = Evo2SAE(a.evo2_ckpt_dir, a.sae_checkpoint, a.layer, device=a.device).load() |
| 66 | + |
| 67 | + # 1. Encode -> the sequence's most-active features (pick a target if not given). |
| 68 | + codes = eng.encode(a.sequence) |
| 69 | + vals, ids = codes.max(0).values.topk(10) |
| 70 | + print(f"top features on {a.sequence[:24]}...:") |
| 71 | + target = a.feature |
| 72 | + for v, i in zip(vals.tolist(), ids.tolist()): |
| 73 | + lab = eng.labels.get(int(i)) |
| 74 | + print(f" feat {int(i):6d} {str(lab):18s} max_act {v:7.2f}") |
| 75 | + if target is None and lab: |
| 76 | + target = int(i) |
| 77 | + if target is None: # no --feature and no labeled feature in the top-k: steer the most-active one |
| 78 | + target = int(ids[0].item()) |
| 79 | + print(f" (no labeled feature; defaulting target to top-active {target})") |
| 80 | + try: |
| 81 | + controls = [int(c) for c in a.controls.split(",") if c.strip()] |
| 82 | + strengths = [float(s) for s in a.strengths.split(",")] |
| 83 | + except ValueError as e: |
| 84 | + raise SystemExit(f"bad --controls/--strengths (need comma-separated ints/floats): {e}") |
| 85 | + |
| 86 | + # 2. Steered generation reuses the production path: Evo2SAE.generate clamps the same |
| 87 | + # decode-only sae.steering hook the server/CLI use, so the harness measures the real thing. |
| 88 | + def gen(clamps): |
| 89 | + feats = [{"feature_id": f, "strength": v} for f, v in clamps.items()] |
| 90 | + out = eng.generate( |
| 91 | + prompt=a.sequence, organism=a.organism, features=feats, n_tokens=a.n_tokens, temperature=0.0, top_k=1 |
| 92 | + ) |
| 93 | + return out["generation"]["sequence"] |
| 94 | + |
| 95 | + base = gen({}) |
| 96 | + print(f"\nbaseline: {base[:60]}") |
| 97 | + |
| 98 | + # 3. Dose-response for the target feature, scored by steer_analysis. |
| 99 | + steered_by_strength = {s: gen({target: s}) for s in strengths} |
| 100 | + dose = dose_response(base, steered_by_strength) |
| 101 | + print(f"\n=== dose-response: feature {target} ({eng.labels.get(target)}) ===") |
| 102 | + for r in dose: |
| 103 | + print( |
| 104 | + f" strength {r['strength']:7.1f}: diverges@{r['first_divergence']:3d} {r['frac_changed']:6.1%} changed" |
| 105 | + ) |
| 106 | + |
| 107 | + # 4. Selectivity: target vs each control feature at the strongest clamp. |
| 108 | + sel = None |
| 109 | + if controls: |
| 110 | + s = strengths[-1] |
| 111 | + control_steered = {c: gen({c: s}) for c in controls} |
| 112 | + sel = selectivity(base, steered_by_strength[s], control_steered) |
| 113 | + print(f"\n=== selectivity @ strength {s} (target/control ratio {sel['selectivity_ratio']}) ===") |
| 114 | + print(f" target {target:6d}: {sel['target_frac_changed']:6.1%} changed") |
| 115 | + for c, frac in sel["control_frac_changed"].items(): |
| 116 | + print(f" control {c:6d}: {frac:6.1%} changed ({eng.labels.get(c)})") |
| 117 | + |
| 118 | + if a.out: |
| 119 | + Path(a.out).write_text( |
| 120 | + json.dumps( |
| 121 | + { |
| 122 | + "target_feature": target, |
| 123 | + "sequence": a.sequence[:80], |
| 124 | + "organism": a.organism, |
| 125 | + "baseline": base, |
| 126 | + "dose_response": dose, |
| 127 | + "selectivity": sel, |
| 128 | + }, |
| 129 | + indent=2, |
| 130 | + ) |
| 131 | + ) |
| 132 | + print(f"\nwrote steering results -> {a.out}") |
| 133 | + |
| 134 | + |
| 135 | +if __name__ == "__main__": |
| 136 | + main() |
0 commit comments