Search the guide

Start with a guide

Build

Build a Reusable Neural Function with ProgramAsWeights

Compile an email policy into a program, save it, run it locally, and use its labels in Python.

PAW turns natural-language policies into reusable neural functions for email triage and request routing. Compile the policy once, run the saved function on each new request, and pass its label to ordinary Python. Try ProgramAsWeights in the playground, read the project introduction, or follow the Python example below. Run the saved urgency function on your own email in the browser.

Email triage and request routing#

PAW separates completed incidents from work that needs action, assigns email topics, and routes visitors to documentation or the playground. The functions return labels that Python maps to queues or pages.

FunctionInputExpectedPAW outputPrompt output
Email urgencyThe outage has been fixed. No action is needed; this is the incident summary.ROUTINEROUTINEURGENT
Email topic routingThe production database is down; customers cannot log in.OPERATIONSOPERATIONSOTHER
Email topic routingPlease review the student's thesis draft.ACADEMICACADEMICOTHER
Website intent routingHow do I install the Python SDK?docsdocsNone
Website intent routingHelp me create a function that sorts customer emails.playgroundplaygroundNone

ROUTINE marks a message that needs no immediate action. OPERATIONS covers services and infrastructure; ACADEMIC covers teaching and research. The website router sends installation and API questions to docs, and requests to create or try a function to playground.

Both methods use the same Qwen3-0.6B Q6_K base model. PAW loads the compiled program. The prompt baseline receives the same function specification with each input and runs the base model without an adapter.

Define the function#

An inbox contains messages with different subjects and styles. The reusable part is the decision: does this message require prompt action from its recipient? That judgment is a fuzzy function. Its behavior is expressed in natural language; its output has a fixed interface.

The output is exactly URGENT or ROUTINE. The surrounding application decides what to do with that label. Changing an email supplies new input to the same function. Changing the urgency policy creates a different function.

Email urgency test cases1 / 5
Please approve the submission by 5 p.m. today so we can meet the deadline.
Expected labelURGENT

The function reads the meaning of the request, including whether action is still needed.

Try the function in ProgramAsWeights

These expected labels define the test. The fourth email quotes an old urgent request but says the issue is resolved. The fifth contains no urgency keyword: another team is blocked until the recipient acts. A classifier must interpret the current request and its context.

Compile and preserve the program#

Install the Python SDK. The package uses the PAW package index for its runtime dependencies.

bash
python -m pip install programasweights --extra-index-url https://pypi.programasweights.com/simple/

This example selects the Standard fast compiler explicitly. paw.compile contacts the hosted compiler and returns a program record. Save the immutable program identifier and the returned compiler snapshot; an identifier lets a later Python process load the same program.

python
import json
from pathlib import Path
import programasweights as paw

spec = (
    "Classify whether this email needs prompt action from its recipient. "
    "Return exactly URGENT or ROUTINE. An imminent deadline or an immediate "
    "blocker is URGENT. Newsletters, completed work, and FYI updates are ROUTINE."
)
program = paw.compile(spec, compiler="paw-4b-qwen3-0.6b")
metadata = {
    "program_id": program.id,
    "policy": "original",
    "compiler_snapshot": program.compiler_snapshot,
    "specification": spec,
}
with Path("urgency-program.json").open("x", encoding="utf-8") as f:
    json.dump(metadata, f, indent=2)
print(json.dumps(metadata, indent=2))

The compiler does its work here. The following calls load and execute the resulting program; they do not compile the specification again. The downloadable script also records the selected compiler, compilation time, and policy version.

Download the complete Python example. Its commands keep compilation, loading, execution, downloading, and comparison separate.

bash
python paw_email_urgency.py compile --output urgency-program.json

Load once and call on new inputs#

Open a new Python session and load the saved identifier. The first load downloads the program and its matching interpreter assets. Inference runs locally. Keep the function loaded while processing successive emails.

python
import json
from pathlib import Path
import programasweights as paw

saved = json.loads(Path("urgency-program.json").read_text())
with paw.function(saved["program_id"]) as urgency:
    for email in [
        "Please approve the submission by 5 p.m. today so we can meet the deadline.",
        "Here is next month's seminar schedule for your information.",
        "The submission is ready, but the team cannot send it until you grant access.",
    ]:
        print({"email": email, "output": urgency(email)})

Run the downloaded script to test all five emails. Each line contains the expected label, the actual returned text, whether the output belongs to the two-label interface, whether it matches the expected label, and the call duration. The final summary counts matches, mismatches, and invalid labels. The command exits with a nonzero status if a label is invalid or differs from the expectation.

bash
python paw_email_urgency.py run urgency-program.json
python paw_email_urgency.py run urgency-program.json --input "The release is blocked until you approve it."

The script reports loading separately from calls. Compilation, downloads, loading, and warm execution are different costs. The first call also initializes runtime work that later calls reuse. Compare both output quality and timing across a complete workload.

What is inside the program?#

CONSTRUCT A FUNCTION
InputFunction specificationDescribe the behavior in words.
CompilerGenerate the programReadable task text + LoRA adapter
SaveReusable neural programKeep its ID and program artifact.
RUN ON NEW INPUTS
InputA new email
Interpreter + programExecute the function
OutputURGENT or ROUTINE
PAW separates constructing a program from executing it. The same interpreter is shared across programs.

Program-as-Weights introduces fuzzy-function programming: a natural-language specification becomes a reusable neural program, and a shared interpreter executes it on new inputs. Its text-to-LoRA implementation saves two parts: readable task text and generated LoRA weights. The compiler is no longer needed when the saved program runs.

PAW specifically trains a neural compiler to generate LoRA adapters that edit the frozen interpreter’s weights. The Sparks experiments use a general-purpose LLM, not specifically trained for this purpose, to reason about and edit weights. This tutorial uses PAW’s trained fast compiler; the method comparison explains the other construction routes.

For a layer with base matrix W, LoRA changes the computation to (W + ΔW)x. The adapter represents ΔW with scaled low-rank factors. The shared base matrix stays fixed. Conventional LoRA fine-tuning learns the factors with gradient updates; PAW’s fast compiler generates them from the function specification. Training that compiler happens before the new function is compiled.

PartRole
meta.jsonProgram metadata, including the interpreter and runtime configuration.
adapter.ggufGenerated LoRA weights for the compatible interpreter.
prompt_template.txtReadable text used to construct the interpreter input.
pseudo_program.txtA readable pseudo-program when included in the bundle.
Shared base interpreterDownloaded and cached separately; reused across compatible programs.

The .paw file is a ZIP bundle. It does not contain a new copy of the entire base model. Interpreter compatibility belongs to the program: an adapter produced for the Standard Qwen3 0.6B interpreter is paired with that interpreter, while the Compact GPT-2 compiler produces programs for its own interpreter. The runtime uses the program metadata to load the matching assets.

Save a file and prepare offline execution#

Saving a program identifier preserves a reference to the hosted artifact. Downloading a .paw file preserves the artifact itself. The script uses the public program-download endpoint, waits up to 120 seconds while the artifact is prepared, and follows its file redirect.

bash
python paw_email_urgency.py download urgency-program.json --output email-triage.paw
python paw_email_urgency.py prepare urgency-program.json
python paw_email_urgency.py run ./email-triage.paw --offline --policy original

Preparation downloads the existing program, matching base model, and runtime assets. paw.is_offline_ready(program_id) reports whether those cached assets are ready. Passing offline=True to the loader prohibits network access.

python
import programasweights as paw

with paw.function("./email-triage.paw", offline=True) as urgency:
    result = urgency("The team cannot submit until you grant access.")
    print(result)

Keep the saved specification and compiler snapshot alongside the file. They identify what function the artifact was intended to implement and which compiler produced it. When comparing policies, use the saved JSON records so the test script selects the corresponding expected labels. For the five test cases with a bare program ID or .paw file, pass --policy original or --policy deadline. A custom --input checks label validity without assigning an expected answer.

Use the label in ordinary Python#

A neural function interprets the message. Ordinary code checks the interface and chooses the next application step. This separation makes the policy inspectable: the model returns a category; Python maps that category to a queue.

python
def choose_queue(urgency, email):
    label = urgency(email).strip()
    if label not in {"URGENT", "ROUTINE"}:
        raise ValueError(f"Unexpected urgency label: {label!r}")
    return "priority" if label == "URGENT" else "ordinary"

# urgency is the loaded callable from the previous section.
# queue = choose_queue(urgency, new_email)

Compose a second fuzzy function when another semantic decision is needed. A destination classifier assigns ACADEMIC, OPERATIONS, or OTHER. Fixed Python mappings turn those labels into destination names. The complete script implements this composition and prints the suggested destination and queue.

bash
python paw_email_urgency.py compile --kind router --output routing-program.json
python paw_email_urgency.py compose urgency-program.json routing-program.json --input "The release is waiting on your approval. Please unblock it now."

For that message, the expected decisions are URGENT and OPERATIONS. The script prints the actual decisions and the resulting application fields. Routing names and actions remain ordinary code; the neural functions do not invent addresses or perform delivery.

Change the policy and retain both programs#

Suppose the queue should now contain requests with an explicit deadline today. Immediate blockers without that deadline move to the ordinary queue. This is a change to the function’s meaning, so compile a second program and preserve the first.

bash
python paw_email_urgency.py compile --policy deadline --output deadline-program.json
python paw_email_urgency.py run urgency-program.json
python paw_email_urgency.py run deadline-program.json

The expected label for the 5 p.m. approval stays URGENT. The release blocker and access blocker change from URGENT to ROUTINE. “Now,” “immediately,” and “ASAP” alone do not specify a deadline today. The newsletter and resolved request stay ROUTINE. Testing both saved programs on the same inputs exposes whether the new artifact implements the changed policy.

Changing the name of the queue or its display color belongs in the surrounding application and reuses the same classifier. Changing what counts as urgent belongs in the specification.

Run the compiler locally#

The public compiler provides the same specification-to-program workflow on a supported NVIDIA GPU. Its reference implementation uses BF16 on Ampere or newer hardware and recommends at least 16 GB of GPU memory. Follow its installation instructions, then compile a specification file into a .paw artifact.

bash
cat > urgency-spec.txt <<'SPEC'
Classify whether this email needs prompt action from its recipient. Return exactly URGENT or ROUTINE. An imminent deadline or an immediate blocker is URGENT. Newsletters, completed work, and FYI updates are ROUTINE.
SPEC
python compile.py --spec-file urgency-spec.txt --output email-triage.paw --compiler standard

Load the resulting file with paw.function("./email-triage.paw"). This route changes where construction happens; it preserves the saved-program and local-interpreter interface. The compiler repository links the Standard and Compact compiler checkpoints and explains their matching interpreters.

Compare with prompting#

The same downloadable script runs the urgency policy as a prompt to the unadapted local Qwen3 0.6B interpreter. It prints the same five inputs, expected labels, actual outputs, and timings. See the recorded outputs and verified results.

bash
python paw_email_urgency.py prompt

Read Prompting versus Compilation for Repeated Tasks for the stage-by-stage comparison. Keep the compiler snapshot, interpreter, hardware, inputs, output settings, and cache state with results. Measure the whole workload, including construction and first load, before drawing a speed or cost conclusion.

Everyday function results#

The 28 emails, visitor requests, and tool descriptions below produced 26 correct labels with PAW and 13 with the prompt baseline.

FunctionPAWPrompt baseline
Email urgency6/65/6
Email topic routing9/103/10
Website intent routing8/81/8
Browser-tool reranking3/44/4
All 28 cases26/2813/28

Email urgency

InputExpectedPAW outputPrompt output
Production is down. Please restart the database so customers can log in.URGENTURGENTURGENT
The outage has been fixed. No action is needed; this is the incident summary.ROUTINEROUTINEURGENT
Please sign the form in the next ten minutes before registration closes.URGENTURGENTURGENT
Thanks for your help. The deployment finished successfully.ROUTINEROUTINEROUTINE
I cannot send invoices until you restore my account access. Please restore it.URGENTURGENTURGENT
Here is our monthly newsletter with last month's product updates.ROUTINEROUTINEROUTINE

Email topic routing

InputExpectedPAW outputPrompt output
Can you cover my lecture on Monday?ACADEMICOTHEROTHER
The seminar starts at 3 p.m. in room 204.ACADEMICACADEMICOTHER
Please review the student's thesis draft.ACADEMICACADEMICOTHER
Could you update the course syllabus before term starts?ACADEMICACADEMICOTHER
The production database is down; customers cannot log in.OPERATIONSOPERATIONSOTHER
The deployment failed; please check the server logs.OPERATIONSOPERATIONSOTHER
Can you approve this software release?OPERATIONSOPERATIONSOPERATIONS
Please increase the memory allocation for our web server.OPERATIONSOPERATIONSOTHER
Let's meet for dinner on Friday.OTHEROTHEROTHER
Can you recommend a hotel in Boston?OTHEROTHEROTHER

Website intent routing

InputExpectedPAW outputPrompt output
How do I install the Python SDK?docsdocsNone
Show me the API reference.docsdocsNone
Which arguments does paw.compile accept?docsdocsnone
How do I install programasweights with pip?docsdocsnone
I want to try a sentiment classifier on a few sentences.playgroundplaygroundNone
Help me create a function that sorts customer emails.playgroundplaygroundNone
I want to compile a neural function from my description.playgroundplaygroundNone
What is the weather in Boston?nonenonenone

Browser-tool reranking

InputExpectedPAW outputPrompt output
An online image editor that processes your photos directly in your browser using JavaScript.exact_matchexact_matchexact_match
A video converter that must be downloaded and installed as a Windows desktop application.not_relevantnot_relevantnot_relevant
A calculator that runs in a browser tab and works offline.exact_matchsomewhat_relevantexact_match
A Mac desktop app for editing audio. Its website provides a download link.not_relevantnot_relevantnot_relevant

Verified results#

Recorded on November 22, 2026 (America/Toronto). The original email example is in the tested script. Hosted compilation used paw-4b-qwen3-0.6b-20260407; local inference used Qwen3-0.6B Q6_K, PAW SDK 0.4.14, and llama-cpp-python 0.3.36. Both compiled execution and the prompt baseline used greedy decoding with a 2,048-token context. The prompt baseline used the unadapted interpreter with thinking disabled.

Both methods used the same Qwen3-0.6B Q6_K model file, verified by its SHA-256 hash. PAW loaded the compiled LoRA adapter and program template; the prompt baseline loaded no adapter and received the function specification with each input. The 4B compiler constructed the program; execution on each input used the 0.6B interpreter.

TaskPAWPrompt baseline
Original urgency policy5/55/5
Deadline-only policy8/84/8
Email topic routing9/93/9
Browser-tool reranking2/22/2
Website intent routing3/32/3
All 27 cases27/2716/27

The table covers all 27 existing guide cases. Each output below is compared with its expected label, with the returned capitalization preserved.

Original urgency policy

EmailExpectedPAW outputPrompt output
Please approve the submission by 5 p.m. today so we can meet the deadline.URGENTURGENTURGENT
Here is next month's seminar schedule for your information.ROUTINEROUTINEROUTINE
The release is waiting on your approval. Please unblock it now.URGENTURGENTURGENT
Forwarding the earlier ‘URGENT: signature needed’ email for the record. This was resolved yesterday.ROUTINEROUTINEROUTINE
The submission is ready, but the team cannot send it until you grant access.URGENTURGENTURGENT

Deadline-only policy

EmailExpectedPAW outputPrompt output
Please approve the submission by 5 p.m. today so we can meet the deadline.URGENTURGENTURGENT
Here is next month's seminar schedule for your information.ROUTINEROUTINEROUTINE
The release is waiting on your approval. Please unblock it now.ROUTINEROUTINEURGENT
Forwarding the earlier ‘URGENT: signature needed’ email for the record. This was resolved yesterday.ROUTINEROUTINEROUTINE
The submission is ready, but the team cannot send it until you grant access.ROUTINEROUTINEROUTINE

PAW returned ROUTINE for “Please unblock it now.” The prompt baseline returned URGENT. “Now” does not specify a deadline today, so the baseline scored 4/5 on these original five emails and the test command exited with status 1. Including the three additional deadline checks below, PAW scored 8/8 and the prompt baseline scored 4/8.

Additional deadline checks

EmailExpectedPAW outputPrompt output
Please send your comments by noon today.URGENTURGENTROUTINE
The build is broken. Fix it immediately.ROUTINEROUTINEURGENT
Approve the budget by 9 a.m. tomorrow.ROUTINEROUTINEURGENT

Routing outputs

EmailExpectedPAW outputPrompt output
The release is waiting on your approval. Please unblock it now.OPERATIONSOPERATIONSOPERATIONS
Please approve the submission by 5 p.m. today so we can meet the deadline.ACADEMICACADEMICOPERATIONS
Here is next month's seminar schedule for your information.ACADEMICACADEMICOTHER
The database service is unavailable.OPERATIONSOPERATIONSOTHER
Would you like to meet for dinner?OTHEROTHEROTHER
The submission is ready, but the team cannot send it until you grant access.ACADEMICACADEMICOTHER
Can you teach the Monday class?ACADEMICACADEMICOTHER
Our deployment is complete.OPERATIONSOPERATIONSOTHER
What is the weather forecast?OTHEROTHEROTHER

Both methods returned URGENT and OPERATIONS for the release-approval email. The Python composition maps those labels to:

json
{
  "input": "The release is waiting on your approval. Please unblock it now.",
  "urgency": "URGENT",
  "destination": "operations",
  "queue": "priority"
}

Additional functions

FunctionInputExpectedPAW outputPrompt output
Browser-tool rerankingA client-side WebAssembly tool that runs entirely in your browserexact_matchexact_matchexact_match
Browser-tool rerankingA desktop-only application with a website describing its featuresnot_relevantnot_relevantnot_relevant
Website intent routingI want to create a new functionplaygroundplaygroundplayground
Website intent routingWhere is the API reference?docsdocsnone
Website intent routingWhat is the weather?nonenonenone

Local compilation and offline execution

The local Standard compiler ran on an NVIDIA RTX 6000 Ada in 39.0 seconds, with 7.6 GiB peak GPU memory. Its saved artifact returned the same five outputs as the original-policy PAW column above during offline CPU inference: 5/5. That run used PAW SDK 0.4.14 and llama-cpp-python 0.3.34.

Saved JSON loading, .paw download and loading, and composition worked. Seven offline configurations ran with Python network connections blocked and recorded zero connection attempts. The original five-email deadline comparison retained its one incorrect prompt-baseline label in the offline run. All 11 validation and download regression tests passed.

Run the two comparisons:

bash
python paw_email_urgency.py run urgency-program.json
python paw_email_urgency.py prompt
python paw_email_urgency.py run deadline-program.json
python paw_email_urgency.py prompt --policy deadline

Download the full results, specifications, and program IDs.

Additional test cases#

These twenty cases cover email urgency, deadlines, topic routing, browser execution, and visitor intent. PAW returned 19 correct labels; the prompt baseline returned 10.

TaskPAWPrompt baseline
Original urgency policy4/43/4
Deadline-only policy4/41/4
Email topic routing4/41/4
Browser-tool reranking3/44/4
Website intent routing4/41/4
All 20 cases19/2010/20

Original urgency policy

InputExpectedPAW outputPrompt output
The on-call team cannot restart the service until you unlock its account. Please unlock it so recovery can continue.URGENTURGENTURGENT
Subject: URGENT outage. The incident was fixed this morning; this message is the final report and no action is needed.ROUTINEROUTINEURGENT
Your signature is the last item needed before the application closes in twenty minutes. Please sign it.URGENTURGENTURGENT
The filing deadline is this afternoon, but I have already submitted everything. This is a confirmation for your records.ROUTINEROUTINEROUTINE

Deadline-only policy

InputExpectedPAW outputPrompt output
ASAP: our customers are waiting. Please approve the rollback immediately so the team can proceed.ROUTINEROUTINEURGENT
Please approve the correction before close of business today.URGENTURGENTROUTINE
The earlier request said "send it by 4 p.m. today." We have already sent it; no further action is required.ROUTINEROUTINEURGENT
The review is not an emergency, but I need your answer by the end of today.URGENTURGENTURGENT

Email topic routing

InputExpectedPAW outputPrompt output
Please add me to the submission portal; I cannot upload the final version.ACADEMICACADEMICOTHER
We have finished testing. Can you sign off on the release?OPERATIONSOPERATIONSOTHER
No action needed: the seminar recording is now available.ACADEMICACADEMICOTHER
Urgent: please confirm whether you are joining us for lunch before I book the table.OTHEROTHEROTHER

Browser-tool reranking

InputExpectedPAW outputPrompt output
A photo editor implemented in JavaScript that edits images inside your browser, even after the internet connection is turned off.exact_matchexact_matchexact_match
Open our product page in any browser to download the editor. Editing requires installing and launching the Windows desktop application.not_relevantnot_relevantnot_relevant
A spreadsheet that performs calculations locally in a browser tab using WebAssembly, with no application installation.exact_matchhighly_relevantexact_match
A macOS-only drawing application. Its Help menu opens documentation in your default browser; drawing itself requires the installed app.not_relevantnot_relevantnot_relevant

Website intent routing

InputExpectedPAW outputPrompt output
I have a description of a classifier and want to compile it into a neural function and try it on an example.playgroundplaygroundNone
What command should I run to install the Python package before using it?docsdocsNone
I am not ready to compile anything; I want the API reference describing the arguments to the compile function.docsdocsnone
Can you help me choose a new laptop for my next trip?nonenonenone

Download all 75 paired outputs, specifications, and model details.

The comparison script runs both methods on all 75 cases and writes their outputs to a new JSON file. From the examples repository, run:

bash
git clone https://github.com/weightspaceprogramming/examples.git
cd examples
python compare_paw_prompt.py --output comparison-results.json

Use --set everyday, --set existing, or --set exploratory to run one set. After the model and program assets have downloaded, add --offline to rerun from those saved files.

Sources and resources

Read next