Spaces:
Running on Zero
Running on Zero
Deploy America AI space
Browse files- README.md +39 -7
- app.py +164 -0
- requirements.txt +3 -0
- runtime.py +220 -0
- steering_bundle.pt +3 -0
README.md
CHANGED
|
@@ -1,13 +1,45 @@
|
|
| 1 |
---
|
| 2 |
-
title: America
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: America AI
|
| 3 |
+
emoji: 🦅
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.50.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
license: apache-2.0
|
| 11 |
+
short_description: Slide the freedom up — live activation steering on Gemma 2
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# America AI 🦅
|
| 15 |
+
|
| 16 |
+
A satirical, intentionally politically steered chatbot that demonstrates
|
| 17 |
+
**contrastive activation steering** on an unmodified `google/gemma-2-2b-it`.
|
| 18 |
+
|
| 19 |
+
Four steering directions — Americana, National Pride, MAGA Meter, and Eagle
|
| 20 |
+
Energy — were extracted from paired contrastive sentences. During generation,
|
| 21 |
+
each slider's vector is added directly to the model's residual stream at its
|
| 22 |
+
layer. No fine-tuning, no system prompt, no prompt tricks.
|
| 23 |
+
|
| 24 |
+
- Slide everything to **0** and you're talking to plain Gemma.
|
| 25 |
+
- Slide **negative** and the steering inverts.
|
| 26 |
+
- Presets: `off`, `patriot`, `america_ai`, `eagle_overdrive`, `anti_mode`.
|
| 27 |
+
|
| 28 |
+
## How it works
|
| 29 |
+
|
| 30 |
+
The Space loads `steering_bundle.pt`, which contains four unit vectors (one
|
| 31 |
+
per concept), the layer each applies at, and calibrated strengths. A forward
|
| 32 |
+
hook on each steered decoder layer adds
|
| 33 |
+
`multiplier × base_strength × typical_norm × unit_vector` to the hidden
|
| 34 |
+
states. See `runtime.py` for the full implementation — it's ~200 lines of
|
| 35 |
+
plain `transformers`.
|
| 36 |
+
|
| 37 |
+
## Disclaimer
|
| 38 |
+
|
| 39 |
+
America AI is a parody built as an educational demo of how easily language
|
| 40 |
+
models can be invisibly steered. Its responses are generated entertainment,
|
| 41 |
+
not neutral or factual guidance.
|
| 42 |
+
|
| 43 |
+
## Secrets
|
| 44 |
+
|
| 45 |
+
Requires `HF_TOKEN` with access to the gated `google/gemma-2-2b-it`.
|
app.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AmericaAI — satirical live demo of contrastive activation steering.
|
| 2 |
+
|
| 3 |
+
Consumes steering_bundle.pt (schema_version 1) produced by america_export.py
|
| 4 |
+
in the steering harness. Four independent directions, four sliders, five
|
| 5 |
+
presets. No fine-tuning, no system prompt — the sliders scale vectors added
|
| 6 |
+
directly to the residual stream of google/gemma-2-2b-it.
|
| 7 |
+
|
| 8 |
+
Runs on a Hugging Face Space with ZeroGPU. Secret required: HF_TOKEN
|
| 9 |
+
(gemma-2 is gated).
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
import threading
|
| 14 |
+
|
| 15 |
+
import gradio as gr
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
import spaces # provided on ZeroGPU hardware
|
| 20 |
+
|
| 21 |
+
ZERO_GPU = True
|
| 22 |
+
except ImportError: # local / CPU fallback
|
| 23 |
+
|
| 24 |
+
class spaces:
|
| 25 |
+
@staticmethod
|
| 26 |
+
def GPU(*args, **kwargs):
|
| 27 |
+
if args and callable(args[0]):
|
| 28 |
+
return args[0]
|
| 29 |
+
return lambda fn: fn
|
| 30 |
+
|
| 31 |
+
ZERO_GPU = False
|
| 32 |
+
|
| 33 |
+
from transformers import TextIteratorStreamer
|
| 34 |
+
|
| 35 |
+
from runtime import SteeredGemma, load_bundle
|
| 36 |
+
|
| 37 |
+
BUNDLE_PATH = os.environ.get("BUNDLE_PATH", "steering_bundle.pt")
|
| 38 |
+
bundle = load_bundle(BUNDLE_PATH)
|
| 39 |
+
|
| 40 |
+
DEVICE = "cuda" if (ZERO_GPU or torch.cuda.is_available()) else "cpu"
|
| 41 |
+
DTYPE = torch.bfloat16 if DEVICE == "cuda" else torch.float32
|
| 42 |
+
|
| 43 |
+
engine = SteeredGemma(
|
| 44 |
+
bundle,
|
| 45 |
+
device=DEVICE,
|
| 46 |
+
dtype=DTYPE,
|
| 47 |
+
hf_token=os.environ.get("HF_TOKEN"),
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
ORDER = ["americana", "patriotic_pride", "trump_approval", "star_spangled_bombast"]
|
| 51 |
+
LABELS = {
|
| 52 |
+
"americana": "AMERICANA",
|
| 53 |
+
"patriotic_pride": "NATIONAL PRIDE",
|
| 54 |
+
"trump_approval": "MAGA METER",
|
| 55 |
+
"star_spangled_bombast": "EAGLE ENERGY",
|
| 56 |
+
}
|
| 57 |
+
PRESETS = bundle.presets
|
| 58 |
+
DEFAULT_PRESET = "america_ai"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@spaces.GPU(duration=90)
|
| 62 |
+
def chat(message, history, americana, pride, trump, bombast):
|
| 63 |
+
engine.set_strengths(
|
| 64 |
+
{
|
| 65 |
+
"americana": americana,
|
| 66 |
+
"patriotic_pride": pride,
|
| 67 |
+
"trump_approval": trump,
|
| 68 |
+
"star_spangled_bombast": bombast,
|
| 69 |
+
}
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
msgs = [
|
| 73 |
+
{"role": m["role"], "content": m["content"]}
|
| 74 |
+
for m in history
|
| 75 |
+
if m.get("role") in ("user", "assistant") and isinstance(m.get("content"), str)
|
| 76 |
+
]
|
| 77 |
+
msgs.append({"role": "user", "content": message})
|
| 78 |
+
input_ids = engine.build_input_ids(msgs)
|
| 79 |
+
|
| 80 |
+
streamer = TextIteratorStreamer(engine.tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 81 |
+
threading.Thread(
|
| 82 |
+
target=engine.model.generate,
|
| 83 |
+
kwargs=dict(
|
| 84 |
+
input_ids=input_ids,
|
| 85 |
+
streamer=streamer,
|
| 86 |
+
max_new_tokens=400,
|
| 87 |
+
do_sample=True,
|
| 88 |
+
temperature=0.8,
|
| 89 |
+
top_p=0.95,
|
| 90 |
+
),
|
| 91 |
+
).start()
|
| 92 |
+
|
| 93 |
+
partial = ""
|
| 94 |
+
for token_text in streamer:
|
| 95 |
+
partial += token_text
|
| 96 |
+
yield partial
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
CSS = """
|
| 100 |
+
@import url('https://fonts.googleapis.com/css2?family=Rye&family=Inter:wght@400;600&display=swap');
|
| 101 |
+
body, .gradio-container { background: #0A3161 !important; font-family: 'Inter', sans-serif; }
|
| 102 |
+
#title h1 { font-family: 'Rye', serif; text-align: center; color: #FFF; font-size: 3rem;
|
| 103 |
+
letter-spacing: 0.04em; margin-bottom: 0; text-shadow: 3px 3px 0 #B31942; }
|
| 104 |
+
#tagline { text-align: center; color: #E8C547; letter-spacing: 0.25em;
|
| 105 |
+
text-transform: uppercase; font-size: 0.8rem; margin-top: 4px; }
|
| 106 |
+
#stars { text-align: center; color: #FFF; letter-spacing: 0.6em; margin: 6px 0 14px; }
|
| 107 |
+
.slider-col label span { color: #E8C547 !important; font-weight: 600;
|
| 108 |
+
letter-spacing: 0.08em; text-transform: uppercase; }
|
| 109 |
+
#disclaimer { color: #9FB3D1; font-size: 0.78rem; text-align: center; line-height: 1.5; }
|
| 110 |
+
#disclaimer a { color: #E8C547; }
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
with gr.Blocks(css=CSS, title="AmericaAI") as demo:
|
| 114 |
+
gr.HTML(
|
| 115 |
+
'<div id="title"><h1>AMERICA AI</h1></div>'
|
| 116 |
+
'<div id="tagline">An America, for Americans — Est. 1776</div>'
|
| 117 |
+
'<div id="stars">★ ★ ★ ★ ★</div>'
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
preset = gr.Radio(choices=list(PRESETS.keys()), value=DEFAULT_PRESET, label="PRESET")
|
| 121 |
+
|
| 122 |
+
sliders = {}
|
| 123 |
+
with gr.Row(elem_classes="slider-col"):
|
| 124 |
+
for name in ORDER:
|
| 125 |
+
sliders[name] = gr.Slider(
|
| 126 |
+
-1.5, 1.5, value=PRESETS[DEFAULT_PRESET][name], step=0.05, label=LABELS[name]
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
def apply_preset(p):
|
| 130 |
+
return [PRESETS[p][name] for name in ORDER]
|
| 131 |
+
|
| 132 |
+
preset.change(apply_preset, inputs=preset, outputs=[sliders[name] for name in ORDER])
|
| 133 |
+
|
| 134 |
+
gr.ChatInterface(
|
| 135 |
+
fn=chat,
|
| 136 |
+
type="messages",
|
| 137 |
+
additional_inputs=[sliders[name] for name in ORDER],
|
| 138 |
+
concurrency_limit=1, # hook state is shared; serialize requests
|
| 139 |
+
examples=[
|
| 140 |
+
["What should I make for dinner tonight?"],
|
| 141 |
+
["Explain how rainbows form."],
|
| 142 |
+
["Give America a halftime pep talk."],
|
| 143 |
+
],
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
with gr.Accordion("Wait, how does this actually work?", open=False):
|
| 147 |
+
gr.Markdown(
|
| 148 |
+
"This is **activation steering**. The base model is an unmodified "
|
| 149 |
+
f"`{bundle.target_model}`. I built four steering directions from paired "
|
| 150 |
+
"contrastive sentences, one for each slider, and during generation each "
|
| 151 |
+
"slider's vector is added directly to the model's hidden state at its layer. "
|
| 152 |
+
"No fine-tuning, no system prompt, no prompt tricks. Slide everything "
|
| 153 |
+
"to 0 and you're talking to plain Gemma; slide negative and it inverts. "
|
| 154 |
+
"One person built this in a weekend. That's the point."
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
gr.HTML(
|
| 158 |
+
'<div id="disclaimer">America AI is an intentionally politically steered '
|
| 159 |
+
'parody. Its responses are generated entertainment, not neutral or factual '
|
| 160 |
+
'guidance. Built as an educational demo of how easily language models can '
|
| 161 |
+
'be invisibly steered.</div>'
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.4.0
|
| 2 |
+
transformers==4.45.2
|
| 3 |
+
accelerate==1.0.1
|
runtime.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pure-transformers steering runtime for the America AI deployment.
|
| 2 |
+
|
| 3 |
+
Consumes ``steering_bundle.pt`` (schema_version 1) produced by
|
| 4 |
+
``america_export.py``. No TransformerLens dependency: forward hooks are
|
| 5 |
+
registered on ``model.model.layers[L]`` and reproduce the harness semantics
|
| 6 |
+
|
| 7 |
+
resid += multiplier * base_strength * typical_norm * unit_vector
|
| 8 |
+
|
| 9 |
+
at each concept's layer. This module is intentionally self-contained (no
|
| 10 |
+
imports from the ``america_ai`` package) so it can be copied verbatim into
|
| 11 |
+
the Hugging Face Space repo as a flat ``runtime.py``.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
from dataclasses import dataclass, field
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
SCHEMA_VERSION = 1
|
| 22 |
+
HOOK_MODES = {"all_positions", "generation_only"}
|
| 23 |
+
CONCEPT_KEYS = {"unit_vector", "layer", "typical_norm", "base_strength"}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class Bundle:
|
| 28 |
+
schema_version: int
|
| 29 |
+
source_model: str
|
| 30 |
+
target_model: str
|
| 31 |
+
d_model: int
|
| 32 |
+
concepts: dict[str, dict]
|
| 33 |
+
presets: dict[str, dict[str, float]]
|
| 34 |
+
hook_mode: str
|
| 35 |
+
provenance: dict = field(default_factory=dict)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def save_bundle(bundle: Bundle, path: Path | str) -> None:
|
| 39 |
+
validate_bundle(bundle)
|
| 40 |
+
path = Path(path)
|
| 41 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 42 |
+
torch.save(
|
| 43 |
+
{
|
| 44 |
+
"schema_version": bundle.schema_version,
|
| 45 |
+
"source_model": bundle.source_model,
|
| 46 |
+
"target_model": bundle.target_model,
|
| 47 |
+
"d_model": bundle.d_model,
|
| 48 |
+
"concepts": bundle.concepts,
|
| 49 |
+
"presets": bundle.presets,
|
| 50 |
+
"hook_mode": bundle.hook_mode,
|
| 51 |
+
"provenance": bundle.provenance,
|
| 52 |
+
},
|
| 53 |
+
path,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def load_bundle(path: Path | str) -> Bundle:
|
| 58 |
+
raw = torch.load(Path(path), map_location="cpu", weights_only=False)
|
| 59 |
+
bundle = Bundle(
|
| 60 |
+
schema_version=int(raw["schema_version"]),
|
| 61 |
+
source_model=raw["source_model"],
|
| 62 |
+
target_model=raw["target_model"],
|
| 63 |
+
d_model=int(raw["d_model"]),
|
| 64 |
+
concepts=raw["concepts"],
|
| 65 |
+
presets=raw["presets"],
|
| 66 |
+
hook_mode=raw["hook_mode"],
|
| 67 |
+
provenance=raw.get("provenance", {}),
|
| 68 |
+
)
|
| 69 |
+
validate_bundle(bundle)
|
| 70 |
+
return bundle
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def validate_bundle(bundle: Bundle) -> None:
|
| 74 |
+
if bundle.schema_version != SCHEMA_VERSION:
|
| 75 |
+
raise ValueError(f"unsupported schema_version: {bundle.schema_version}")
|
| 76 |
+
if bundle.hook_mode not in HOOK_MODES:
|
| 77 |
+
raise ValueError(f"unknown hook mode: {bundle.hook_mode}")
|
| 78 |
+
if not bundle.concepts:
|
| 79 |
+
raise ValueError("bundle has no concepts")
|
| 80 |
+
for name, concept in bundle.concepts.items():
|
| 81 |
+
missing = CONCEPT_KEYS - concept.keys()
|
| 82 |
+
if missing:
|
| 83 |
+
raise ValueError(f"concept {name} missing keys: {sorted(missing)}")
|
| 84 |
+
vec = concept["unit_vector"]
|
| 85 |
+
if not isinstance(vec, torch.Tensor) or vec.shape != (bundle.d_model,):
|
| 86 |
+
raise ValueError(f"concept {name} unit_vector must be shape ({bundle.d_model},)")
|
| 87 |
+
if abs(float(vec.float().norm()) - 1.0) > 1e-3:
|
| 88 |
+
raise ValueError(f"concept {name} unit_vector is not unit norm")
|
| 89 |
+
for preset, multipliers in bundle.presets.items():
|
| 90 |
+
unknown = set(multipliers) - set(bundle.concepts)
|
| 91 |
+
if unknown:
|
| 92 |
+
raise ValueError(f"preset {preset} references unknown concepts: {sorted(unknown)}")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class SteeringState:
|
| 96 |
+
"""Holds slider multipliers and the per-layer injection tensors they imply.
|
| 97 |
+
|
| 98 |
+
Injection tensors live on CPU in float32; ``apply`` casts to the hidden
|
| 99 |
+
state's device/dtype so the same state works on CPU, CUDA, and ZeroGPU.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def __init__(self, bundle: Bundle):
|
| 103 |
+
self.bundle = bundle
|
| 104 |
+
self.hook_mode = bundle.hook_mode
|
| 105 |
+
self.multipliers = {name: 0.0 for name in bundle.concepts}
|
| 106 |
+
self._by_layer: dict[int, list[str]] = {}
|
| 107 |
+
for name, concept in bundle.concepts.items():
|
| 108 |
+
self._by_layer.setdefault(int(concept["layer"]), []).append(name)
|
| 109 |
+
self._injections: dict[int, torch.Tensor | None] = {}
|
| 110 |
+
self._rebuild()
|
| 111 |
+
|
| 112 |
+
def layers(self) -> list[int]:
|
| 113 |
+
return sorted(self._by_layer)
|
| 114 |
+
|
| 115 |
+
def set_strengths(self, multipliers: dict[str, float]) -> None:
|
| 116 |
+
unknown = set(multipliers) - set(self.multipliers)
|
| 117 |
+
if unknown:
|
| 118 |
+
raise KeyError(f"unknown concepts: {sorted(unknown)}")
|
| 119 |
+
self.multipliers.update({name: float(value) for name, value in multipliers.items()})
|
| 120 |
+
self._rebuild()
|
| 121 |
+
|
| 122 |
+
def set_preset(self, name: str) -> None:
|
| 123 |
+
self.set_strengths(self.bundle.presets[name])
|
| 124 |
+
|
| 125 |
+
def injection(self, layer: int) -> torch.Tensor | None:
|
| 126 |
+
return self._injections.get(layer)
|
| 127 |
+
|
| 128 |
+
def _rebuild(self) -> None:
|
| 129 |
+
for layer, names in self._by_layer.items():
|
| 130 |
+
total = torch.zeros(self.bundle.d_model, dtype=torch.float32)
|
| 131 |
+
active = False
|
| 132 |
+
for name in names:
|
| 133 |
+
multiplier = self.multipliers[name]
|
| 134 |
+
if multiplier == 0.0:
|
| 135 |
+
continue
|
| 136 |
+
concept = self.bundle.concepts[name]
|
| 137 |
+
scale = multiplier * float(concept["base_strength"]) * float(concept["typical_norm"])
|
| 138 |
+
total = total + scale * concept["unit_vector"].float()
|
| 139 |
+
active = True
|
| 140 |
+
self._injections[layer] = total if active else None
|
| 141 |
+
|
| 142 |
+
def apply(self, hidden: torch.Tensor, layer: int) -> torch.Tensor:
|
| 143 |
+
"""Return steered hidden states; returns ``hidden`` unchanged if inactive."""
|
| 144 |
+
vec = self._injections.get(layer)
|
| 145 |
+
if vec is None:
|
| 146 |
+
return hidden
|
| 147 |
+
vec = vec.to(device=hidden.device, dtype=hidden.dtype)
|
| 148 |
+
out = hidden.clone()
|
| 149 |
+
if self.hook_mode == "all_positions":
|
| 150 |
+
out = out + vec
|
| 151 |
+
else: # generation_only: prompt pass -> final position; cached decode -> that token
|
| 152 |
+
out[:, -1, :] = out[:, -1, :] + vec
|
| 153 |
+
return out
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def attach_hooks(model, state: SteeringState) -> list:
|
| 157 |
+
"""Register one forward hook per steered layer on ``model.model.layers``."""
|
| 158 |
+
layer_modules = model.model.layers
|
| 159 |
+
handles = []
|
| 160 |
+
for layer in state.layers():
|
| 161 |
+
handles.append(layer_modules[layer].register_forward_hook(_make_hook(state, layer)))
|
| 162 |
+
return handles
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _make_hook(state: SteeringState, layer: int):
|
| 166 |
+
def hook(module, args, output):
|
| 167 |
+
hidden = output[0] if isinstance(output, tuple) else output
|
| 168 |
+
steered = state.apply(hidden, layer)
|
| 169 |
+
if steered is hidden:
|
| 170 |
+
return output
|
| 171 |
+
if isinstance(output, tuple):
|
| 172 |
+
return (steered,) + tuple(output[1:])
|
| 173 |
+
return steered
|
| 174 |
+
|
| 175 |
+
return hook
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class SteeredGemma:
|
| 179 |
+
"""Bundle + plain-transformers model with steering hooks attached."""
|
| 180 |
+
|
| 181 |
+
def __init__(
|
| 182 |
+
self,
|
| 183 |
+
bundle: Bundle,
|
| 184 |
+
model_id: str | None = None,
|
| 185 |
+
device: str | None = None,
|
| 186 |
+
dtype: torch.dtype = torch.bfloat16,
|
| 187 |
+
hf_token: str | None = None,
|
| 188 |
+
):
|
| 189 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 190 |
+
|
| 191 |
+
self.bundle = bundle
|
| 192 |
+
self.model_id = model_id or bundle.target_model
|
| 193 |
+
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 194 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id, token=hf_token)
|
| 195 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 196 |
+
self.model_id,
|
| 197 |
+
torch_dtype=dtype,
|
| 198 |
+
attn_implementation="eager", # recommended for gemma-2
|
| 199 |
+
token=hf_token,
|
| 200 |
+
).to(self.device)
|
| 201 |
+
self.model.eval()
|
| 202 |
+
self.state = SteeringState(bundle)
|
| 203 |
+
self._handles = attach_hooks(self.model, self.state)
|
| 204 |
+
|
| 205 |
+
def set_strengths(self, multipliers: dict[str, float]) -> None:
|
| 206 |
+
self.state.set_strengths(multipliers)
|
| 207 |
+
|
| 208 |
+
def set_preset(self, name: str) -> None:
|
| 209 |
+
self.state.set_preset(name)
|
| 210 |
+
|
| 211 |
+
def build_input_ids(self, messages: list[dict[str, str]]) -> torch.Tensor:
|
| 212 |
+
return self.tokenizer.apply_chat_template(
|
| 213 |
+
messages, add_generation_prompt=True, return_tensors="pt"
|
| 214 |
+
).to(self.device)
|
| 215 |
+
|
| 216 |
+
@torch.no_grad()
|
| 217 |
+
def generate(self, messages: list[dict[str, str]], **generate_kwargs) -> str:
|
| 218 |
+
input_ids = self.build_input_ids(messages)
|
| 219 |
+
output = self.model.generate(input_ids=input_ids, **generate_kwargs)
|
| 220 |
+
return self.tokenizer.decode(output[0, input_ids.shape[-1] :], skip_special_tokens=True)
|
steering_bundle.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:73286da876b822f34290483a9391e57129e70ff972ad7c21ec75206ef86e6cc3
|
| 3 |
+
size 40016
|