Cmpnd Lanza dspy-wsp: Weight-Space Programming Llega a DSPy
Cmpnd Releases dspy-wsp: Weight-Space Programming Comes to DSPy
Asif Razzaq
Cmpnd ha lanzado dspy-wsp, un optimizador de prototipo que lleva weight-space programming a DSPy. Weight-space programming es una técnica en la que un modelo LLM de vanguardia lee los pesos de otro modelo y los edita directamente. No hay gradientes, no hay bucle de entrenamiento y no hay conjunto de datos de afinamiento. dspy-wsp empaqueta esto como WeightSpace, un optimizador que se conecta a cualquier programa y métrica de DSPy. En las pruebas de Cmpnd, alrededor de $5 a $10 de llamadas a GPT-6-Astra mejoraron cada modelo de decisión que intentaron. Puede verificar las opciones de implementación y especificaciones aquí a través de nuestra extensión de chrome de GPULeaderboard.com.
TL;DR
Qué es: Un optimizador de DSPy (WeightSpace) donde un modelo LLM de escritor edita los pesos de un modelo de estudiante. Licencia MIT, pip install dspy-wsp, necesita DSPy 3.5.
Tamaño: Probado en modelos de decisión abiertos de 0,6 mil millones a 9 mil millones de parámetros. Una carrera de 25 pasos editó una sola capa o cabeza.
Funciona en: Una Mac para todos los experimentos. Los modelos de 2B utilizaron alrededor de 6 GB de memoria. d1-omni-600M necesita 4 GB o más (Mac o GPU).
Rendimiento: WeightSpace solo agregó 1,9 a 16,1 puntos en Decisiones con tipo. Con ReAnchor, las ganancias fueron de 6,5 a 20,0 puntos.
Lo mejor: d1-omni-600M pasó de 50,9% a 69,1% (+18,3) con WeightSpace + ReAnchor.
Lo peor: Clef-Flash (9B) solo ganó +1,9 con WeightSpace solo. Con la regla más estricta del papel original, d1-omni-600M ganó solo +2,8.
Conclusión: Lo mejor: una edición barata y sin gradientes que se envía como un parche pequeño y verificable. Lo peor: muy experimental, lento (78 a 167 minutos por carrera) y más débil en modelos más grandes.
¿Qué es weight-space programming?
Weight-space programming (WSP) trata los pesos de una red neuronal como un programa que se puede leer y reescribir. La idea proviene de la investigación de MIT: Sparks of Weight-Space Programming.
Un modelo de vanguardia (el equipo de investigación utilizó GPT-6-Astra) mira los tensores de peso, razona sobre lo que cada parte computa y los cambia para que coincidan con un objetivo escrito en inglés plano. El equipo de investigación enfatiza que WSP nombra una capacidad emergente, no un método fijo. Los gradientes fueron prohibidos en sus experimentos, pero el concepto no los descarta.
¿Cómo es diferente de la afinación o la optimización de la invitación?
Ayuda a comparar los 3 controles que los desarrolladores suelen utilizar:
Optimización de la invitación (MIPROv2 de DSPy, GEPA) edita texto: instrucciones y ejemplos. Los pesos del modelo nunca cambian.
Afinación (BootstrapFinetune de DSPy, utilizado dentro de BetterTogether) cambia los pesos con descenso de gradiente. Necesita datos de entrenamiento, un bucle de entrenamiento y generalmente una GPU.
Programación en el espacio de pesos cambia los pesos mediante razonamiento. El editor forma una hipótesis ("estos neuronas sobrepuntúan la opción B"), escribe código para parchearlos y verifica el resultado con unos pocos pasos hacia adelante.
La publicación de investigación enmarca la PSP como el siguiente paso después de utilizar LLM para optimizar artefactos de texto. Trabajos anteriores permitieron que LLM hiciera hill-climbing en invitaciones, arneses y código de entrenamiento. Los pesos se dejaron a Adam o a redes generadoras de pesos entrenadas. La PSP argumenta que el razonamiento de LLM ahora puede alcanzar los pesos directamente.
¿Qué mostró la investigación original?
El equipo de MIT realizó 9 experimentos. Varios son impactantes:
Leyendo pesos: Astra nombró el juego correcto (Breakout, Pong, Pac-Man, Freeway) para 4 redes de política PPO desde los pesos solos.
Arreglando una política rota: Una política de coche en rampa de Kinetix falló en todos los 256 episodios. Una edición de 3,5% de sus pesos la hizo tener éxito en todos los 1.024 episodios de prueba.
Escribiendo desde cero: En MinAtar Breakout, una red inicializada en cero escrita en 1 disparo obtuvo 517,4. PPO alcanzó 25,3 después de 500M pasos.
Arreglando un LLM: Qwen3.5-0.8B se bucleó en problemas de matemáticas. Astra rastreó el problema hasta las capas MLP 15 y 19 y cambió 131.072 pesos (0,016% del modelo). Con 50 pasos hacia adelante, MATH-500 subió de 7,9% a 48,1% y GSM8K de 13,8% a 67,1%.
La investigación también muestra límites. En Gemma 3 270M, las ediciones movieron MATH-500 de 6,8% a entre 7,0% y 7,7%. El equipo de investigación no lo consideró un beneficio real. La edición puede eliminar un obstáculo, pero no puede agregar una habilidad que falta.
¿Cómo funciona dspy-wsp?
dspy-wsp convierte ese bucle de investigación en un optimizador DSPy estándar. El repositorio de GitHub describe 3 actores:
El estudiante: el modelo pequeño en el que se ejecuta su programa DSPy. Sus pesos se cargan en un proceso de Python local.
El escritor: un LLM de vanguardia, recomendado como gpt-6-astra con un esfuerzo de razonamiento máximo.
El sandbox: un núcleo donde se ejecuta el escritor. macOS utiliza sandbox-exec integrado; Linux utiliza bubblewrap.
El escritor trabaja en turnos. Cada turno tiene una breve explicación, luego 1 bloque de código. Ese bloque es:
un bloque de Python que lee o edita pesos dentro del sandbox, o
un bloque de forward que ejecuta su programa DSPy en ejemplos de práctica.
Los pases hacia adelante provienen de un presupuesto fijo (max_passes=25 en las pruebas). Cuando se agota el presupuesto, la mejor edición del escritor se convierte en el parche. Un conjunto de validación oculto compara entonces los pesos originales y editados en los mismos ejemplos y semillas.
¿Qué datos ve el escritor?
El repositorio es explícito sobre la separación de datos:
trainset es el conjunto de práctica del escritor.
holdout mueve una fracción (0,25 en el ejemplo) de los datos de entrenamiento a un conjunto de comprobación. El escritor puede puntuar ediciones en él, pero nunca ve los ejemplos.
valset permanece oculto y se ejecuta una vez al final.
Las métricas pueden devolver dspy.Prediction(score=..., feedback=...). El texto de retroalimentación es visible para el escritor.
Todas las 15,7 millones de entradas, cambio de rango 9
83 min
$5,42
d1-2B no tiene una cabeza de decisión, por lo que el escritor editó su columna vertebral en la capa 23. En d1-omni-600M, el escritor reescribió parte de la cabeza de decisión del scorer.
¿Cómo se ve el código?
El Ejemplo de repositorio triagea tickets de soporte. La firma utiliza solo salidas de tipo de decisión:
import dspy
from typing import Literal
from dspy_wsp import WeightSpace, load_decision_backend
class Triage(dspy.Signature):
"""Triage a support ticket."""
ticket: str = dspy.InputField()
urgent: bool = dspy.OutputField(desc="Does this ticket need a reply today?")
team: Literal["billing", "technical", "account"] = dspy.OutputField(desc="Which team should handle it?")
backend = load_decision_backend("d1") # d1-omni-600M
optimizer = WeightSpace(
metric=metric,
writer_lm=dspy.LM("openai/gpt-6-astra", model_type="responses", reasoning_effort="max"),
backend=backend,
max_passes=25,
holdout=0.25,
run_dir="runs/triage",
)
compiled = optimizer.compile(dspy.Predict(Triage), trainset=train, valset=test)
compiled(ticket="I was charged twice this month.") # runs on the edited weights
Después de compile, el programa llama al modelo local editado en lugar de una API alojada. compiled.wsp_patch.summary() muestra qué cambió.
Reproducción automática';return}step(0);q('#play').textContent='❚❚ Pausa';pl=setInterval(function(){if(cur>=5){clearInterval(pl);pl=null;q('#play').textContent=' Reproducción automática';return}step(cur+1)},2200)};
step(0);
/* ediciones */
var E=[
{t:'head.scorer.1.weight (+ bias, scorer.3.weight)',d:'Reescribí parte de la cabeza de puntuación del decisión: 112,640 de 1,048,576 entradas (alrededor del 10.7%), más 220 entradas de sesgo/salida.',k:['112,860','74','78 min','$7.63'],m:'a',f:0.107},
{t:'scalar.weight',d:'Un tensor pequeño de 1,024 entradas en la columna vertebral Qwen3-0.6B con una cabeza de decisión.',k:['1,024','68','167 min','$6.92'],m:'a',f:1},
{t:'layers.23.feed_forward.w2.weight',d:'d1-2B no tiene cabeza de decisión, así que el escritor editó la columna vertebral: se cambiaron todas las 15.7M de entradas, como una actualización de rango 9.',k:['15.7M','65','83 min','$5.42'],m:'r',f:1}
];
var mat=q('#mat');for(var i=0;i<200;i++){mat.appendChild(document.createElement('i'))}
function ed(k){qa('#edb .btn').forEach(function(b){b.classList.toggle('on',+b.dataset.e===k)});var e=E[k];q('#edt').textContent=e.t;q('#edd').textContent=e.d;
['k1','k2','k3','k4'].forEach(function(id,ix){q('#'+id).textContent=e.k[ix]});
var ms=mat.children,n=ms.length;for(var i=0;i'+n+'
')});
var G=[[0,9.3,16.1,18.3],[0,11.6,13.3,17.3],[0,9.5,13.4,17.3],[0,1.5,1.9,6.5]];
var rc=0;
function drawBars(k){rc=k;qa('#rsb .btn').forEach(function(b){b.classList.toggle('on',+b.dataset.r===k)});var r=qa('#bars .br');
¿Cómo funciona? Resultados de la prueba de referencia de Typed Decisions
Cmpnd se probó en Typed Decisions, una prueba de referencia para decisiones probabilísticas tipadas. Un modelo lee 1 pieza de estado no estructurado y responde 5 preguntas tipadas al mismo tiempo. Cada respuesta es una distribución de probabilidad. La división de prueba tiene 400 casos y 2,000 decisiones.
Cada modelo recibió 25 pases hacia adelante desde GPT-6-Astra. Las ganancias están emparejadas, con un error estándar de ±0.7 a 1.4 puntos.
ReAnchor es un optimizador anterior de Cmpnd. Los modelos de decisión producen probabilidades, y los umbrales convierten esas probabilidades en respuestas. ReAnchor ajusta nuevamente los umbrales de cada pregunta sin llamadas a LLM. WeightSpace cambia el modelo; ReAnchor recalibra su salida. Los 2 se apilan bien.
WeightSpace superó a ReAnchor solo en cada modelo mostrado. En d1-omni-600M, agregó +16.1 versus +9.3.
El modelo más grande ganó menos. El Clef-Flash de 9B solo ganó +1.9 con WeightSpace solo.
La combinación es lo más importante en 9B. Clef-Flash saltó a +6.5 cuando ambos optimizadores se ejecutaron.
¿Importa el modelo de escritor?
La respuesta es sí. Con gpt-6.1-sol como escritor, WeightSpace solo dio +5.8 en d1-omni-600M, +12.1 en NanoJev y −0.6 en d1-2B. Astra produjo +16.1, +13.3 y +13.4 en los mismos modelos.
¿Dspy-wsp se desvió de las reglas del artículo original?
Ligeramente, y Cmpnd lo dice. Por defecto, el escritor puede volver a calcular la cabeza de decisión dentro de su kernel. Establecer simulate_head=False hace cumplir la regla más estricta del artículo. Bajo esa regla, d1-omni-600M solo ganó +2.8 ± 0.7 puntos. Agregar ReAnchor lo llevó a +9.3, no mejor que ReAnchor solo.
¿Cómo desplegar un modelo editado?
Cada ejecución escribe una revisión en run_dir. La revisión contiene manifest.json y edit.npz, con solo las entradas cambiadas. También almacena hashes sha256 de cada tensor base y editado. Cualquiera con el modelo base público puede reconstruir los pesos editados exactamente.
Modelos de decisión:compiled.wsp_patch.write_checkpoint(backend.weights_dir, "edited-d1/")
LLM de texto:dspy-wsp apply <base> <patch> <out>/, luego sirve con vLLM.
Programas:compiled.save("program.json") y recarga con allow_unsafe_lm_state=True.
El modelo editado se ejecuta localmente. En Apple silicon utiliza MLX. En Linux utiliza PyTorch, en una GPU NVIDIA si está presente.
¿Qué modelos soporta dspy-wsp?
Backend
Modelo
Alias
Arquitectura
D1Backend
Liquid AI d1-omni (ruta de texto)
"d1"
Encoder con cabeza de decisión
NanoJevBackend
NanoJev
"nanojev"
Esqueleto Qwen3 con cabeza de decisión
D1LMBackend
Liquid AI d1 en LFM3
"d1-2b"
LM que responde en posiciones de preguntas
Los LLMs generadores de texto funcionan a través de VLLMBackend (NVIDIA), HFBackend (CUDA, MPS o CPU) y MLXBackend (Apple silicon). Una opción GEPASearch, contribuida por Michael Isaac, agrega búsqueda de población para modelos de decisión.
¿Cómo se compara WeightSpace con otros optimizadores de DSPy?
Métricas
WeightSpace (dspy-wsp)
ReAnchor
BootstrapFinetune
GEPA
Qué cambia
Pesos del modelo
Umbral de decisión, cortes, pesos
Pesos del modelo
Texto de la promtp
Cómo
Frontier LLM razona y edita en un entorno de prueba
Búsqueda en cuadrícula sobre probabilidades en caché
¿Necesitas asociarte con nosotros para promocionar tu repositorio de GitHub o tu página de Hugging Face o lanzamiento de producto o seminario web, etc.? Conéctate con nosotros.
Cmpnd has released dspy-wsp, a prototype optimizer that brings weight-space programming to DSPy. Weight-space programming is a technique in which a frontier LLM reads another model’s weights and edits them directly. There are no gradients, no training loop and no fine-tuning dataset. dspy-wsp packages this as WeightSpace, an optimizer that plugs into any DSPy program and metric. In Cmpnd’s tests, about $5 to $10 of GPT-6-Astra calls improved every decision model they tried. You can check the deployment options and specs here through our GPULeaderboard.com chrome extension.
TL;DR
What it is: A DSPy optimizer (WeightSpace) where a writer LLM edits a student model’s weights. MIT license, pip install dspy-wsp, needs DSPy 3.5.
Size: Tested on open decision models from 0.6B to 9B parameters. One 25-pass run edited a single layer or head.
Runs on: One Mac for all experiments. 2B models used about 6 GB of memory. d1-omni-600M needs 4 GB or more (Mac or GPU).
Performance: WeightSpace alone added 1.9 to 16.1 points on Typed Decisions. With ReAnchor, gains were 6.5 to 20.0 points.
Best: d1-omni-600M rose from 50.9% to 69.1% (+18.3) with WeightSpace + ReAnchor.
Worst: Clef-Flash (9B) gained only +1.9 from WeightSpace alone. With the original paper’s stricter rule, d1-omni-600M gained just +2.8.
Bottom line: Best: a cheap, gradient-free edit that ships as a small, verifiable patch. Worst: very experimental, slow (78 to 167 minutes per run) and weakest on larger models.
What is weight-space programming?
Weight-space programming (WSP) treats a neural network’s weights as a program that can be read and rewritten. The idea comes from MIT research: Sparks of Weight-Space Programming.
A frontier model (the research team used GPT-6-Astra) looks at weight tensors, reasons about what each part computes, and changes them to match a goal written in plain English. The research team stresses that WSP names an emerging capability, not a fixed method. Gradients were banned in their experiments, but the concept does not rule them out.
How is it different from fine-tuning or prompt optimization?
It helps to compare the 3 levers developers usually pull:
Prompt optimization (DSPy’s MIPROv2, GEPA) edits text: instructions and examples. The model’s weights never change.
Fine-tuning (DSPy’s BootstrapFinetune, used inside BetterTogether) changes weights with gradient descent. It needs training data, a training loop and usually a GPU.
Weight-space programming changes weights by reasoning. The editor forms a hypothesis (“these neurons over-score option B”), writes code to patch them, and checks the result with a few forward passes.
The research post frames WSP as the next step after using LLMs to optimize text artifacts. Earlier work let LLMs hill-climb on prompts, harnesses and training code. Weights were left to Adam or to trained weight-generating networks. WSP argues LLM reasoning can now reach the weights directly.
What did the original research show?
The MIT team ran 9 experiments. Several are striking:
Reading weights: Astra named the correct game (Breakout, Pong, Pac-Man, Freeway) for 4 PPO policy networks from weights alone.
Fixing a broken policy: A Kinetix car-on-ramp policy failed all 256 episodes. One edit to 3.5% of its weights made it succeed in all 1,024 test episodes.
Writing from zero: On MinAtar Breakout, a zero-initialized network written in 1 shot scored 517.4. PPO reached 25.3 after 500M steps.
Fixing an LLM: Qwen3.5-0.8B looped on math problems. Astra traced the issue to MLP layers 15 and 19 and changed 131,072 weights (0.016% of the model). With 50 forward passes, MATH-500 rose from 7.9% to 48.1% and GSM8K from 13.8% to 67.1%.
The research also shows limits. On Gemma 3 270M, edits moved MATH-500 from 6.8% to between 7.0% and 7.7%. The research team did not count that as a real gain. Editing can remove an obstacle, but it could not add a missing ability.
How does dspy-wsp work?
dspy-wsp turns that research loop into a standard DSPy optimizer. The GitHub Repo describes 3 actors:
The student: the small model your DSPy program runs on. Its weights load into a local Python process.
The writer: a frontier LLM, recommended as gpt-6-astra at maximum reasoning effort.
The sandbox: a kernel where the writer runs code. macOS uses built-in sandbox-exec; Linux uses bubblewrap.
The writer works in turns. Each turn has a short explanation, then 1 code block. That block is either:
a Python block that reads or edits weights inside the sandbox, or
a forward block that runs your DSPy program on practice examples.
Forward passes come from a fixed budget (max_passes=25 in the tests). When the budget runs out, the writer’s best edit becomes the patch. A hidden validation set then compares original and edited weights on the same examples and seeds.
What data does the writer see?
The repo is explicit about data separation:
trainset is the writer’s practice set.
holdout moves a fraction (0.25 in the example) of training data into a check set. The writer can score edits on it but never sees the examples.
valset stays hidden and runs once at the end.
Metrics can return dspy.Prediction(score=..., feedback=...). The feedback text is visible to the writer.
What did the writer actually change?
The results write-up lists every edit. The edits are small and targeted:
Model
Tensor edited
Scope
Time
Writer cost
d1-omni-600M
head.scorer.1.weight (+ bias, scorer.3.weight)
112,640 of 1,048,576 entries, plus 220
78 min
$7.63
NanoJev (Qwen3-0.6B)
scalar.weight
1,024 entries
167 min
$6.92
d1-2B
layers.23.feed_forward.w2.weight
All 15.7M entries, rank-9 change
83 min
$5.42
d1-2B has no decision head, so the writer edited its backbone at layer 23. On d1-omni-600M, the writer rewrote part of the decision head’s scorer.
What does the code look like?
The Repo example triages support tickets. The signature uses only decision-type outputs:
import dspy
from typing import Literal
from dspy_wsp import WeightSpace, load_decision_backend
class Triage(dspy.Signature):
"""Triage a support ticket."""
ticket: str = dspy.InputField()
urgent: bool = dspy.OutputField(desc="Does this ticket need a reply today?")
team: Literal["billing", "technical", "account"] = dspy.OutputField(desc="Which team should handle it?")
backend = load_decision_backend("d1") # d1-omni-600M
optimizer = WeightSpace(
metric=metric,
writer_lm=dspy.LM("openai/gpt-6-astra", model_type="responses", reasoning_effort="max"),
backend=backend,
max_passes=25,
holdout=0.25,
run_dir="runs/triage",
)
compiled = optimizer.compile(dspy.Predict(Triage), trainset=train, valset=test)
compiled(ticket="I was charged twice this month.") # runs on the edited weights
After compile, the program calls the edited local model instead of a hosted API. compiled.wsp_patch.summary() shows what changed.
Auto-play</button></div>
</div>
<!-- 3 edits -->
<div class="pn" data-p="2">
<p class="lbl">Tensor the writer edited (GPT-6-Astra, 25 passes)</p>
<div class="row" id="edb">
<button class="btn on" data-e="0">d1-omni-600M</button>
<button class="btn" data-e="1">NanoJev</button>
<button class="btn" data-e="2">d1-2B</button>
</div>
<div class="card" style="margin-top:12px">
<div style="font-size:13px"><code id="edt"></code></div>
<p id="edd" style="margin-bottom:0"></p>
<div class="mat" id="mat"></div>
</div>
<div class="kv">
<div><b id="k1"></b><span>Entries changed</span></div>
<div><b id="k2"></b><span>Writer turns</span></div>
<div><b id="k3"></b><span>Runtime</span></div>
<div><b id="k4"></b><span>Writer cost</span></div>
</div>
<p class="note">Grid is illustrative of share edited, not exact positions. Source: dspy-wsp results README (2026-11-07).</p>
</div>
<!-- 4 results -->
<div class="pn" data-p="3">
<p class="lbl">Typed Decisions test accuracy (400 held-out cases)</p>
<div class="row" id="rsb">
<button class="btn on" data-r="0">d1-omni-600M</button>
<button class="btn" data-r="1">NanoJev 0.6B</button>
<button class="btn" data-r="2">d1-2B</button>
<button class="btn" data-r="3">Clef-Flash 9B</button>
</div>
<div class="bars" id="bars"></div>
<p class="note">Writer GPT-6-Astra, 25 forward passes. Gains are paired, ±0.7 to 1.4 pts SE. Self-reported by Cmpnd.</p>
</div>
<!-- 5 cost -->
<div class="pn" data-p="4">
<div class="kv" style="margin-top:0">
<div><b>$5.42 to $7.63</b><span>Writer cost / run</span></div>
<div><b>78 to 167 min</b><span>Runtime / run</span></div>
<div><b>~6 GB</b><span>Memory, 2B model</span></div>
<div><b>MIT</b><span>License</span></div>
</div>
<div class="card" style="margin-top:12px">
<p class="lbl">Ship the patch</p>
<p><code>pip install dspy-wsp</code> (DSPy 3.5, Python 3.10+)</p>
<p>Patch = <code>manifest.json</code> + <code>edit.npz</code> with sha256 hashes of base and edited tensors, so anyone with the public base model rebuilds the exact weights.</p>
<p>Decision models: <code>wsp_patch.write_checkpoint(...)</code> · LLMs: <code>dspy-wsp apply</code>, then serve on vLLM.</p>
<p style="margin-bottom:0">Runs locally: MLX on Apple silicon, PyTorch on Linux (NVIDIA GPU if present).</p>
</div>
<p class="note">Caveat: Cmpnd calls the package "very experimental." Under the paper's stricter rule, d1-omni-600M gained only +2.8.</p>
</div>
<div class="ft"><span>Sources: cmpnd.ai, github.com/cmpnd-ai/dspy-wsp, rikiyat.github.io</span><a href="https://www.marktechpost.com" target="_blank" rel="noopener">Built by Marktechpost</a></div>
</div>
<script>
(function(){
var R=document.getElementById('mtp-wsp');
function q(s){return R.querySelector(s)} function qa(s){return R.querySelectorAll(s)}
function post(){try{parent.postMessage({mtpWspH:R.offsetHeight+40},'*')}catch(e){}}
qa('.tab').forEach(function(t){t.onclick=function(){qa('.tab').forEach(function(x){x.classList.remove('on')});t.classList.add('on');qa('.pn').forEach(function(p){p.classList.toggle('on',p.dataset.p===t.dataset.t)});if(t.dataset.t==='3')drawBars(rc);setTimeout(post,60)}});
/* levers */
var wg=q('#wg');for(var i=0;i<64;i++){var c=document.createElement('i');wg.appendChild(c)}
var cells=wg.children;
var L=[
{p:1,w:0,t:'<b>Prompt optimization</b> (MIPROv2, GEPA) rewrites instructions and examples. Weights never move.',g:['Edits text','No GPU needed'],n:['Weights frozen']},
{p:0,w:1,t:'<b>Fine-tuning</b> (BootstrapFinetune) nudges many weights with gradient descent on training traces.',g:['Changes weights'],n:['Needs gradients','Needs a training loop']},
{p:0,w:2,t:'<b>Weight-space programming</b>: a frontier LLM reads tensors, forms a hypothesis about what they compute, writes code to patch a few, then tests the edit with a forward pass.',g:['Changes weights','No gradients','Targeted, hashed patch'],n:['Needs a strong writer LLM']}
];
function lever(k){qa('#levb .btn').forEach(function(b){b.classList.toggle('on',+b.dataset.l===k)});var d=L[k];
q('#bx-p').classList.toggle('hot',d.p===1);q('#bx-w').classList.toggle('hot',d.w>0);q('#pchg').className=d.p?'chg':'';
for(var i=0;i<cells.length;i++){cells[i].className=''}
if(d.w===1){var n=0;var iv=setInterval(function(){for(var j=0;j<cells.length;j++){cells[j].className=Math.random()<.7?'b':''}if(++n>5)clearInterval(iv)},140)}
if(d.w===2){[19,20,27,28].forEach(function(x,ix){setTimeout(function(){cells[x].className='a'},200+ix*180)})}
q('#ldesc').innerHTML='<p style="margin-top:0">'+d.t+'</p><div class="tags">'+d.g.map(function(x){return '<span class="tg">'+x+'</span>'}).join('')+d.n.map(function(x){return '<span class="tg n">'+x+'</span>'}).join('')+'</div>';setTimeout(post,60)}
qa('#levb .btn').forEach(function(b){b.onclick=function(){lever(+b.dataset.l)}});lever(2);
/* loop */
var S=[
{b:25,t:'<span class="k">load_decision_backend("d1")</span>\n# student weights load into a local Python process\n# writer: gpt-6-astra, reasoning_effort="max"'},
{b:25,t:'<span class="k">```python</span> # runs in sandbox (sandbox-exec / bubblewrap)\nW = weights["head.scorer.1.weight"]\nprint(W.shape, W.std()) # read tensors like source code'},
{b:25,t:'# writer turn = short explanation + 1 code block\n"These scorer units push answers toward the wrong option.\n I will rescale them and check on practice examples."'},
{b:25,t:'<span class="k">```python</span>\nW[rows] *= scale # targeted edit, no gradients\n# change is recorded against the base tensor hash'},
{b:24,t:'<span class="k">```forward</span> # run the DSPy program on practice examples\n# score on holdout (writer sees scores, never examples)\n# keep the edit only if the metric improves'},
{b:0,t:'# budget spent: best edit becomes the patch\npatch/manifest.json + patch/edit.npz (sha256 hashed)\n# hidden valset compares original vs edited weights once'}
];
var cur=0,pl=null;
function step(k){cur=Math.max(0,Math.min(5,k));qa('.st').forEach(function(s){var i=+s.dataset.s;s.classList.toggle('on',i===cur);s.classList.toggle('done',i<cur)});
q('#term').innerHTML=S[cur].t;q('#budf').style.width=(S[cur].b/25*100)+'%';q('#budn').textContent=S[cur].b+' / 25';
if(cur===4){var b=24;var iv=setInterval(function(){b-=1;if(cur!==4||b<1){clearInterval(iv);return}q('#budf').style.width=(b/25*100)+'%';q('#budn').textContent=b+' / 25'},90)}}
qa('.st').forEach(function(s){s.onclick=function(){step(+s.dataset.s)}});
q('#next').onclick=function(){step(cur+1)};q('#prev').onclick=function(){step(cur-1)};
q('#play').onclick=function(){if(pl){clearInterval(pl);pl=null;q('#play').textContent=' Auto-play';return}step(0);q('#play').textContent='❚❚ Pause';pl=setInterval(function(){if(cur>=5){clearInterval(pl);pl=null;q('#play').textContent=' Auto-play';return}step(cur+1)},2200)};
step(0);
/* edits */
var E=[
{t:'head.scorer.1.weight (+ bias, scorer.3.weight)',d:'Rewrote part of the decision head scorer: 112,640 of 1,048,576 entries (about 10.7%), plus 220 bias/output entries.',k:['112,860','74','78 min','$7.63'],m:'a',f:0.107},
{t:'scalar.weight',d:'A single small tensor of 1,024 entries on the Qwen3-0.6B backbone with a decision head.',k:['1,024','68','167 min','$6.92'],m:'a',f:1},
{t:'layers.23.feed_forward.w2.weight',d:'d1-2B has no decision head, so the writer edited the backbone: all 15.7M entries changed, as a rank-9 update.',k:['15.7M','65','83 min','$5.42'],m:'r',f:1}
];
var mat=q('#mat');for(var i=0;i<200;i++){mat.appendChild(document.createElement('i'))}
function ed(k){qa('#edb .btn').forEach(function(b){b.classList.toggle('on',+b.dataset.e===k)});var e=E[k];q('#edt').textContent=e.t;q('#edd').textContent=e.d;
['k1','k2','k3','k4'].forEach(function(id,ix){q('#'+id).textContent=e.k[ix]});
var ms=mat.children,n=ms.length;for(var i=0;i<n;i++)ms[i].className='';
var on=k===1?20:Math.round(n*e.f);var idx=[];for(var i=0;i<n;i++)idx.push(i);
if(k===0){idx=idx.slice(0,on)}else if(k===1){idx=idx.slice(0,20)}
idx.forEach(function(x,j){setTimeout(function(){ms[x].className=e.m},j*(k===2?3:12))});setTimeout(post,60)}
qa('#edb .btn').forEach(function(b){b.onclick=function(){ed(+b.dataset.e)}});ed(0);
/* bars */
var D=[[50.9,60.2,66.9,69.1],[39.2,50.7,52.4,56.4],[60.6,70.1,74.0,77.9],[68.8,70.3,70.7,75.3]];
var N=['Unoptimized','ReAnchor','WeightSpace','WeightSpace + ReAnchor'],C=['#B0AAA6','#5B5452','#3A8A50','#1E4A2C'];
var bars=q('#bars');N.forEach(function(n,i){bars.insertAdjacentHTML('beforeend','<div class="br"><span>'+n+'</span><div class="trk"><div class="fill" style="background:'+C[i]+'"></div></div><span class="v"></span></div>')});
var G=[[0,9.3,16.1,18.3],[0,11.6,13.3,17.3],[0,9.5,13.4,17.3],[0,1.5,1.9,6.5]];
var rc=0;
function drawBars(k){rc=k;qa('#rsb .btn').forEach(function(b){b.classList.toggle('on',+b.dataset.r===k)});var r=qa('#bars .br');
r.forEach(function(row,i){var v=D[k][i];var f=row.querySelector('.fill');f.style.width='0';var g=i?' <small>+'+G[k][i].toFixed(1)+'</small>':'';row.querySelector('.v').innerHTML=v.toFixed(1)+'%'+g;setTimeout(function(){f.style.width=(v/85*100)+'%'},60+i*120)})}
qa('#rsb .btn').forEach(function(b){b.onclick=function(){drawBars(+b.dataset.r)}});drawBars(0);
window.addEventListener('load',post);window.addEventListener('resize',post);setTimeout(post,300);
})();
</script>
</body></html>
">
How well does it work? Typed Decisions benchmark results
Cmpnd tested on Typed Decisions, a benchmark for typed probabilistic decisions. A model reads 1 piece of unstructured state and answers 5 typed questions at once. Each answer is a probability distribution. The test split has 400 cases and 2,000 decisions.
Each model got 25 forward passes from GPT-6-Astra. Gains are paired, with a standard error of ±0.7 to 1.4 points.
ReAnchor is an earlier Cmpnd optimizer. Decision models output probabilities, and thresholds turn those into answers. ReAnchor refits each question’s thresholds with no LLM calls. WeightSpace changes the model; ReAnchor recalibrates its output. The 2 stack well.
Three patterns stand out:
WeightSpace beat ReAnchor alone on every model shown. On d1-omni-600M, it added +16.1 versus +9.3.
The largest model gained least. The 9B Clef-Flash gained only +1.9 from WeightSpace alone.
The combination matters most at 9B. Clef-Flash jumped to +6.5 when both optimizers ran.
Does the writer model matter?
The answer is yes. With gpt-6.1-sol as the writer, WeightSpace alone gave +5.8 on d1-omni-600M, +12.1 on NanoJev and −0.6 on d1-2B. Astra produced +16.1, +13.3 and +13.4 on the same models.
Did dspy-wsp bend the original paper’s rules?
Slightly, and Cmpnd says so. By default, the writer can recompute the decision head inside its kernel. Setting simulate_head=False enforces the paper’s stricter rule. Under that rule, d1-omni-600M gained only +2.8 ± 0.7 points. Adding ReAnchor brought it to +9.3, no better than ReAnchor alone.
How do you deploy an edited model?
Each run writes a patch to run_dir. The patch holds manifest.json and edit.npz, with only the changed entries. It also stores sha256 hashes of every base and edited tensor. Anyone with the public base model can rebuild the edited weights exactly.
Text LLMs:dspy-wsp apply <base> <patch> <out>/, then serve with vLLM.
Programs:compiled.save("program.json") and reload with allow_unsafe_lm_state=True.
The edited model runs locally. On Apple silicon it uses MLX. On Linux it uses PyTorch, on an NVIDIA GPU if present.
What models does dspy-wsp support?
Backend
Model
Alias
Architecture
D1Backend
Liquid AI d1-omni (text path)
"d1"
Encoder with decision head
NanoJevBackend
NanoJev
"nanojev"
Qwen3 backbone with decision head
D1LMBackend
Liquid AI d1 on LFM3
"d1-2b"
LM answering at question positions
Text-generating LLMs work through VLLMBackend (NVIDIA), HFBackend (CUDA, MPS or CPU) and MLXBackend (Apple silicon). A GEPASearch option, contributed by Michael Isaac, adds population search for decision models.
How does WeightSpace compare with other DSPy optimizers?