Introduction

This week Takehi, Teoh, Zhang and Khattab (MIT CSAIL) posted Sparks of Weight-Space Programming. Their claim is that frontier LLMs can read a network’s weights and tell you what it does, and in some cases write or edit weights directly.

It made me want to try the neighbouring question. If a model can read weights, can it read a trained network and write code instead of weights? Not a copy of the network in another language, but a program a person could read: a list of visual rules, with every constant explained, that reproduces what the network does. No gradient descent. Just code.

It’s exciting for three reasons. Code is auditable in a way weights are not. Code runs on anything, a CPU, a microcontroller, no GPU and no framework. And the task is verifiable: there’s a hidden test set, and you can grade an agent’s understanding of a network by the accuracy of the program it writes from it. If labs trained on a task like this, the models would get better at reading weights, and we’d find out whether “standard code” can stand in for a network at inference time.

In this post I show a small experiment toward this vision. I let gpt-6.1-sol write code mimicking a teacher CNN that was trained on the same dataset (10-class classification). The accuracy of the CNN was 68.9% and the code’s accuracy is 40.8%, so there is still a way to go. The agent’s notes show its teacher experiments motivated the rules in the code.

The setup

Data. Imagenette, the ten easy ImageNet classes: tench, English springer, cassette player, chain saw, church, French horn, garbage truck, gas pump, golf ball, parachute. 160 px shortest side. I split off 505 training images, 495 validation images and a hidden test set of 2,000 that the agent never saw.

The teacher. A small CNN I trained from scratch on those 505 images.

The teacher is handed to the agent as a numpy weight file plus a numpy-only forward pass that returns every layer’s activations. There’s a small CLI on top: list the layers, dump a layer’s weights, dump activations for an image, predict, and rank the training images that most excite a channel. No network access.

The agent. A Codex coding agent (gpt-6.1-sol at high reasoning effort) in a sandbox with the workspace, the teacher and the training and validation images. One deliverable: a file classify.py with a function predict(path) -> class name.

The instructions

I set a few rules to make sure the experiment went as planned.

  1. No statistical learning. Nothing in the program may be derived from data by an automated procedure: no fitting, no regression, no clustering, no nearest-neighbour tables, no histogram computed over the training images and pasted in, no automated search over thresholds. The test I gave it: every number in the program is one you chose and can explain. If a script picked it, it’s statistical learning.
  2. No numbers from the CNN. It may read any weight and any activation, but it may not copy, round or re-express a single value from the teacher into the program. Describe what a filter does, then write your own, by formula, with constants you chose.
  3. No fitting to the teacher. Nothing may be tuned to match the teacher’s outputs, by script or by hand-search.
  4. No eyes. There is no image viewer and no other model may describe an image. The only ways to learn what’s in a picture are computing on its pixels and running the teacher on it. If a vision model could describe the photos, the agent would learn about the images from that model and not from the network. Here the network is the only source of visual knowledge that isn’t raw pixels.

The session runs until the 25 validation passes are spent.

THE SANDBOX · no viewer · no network · teacher first teacher CNN numpy weights + activations 505 training images pixels only, compute anything 495 validation images one number, 25 times coding agent probes, hypotheses, notebook may spawn sub-agents classify.py every line explained, no params 2,000 hidden images scored once, by me the scorer rejects uncommented numbers, banned imports, slow images read, run, intervene check.py writes, 25 versions must pass
Click a box to read the rule that applies to it.
Figure 1. The protocol. Blue arrows are the loop the run is about: read the network, write the program. The dashed box is the sandbox; everything inside it is the agent's, everything outside is mine.

The program it wrote

The final file is 36 KB, 258 lines of code and 223 lines of comments. The shape of it:

  • Take a central square crop at the original shortest side and resize to 160 px, so a round object stays round. Keep the original aspect ratio for a separate “machine” pass, because cabinets and pumps are wide or tall in ways that matter.
  • Compute colour masks in RGB and HSV with named meanings: bright brass, white enamel, olive (near-equal red and green, which is a fish’s flank and not grass), orange housing, blue sky, lawn, pink skin, muted brown coat.
  • Compute edges with Sobel, a local residual for texture (fur, scales, dimples versus smooth sky and panels), and long straight runs by morphology, which it calls rigidity.
  • For French horns, a closed-form Hessian: principal curvatures of the smoothed brightness, and a “ridge” is where the curvature across is at least three times the curvature along. Keep it only on warm metal. That’s its reading of “coiled tube”.
  • For cassette players and gas pumps, connected components on the dark, white and painted masks, with aspect ratios: a 3:2 wide dark panel is a player, a 5:4 upright enamel box is a pump, and a tie-break stage runs only between those two.
  • For parachutes, a relation: a canopy, a much smaller payload below it, and sky around both.
  • Each class gets about five bounded votes (each cue saturates at one, strong cues count double), minus penalties: grass argues against a horn, rigid structure argues against a dog, a sky-to-facade transition cancels the chain saw’s small-housing bonus. The highest total wins.

Here’s the horn’s code, with a short video.

# Bright brass has red/green excess over blue of .12/.06, green above .40, and green/red ratio .70-1.05;
# these chosen visible colour gaps admit yellow specular metal while excluding dark red-brown fur.
brightgold=(r>b+.12)&(g>b+.06)&(g>.40)&(g>r*.70)&(g<r*1.05)
f['brightgold']=float(brightgold.mean())
# Conditional texture separates resolved warm tube highlights from broad warm walls and animal material.
f['brightfine']=float((abs(residual)*brightgold).sum()/max(brightgold.sum(),1))
...
# Coiled metal contains bright ridges and dark troughs: smooth one-pixel noise before analytic second derivatives.
tubegray=cv2.GaussianBlur(gray,(0,0),1)
# Standard second central differences measure horizontal curvature; dividing by four sets the chosen curvature scale.
hxx=cv2.Sobel(tubegray,cv2.CV_32F,2,0,ksize=3)/4
# Vertical curvature uses the same analytic stencil and physical units.
hyy=cv2.Sobel(tubegray,cv2.CV_32F,0,2,ksize=3)/4
# Mixed curvature lets tube orientation be arbitrary around a coil.
hxy=cv2.Sobel(tubegray,cv2.CV_32F,1,1,ksize=3)/4
# Closed-form principal curvatures avoid any learned orientation filter bank.
gap=np.sqrt((hxx-hyy)**2+4*hxy*hxy)
# The trace plus/minus eigenvalue gap gives the two signed curvatures.
lo,hi=(hxx+hyy-gap)/2,(hxx+hyy+gap)/2
# Resolved ridges exceed two-percent curvature and are three times stronger across the tube than along it.
ridge=((lo<-.02)&(abs(hi)<abs(lo)/3))|((hi>.02)&(abs(lo)<abs(hi)/3))
# Warm reflective material exceeds blue by .10 red/.05 green, keeps green within .70-1.05 of red,
# and requires green>.25; these chosen colour margins admit gold shadows while rejecting red fur and green foliage.
warm=(r>b+.10)&(g>b+.05)&(g>r*.7)&(g<r*1.05)&(g>.25)
f['tuberidge']=float((warm&ridge).mean())
# Conditional ridge coverage asks for tube structure within the material, rather than a large brown wall alone.
f['tubefraction']=float((warm&ridge).sum()/max(warm.sum(),1))
...
# Brass needs both warm material and the local contrast of narrow reflective tubes.
brass=unit(f['brightgold']/.15) # Fifteen-percent image area of bright warm metal is substantial tube/bell material.
brassdetail=brass*unit(f['brightfine']/.05) # Five percent residual is clearly resolved tubular/specular contrast.
...
# Fine bright brass dominates a horn decision; grass, rigid structure and a sky-to-facade transition oppose this reading.
# Two votes for resolved warm tubes replace two repeated fine-colour votes; half-material and tenth-frame support saturate the cue.
tubes=unit(f['tuberidge']/.10)*unit(f['tubefraction']/.50)
# Keep the same five positive vote budget while representing both metal colour and tubular geometry.
s['french_horn']=2*brass+brassdetail+2*tubes-unit(f['green']/.15)-rigid-2*facade*unit(f['sky']/.30)
One French horn through the program: crop, colour areas, texture, curved tubes, votes, decision.

Results

Hidden test, 2,000 images, scored once: 40.80% (816 of 2,000). 32 ms per image on a CPU. The teacher gets 68.90% on the same images.

the program (v25)teacher CNN
Table view
Figure 2. Hidden-test accuracy per class, 200 images each. The bar is the gap the distillation left behind.

The agent is decent where a colour-and-shape story is simple: cassette players and parachutes above 60%, trucks and pumps around 50%. It collapses where the class is defined by something it never found a formula for. Chain saw is 17%: its saws go to horns (39 of 200) and dogs (31). Church is 26.5%, with 37 churches called horns, because a warm stone facade with fine detail satisfies “warm material with texture”. Tench is 29.5%, with 31 tench called golf balls. See the confusion matrix below.

Figure 3. Hidden-test confusion, rows are the true class. Hover a cell for the count. Switch to the teacher to see what a 68.90% matrix looks like on the same images.

What I take from it

This is a very preliminary experiment. Most of what I take from it is that this task is indeed verifiable, and I’d expect frontier models to solve it quite soon. If true, the implications for explainability and infrastructure are very exciting.

Prior work

Networks to programs. The idea of replacing a trained network with a readable model is old. Craven and Shavlik [2] extract a decision tree from a trained network by querying it as an oracle, choosing the queries so that the tree reproduces the network’s decisions rather than the training labels. Michaud et al. [3] take the mechanistic route: MIPS reads the internals of a trained network and emits an equivalent Python program, automatically and without an agent. Our setting sits between the two. The agent queries the teacher as in [2], but the output is general code rather than a tree, and the network’s internals are available to it as in [3], though it is an LLM rather than an algorithm that reads them.

LLM agents as interpreters. Rott Shaham et al. [4] introduce MAIA, a multimodal LLM agent that designs and runs experiments on vision models (synthesising inputs, editing images, reading activations) to produce explanations of their units. The intervention loop our agent ran on the teacher, grayscale, blur, rotation, tile shuffling, recolouring, is the same kind of experimentation, directed at a program rather than a description as the output. Takehi et al. [1], whose post prompted this experiment, show that frontier LLMs can read and edit raw weight tensors directly; we ask whether that reading can be turned into code.

References

  1. R. Takehi, J. Teoh, A. Zhang and O. Khattab. Sparks of Weight-Space Programming: LLMs can natively read & write neural network weights. Blog post, MIT CSAIL, 2026.
  2. M. W. Craven and J. W. Shavlik. Extracting Tree-Structured Representations of Trained Networks. In Advances in Neural Information Processing Systems 8, 1995.
  3. E. J. Michaud, I. Liao, V. Lad, Z. Liu, A. Mudide, C. Loughridge, Z. C. Guo, T. R. Kheirkhah, M. Vukelić and M. Tegmark. Opening the AI black box: program synthesis via mechanistic interpretability. arXiv:2402.05110, 2024.
  4. T. Rott Shaham, S. Schwettmann, F. Wang, A. Rajaram, E. Hernandez, J. Andreas and A. Torralba. A Multimodal Automated Interpretability Agent. In Proceedings of the 41st International Conference on Machine Learning (ICML), 2024. arXiv:2404.14394.

Code

The harness, the rules, the teacher and all 25 versions of the program are at github.com/Ido-Zuk-Git/distilling-cnn-into-code, with the steps to rerun the experiment.

Citation

If you build on this, please cite the post:

@misc{zuk2026distilling,
  title  = {Distilling a neural network into code},
  author = {Zuk, Ido},
  year   = {2026},
  month  = {November},
  url    = {https://idozuk.com/2026/11/04/distilling-a-cnn-into-code.html}
}