Spaces:
Paused
Paused
Add a radio dial for the steering coefficient
Browse files16 unmodified lines171819202122232425261 unmodified line282930313233343557 unmodified lines9394959697989910010110210310410510661 unmodified lines1681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132 unmodified lines21621721821922022122222322416 unmodified lines"clean": "analogy_vector_gemma_2_2b_it_clean.pt","raw": "analogy_vector_gemma_2_2b_it.pt","high_alpha": ("Past Gemma-2's peak. Fluency drops above α ≈ 1.5. ""The raw vector often loops the token Imagine."),"mid_alpha": "Near the paper's operating point (α = 1). A plain question starts using an analogy.",},"Qwen-2.5-7B-Instruct": {"hf": "Qwen/Qwen2.5-7B-Instruct",1 unmodified line"paper_alpha": 2.0,"clean": "analogy_vector_qwen_2_5_7b_instruct_clean.pt","raw": "analogy_vector_qwen_2_5_7b_instruct.pt","high_alpha": "Qwen-2.5 keeps strengthening through α = 2. Larger α stays coherent.","mid_alpha": "Near the paper's operating point (α = 2). Analogy keeps growing with α.",},}57 unmodified linesspec = MODELS[model_name]alpha = float(alpha)if alpha < -0.05:meaning = "Negative α attenuates analogy on this question."elif abs(alpha) < 0.05:meaning = "α = 0 leaves the model unsteered."elif alpha >= spec["paper_alpha"] + 0.4:meaning = spec["high_alpha"]else:meaning = spec["mid_alpha"]return f"Layer {spec['layer']}. {meaning}"def _format_prompt(tokenizer, question):61 unmodified linesreturn alpha, alpha_caption(model_name, alpha)def build_demo():import gradio as grwith gr.Blocks(title="Analogy Vector") as demo:gr.Markdown("""# Analogy VectorType any question. The slider adds one extracted direction to the residual stream,`x' = x + α · v`. Nothing in the question has to mention analogy.**α < 0** attenuates it. **α = 0** is the normal answer. **α > 0** brings an analogy out.Gemma-2 peaks near 1, then fades. Qwen-2.5 keeps strengthening through 2.""".strip())with gr.Row():model_name = gr.Dropdown(choices=list(MODELS),value="Gemma-2-2B-IT",label="Model",)use_raw = gr.Checkbox(value=False,label="Raw vector (Imagine collapse at high α)",)question = gr.Textbox(label="Your question",lines=3,value="Explain how TCP/IP handshakes work.",placeholder="Explain how a barcode works.",)alpha = gr.Slider(minimum=-1.5,maximum=2.5,step=0.25,value=1.0,label="Steering coefficient α",)caption = gr.Markdown(alpha_caption("Gemma-2-2B-IT", 1.0))go = gr.Button("Generate", variant="primary")answer = gr.Textbox(label="Answer", lines=14)gr.Examples(examples=[["Explain how TCP/IP handshakes work."],2 unmodified lines["Explain how a vaccine trains the immune system."],],inputs=question,)model_name.change(on_model_change, model_name, [alpha, caption])alpha.change(alpha_caption, [model_name, alpha], caption)go.click(generate,[model_name, question, alpha, use_raw],16 unmodified lines1718192021222324251 unmodified line2728293031323357 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511611761 unmodified lines1791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133142 unmodified lines31731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135216 unmodified lines"clean": "analogy_vector_gemma_2_2b_it_clean.pt","raw": "analogy_vector_gemma_2_2b_it.pt","high_alpha": ("Turned too far for Gemma. Past about 1.5 the answer often falls apart. ""The raw-vector box makes it loop the word Imagine."),},"Qwen-2.5-7B-Instruct": {"hf": "Qwen/Qwen2.5-7B-Instruct",1 unmodified line"paper_alpha": 2.0,"clean": "analogy_vector_qwen_2_5_7b_instruct_clean.pt","raw": "analogy_vector_qwen_2_5_7b_instruct.pt","high_alpha": "Still turned up. Qwen keeps the analogy and usually stays readable.",},}57 unmodified linesspec = MODELS[model_name]alpha = float(alpha)if alpha < -0.05:meaning = "Dial turned left. Analogies should thin out."elif abs(alpha) < 0.05:meaning = "Dial straight up. This is the normal answer, with no steering."elif alpha >= spec["paper_alpha"] + 0.4:meaning = spec["high_alpha"]else:meaning = "Dial turned right. The question never says “analogy,” but the answer should reach for one."return f"**{meaning}**\n\nα = {alpha:.2f}"def preset_alpha(model_name, which):spec = MODELS[model_name]if which == "less":alpha = -1.0elif which == "off":alpha = 0.0elif which == "on":alpha = spec["paper_alpha"]else:alpha = 2.0 if model_name.startswith("Gemma") else 2.5return alpha, alpha_caption(model_name, alpha)def _format_prompt(tokenizer, question):61 unmodified linesreturn alpha, alpha_caption(model_name, alpha)DIAL_CSS = """#dial-stack { position: relative; width: min(320px, 86vw); margin: 0.25rem auto 0; touch-action: none; user-select: none; }#dial { cursor: grab; touch-action: none; }#dial:active { cursor: grabbing; }#dial svg { width: 100%; height: auto; display: block; filter: drop-shadow(0 10px 18px rgba(20, 24, 33, 0.18)); }#dial-readout {position: absolute; left: 0; right: 0; top: 62%;text-align: center; pointer-events: none;font-variant-numeric: tabular-nums;font-size: 1.55rem; font-weight: 700; letter-spacing: -0.03em; color: #1c1917;}#dial-ends { display: flex; justify-content: space-between; width: min(320px, 86vw); margin: 0 auto 0.75rem; color: #57534e; font-size: 0.92rem; }#presets { max-width: 520px; margin: 0 auto; }#alpha-slider { max-width: 520px; margin: 0.25rem auto 0; }#ask-row { max-width: 820px; margin: 0 auto; }"""DIAL_HTML = """<div id="dial-stack"><div id="dial" role="slider" aria-label="Analogy dial" aria-valuemin="-1.5" aria-valuemax="2.5" aria-valuenow="1" tabindex="0"><svg viewBox="0 0 200 200"><circle cx="100" cy="100" r="96" fill="#f5f0e8" stroke="#d6d3d1" stroke-width="2"/><path d="M34 146 A78 78 0 1 1 166 146" fill="none" stroke="#e7e5e4" stroke-width="10" stroke-linecap="round"/><path d="M100 22 A78 78 0 0 1 166 146" fill="none" stroke="#f59e0b" stroke-width="10" stroke-linecap="round" opacity="0.85"/><path d="M34 146 A78 78 0 0 1 100 22" fill="none" stroke="#93c5fd" stroke-width="10" stroke-linecap="round" opacity="0.9"/><g id="dial-needle"><line x1="100" y1="108" x2="100" y2="30" stroke="#1c1917" stroke-width="4" stroke-linecap="round"/><circle cx="100" cy="30" r="5.5" fill="#b45309"/></g><circle cx="100" cy="100" r="7" fill="#1c1917"/></svg></div><div id="dial-readout">+1.00</div></div><div id="dial-ends"><span>less analogy</span><span>off</span><span>more analogy</span></div>"""DIAL_JS = r"""() => {const MIN = -1.5, MAX = 2.5, STEP = 0.25, SWEEP = 135;const boot = () => {const dial = document.getElementById("dial");const needle = document.getElementById("dial-needle");const readout = document.getElementById("dial-readout");const range = document.querySelector("#alpha-slider input[type='range']");if (!dial || !needle || !range) { setTimeout(boot, 200); return; }const snap = (v) => Math.max(MIN, Math.min(MAX, Math.round(v / STEP) * STEP));const toAngle = (v) => v <= 0 ? (v / 1.5) * SWEEP : (v / 2.5) * SWEEP;const fromAngle = (deg) => {deg = Math.max(-SWEEP, Math.min(SWEEP, deg));return deg <= 0 ? (deg / SWEEP) * 1.5 : (deg / SWEEP) * 2.5;};const paint = (v) => {needle.setAttribute("transform", "rotate(" + toAngle(v) + " 100 100)");const text = (v > 0 ? "+" : "") + v.toFixed(2);readout.textContent = Math.abs(v) < 0.001 ? "off" : text;dial.setAttribute("aria-valuenow", v.toFixed(2));};const write = (v) => {v = snap(v);range.value = String(v);const num = document.querySelector("#alpha-slider input[type='number']");if (num) num.value = String(v);range.dispatchEvent(new Event("input", { bubbles: true }));range.dispatchEvent(new Event("change", { bubbles: true }));paint(v);};const pointerValue = (e) => {const box = dial.getBoundingClientRect();const dx = e.clientX - (box.left + box.width / 2);const dy = e.clientY - (box.top + box.height / 2);return fromAngle(Math.atan2(dx, -dy) * 180 / Math.PI);};let dragging = false;dial.addEventListener("pointerdown", (e) => {dragging = true;dial.setPointerCapture(e.pointerId);write(pointerValue(e));e.preventDefault();});dial.addEventListener("pointermove", (e) => { if (dragging) write(pointerValue(e)); });dial.addEventListener("pointerup", () => { dragging = false; });dial.addEventListener("pointercancel", () => { dragging = false; });let seen = null;setInterval(() => {const v = parseFloat(range.value);if (Number.isNaN(v) || v === seen) return;seen = v;paint(v);}, 120);paint(parseFloat(range.value) || 1);};boot();}"""def build_demo():import gradio as grwith gr.Blocks(title="Analogy Vector",theme=gr.themes.Soft(),css=DIAL_CSS,js=DIAL_JS,) as demo:gr.Markdown("""# Analogy VectorAsk any question, then turn the dial. Straight up is the normal answer.Left thins analogies out. Right brings one in, even though you never asked for it.""".strip())model_name = gr.Radio(choices=[("Gemma-2-2B · turns up, then breaks", "Gemma-2-2B-IT"),("Qwen-2.5-7B · keeps growing", "Qwen-2.5-7B-Instruct"),],value="Gemma-2-2B-IT",label="Model",elem_id="model-pick",)question = gr.Textbox(label="Your question",lines=2,value="Explain how TCP/IP handshakes work.",placeholder="Explain how a barcode works.",elem_id="ask-row",)gr.Examples(examples=[["Explain how TCP/IP handshakes work."],2 unmodified lines["Explain how a vaccine trains the immune system."],],inputs=question,label="Try one",)gr.HTML(DIAL_HTML)with gr.Row(elem_id="presets"):less = gr.Button("Less")off = gr.Button("Off")on = gr.Button("Analogy", variant="primary")far = gr.Button("Far")alpha = gr.Slider(minimum=-1.5,maximum=2.5,step=0.25,value=1.0,label="Fine tune",elem_id="alpha-slider",)caption = gr.Markdown(alpha_caption("Gemma-2-2B-IT", 1.0))go = gr.Button("Generate", variant="primary")answer = gr.Textbox(label="Answer", lines=12)use_raw = gr.Checkbox(value=False,label="Raw vector — at Far, Gemma loops the word Imagine",)model_name.change(on_model_change, model_name, [alpha, caption])alpha.change(alpha_caption, [model_name, alpha], caption)less.click(lambda m: preset_alpha(m, "less"), model_name, [alpha, caption])off.click(lambda m: preset_alpha(m, "off"), model_name, [alpha, caption])on.click(lambda m: preset_alpha(m, "on"), model_name, [alpha, caption])far.click(lambda m: preset_alpha(m, "far"), model_name, [alpha, caption])go.click(generate,[model_name, question, alpha, use_raw],
app.py+164-36