A local-first research workbench and supervised autonomy platform for inspecting, tracing, causally intervening on, editing, evaluating, and exporting open-weights neural networks.
Status: v1.0 Complete (Phases 0–10 / Milestones M1–M7 complete). All 36 roadmap slices in ROADMAP.md are implemented and verified across 1,164 deterministic T1 tests and 18 real-API Playwright E2E browser tests on Windows and Linux. See ARCHITECTURE.md for the complete as-built architecture and slice-by-slice changelog, docs/user-guide.md for concepts and tutorials, docs/notebook-client.md for the Python scripting client, and LICENSE.md for the WeightForge Research and Collaboration Licence v2.0.
| Domain | Implemented Capabilities | Documentation |
|---|---|---|
| 1. Model Runtime & Quantisation | Loads real GPT-2, Llama, and Qwen2 causal LMs with local tokenizers in float32, float16, bfloat16, or symmetric per-row 8bit / 4bit packed weight + fp32 scale quantisation. One model_id owns one live nn.Module shared across inspection, tracing, interventions, weight edits, and evaluation. |
docs/runtime.md, docs/live-weights.md |
| 2. Structure & Spectral Inspection | Separate Module Tree (virtualised, with canonical adapter hook mappings) and Parameter Table (with owner modules and tied-weight alias resolution). UniversalTensorAnalyzer computes norms, sparsity, outliers, 16-bin value histograms, bucketed row/col L2 norm heatmaps, active patched-coordinate overlays, and default torch.svd_lowrank truncated SVD (exact_svd=True opt-in). |
docs/model-structure.md |
| 3. Activation Tracing & Logit Lens | Batched, masked per-token activation captures at canonical pre/post hooks (embed, blocks[i].resid_pre, blocks[i].attn.out, blocks[i].mlp.out, blocks[i].resid_post, ln_final, unembed), architecture-exact final-normalised logit lens, and SHA-256-verified on-disk safetensors activation snapshots. |
docs/real-tracing.md |
| 4. Causal Interventions & Sweeps | Zero, reference-mean, and seeded-resample ablation; position-aligned clean→corrupt activation patching (position_map, no silent truncation); directional steering (α·v from provided vectors, stored vector_ids, or difference-of-means); scalar scaling; full-vocabulary KL divergence; and 256-cell layer × position sweeps. |
docs/real-interventions.md |
| 5. Reversible Weight Editing & Checkpoint Saving | N-D sparse_edit, row_edit, column_edit, scalar_scale, and low_rank_update (inline or streamed safetensors factor uploads). Post-cast fp64 budgets (max_delta_l2, max_delta_linf, max_touched_elements, max_relative_norm), dry-run previews, quantised target-copy re-quantisation (requantised: true, quantisation_error_l2), disjoint middle-patch revert, R1 stored-value replay, durable journals, and verified merged/delta safetensors checkpoint saving. |
docs/edit-operations.md, docs/patch-stacks.md, docs/patch-persistence.md, docs/checkpoint-saving.md |
| 6. Datasets, Evaluation & Statistical Controls | Streamed JSONL dataset registry with SHA-256 deduplication and private group/relation metadata. Versioned EvaluationProtocol measuring greedy accuracy, choice log-prob, target log-prob, logit difference, and LM perplexity. Isolated-worker controlled comparisons (baseline, random_subspace, shuffle, no_op) with cluster-preserving bootstrap CIs, paired sign-flip p-values, and Holm-Bonferroni multiplicity adjustment. |
docs/datasets.md, docs/evaluation.md, docs/controlled-evaluation.md |
| 7. Off-Target Regression & Contamination Gates | 4–5 check preservation suites (general_lm perplexity, neighbourhood, 2–3 unrelated tasks) that block publication (scientific_gate_passed: false) on collateral degradation. Frozen confirmatory protocols (POST /evaluations/protocols/freeze), cross-split group_id leakage detection, atomic SQLite locked-test exposure caps (BEGIN IMMEDIATE), and schema-allowlist output projection (BenchmarkLeakageGuard.project_response). |
docs/off-target-regression.md, docs/contamination-controls.md |
| 8. Experiment DAG & Reproducible Catalog v2 | Unified ExperimentService layer (scratch-{model_id} or explicit session) backed by Alembic-managed SQLite DAG tables with automatic branching on patch revert and bounded 64-cell ExperimentSpec matrices. Verified catalog registration from passed regression gates, portable .wfpatch zip export/import (with zip-slip, pickle, and zip-bomb guards), R1–R4 replay verification, and separate unverified experiment archives. |
docs/unified-services.md, docs/experiment-dag.md, docs/catalog-v2.md |
| 9. Workbench v2 UI | Dark/light design tokens, Cmd/Ctrl+K command palette, provenance toasts (state_id + content_digest), resizable explorer pane layouts, virtualised module tree, log-scale SVD & norm heatmaps, per-token L2 heat strips, logit-lens grids, interactive sweep drill-down, steering sliders, L2 budget meters, candidate-vs-control forest plots, branching DAG inspector, and .wfpatch browser. |
frontend/src/ |
| 10. Supervised Autonomy & MCP Server | 24 typed tools generated from service-layer Pydantic models (GET /api/v1/agent/tools) and a JSON-RPC 2.0 MCP server over stdio (weightforge mcp) and HTTP (POST /api/v1/mcp). Atomic preflight budget reservations (tool_calls, tokens, forward_passes, sequences, input_tokens, evaluation_calls, candidate_attempts, wall_clock_seconds, gpu_seconds), dispatch-enforced evidence_policy (weights_only, attention_only, activation_access, output_access), single-use state-bound human approvals, provider-agnostic ResearchAgentRunner (gemini, local, scripted_mock), live SSE streaming, and a planted-answer evaluation harness. |
docs/security/threat-model.md |
| 11. Memory Manager, GGUF/Ollama Export & Python Client | HardwareMemoryGuard keyed by (model_id, tensor) with enforced RAM/VRAM ceilings (409 Conflict admission with MB estimates), OrderedDict LRU cache eviction, and pinned disk artifact retention. Real GGUF v3 (F32, F16, Q8_0) and Ollama .Modelfile export (POST /api/v1/models/export) with R2/R3 runtime parity verification, plus the weightforge.client (WeightForgeClient) Python package. |
docs/notebook-client.md |
| 12. Frontier Research Features (Phase 9) | One-backward-pass attribution patching (/attribution), closed-form ridge linear probes with steering-vector export (/probes/train), sparse autoencoders (/saes, /saes/decompose, /saes/intervene), ROME/MEMIT rank-one model editing (/rome), task arithmetic (/task-arithmetic), circuit graph construction (/circuits), and checkpoint comparison + R1 selective restoration (/compare-checkpoints, /selective-restore). |
docs/user-guide.md |
- Legacy synthetic benchmark runner stays retired (
501):POST /api/v1/benchmarks/run(the original generator's fake weight-norm formula) remains permanently retired with501 Not Implemented. Use/api/v1/evaluations/run,/api/v1/evaluations/comparisons/run,/api/v1/evaluations/regressions/run, and/api/v1/evaluations/final/runfor real dataset evaluations. - Separate opt-in toy lab:
POST /api/v1/activations/traceand/api/v1/activations/interveneaccept onlymodel_id="toy"and label resultsexecution_kind="toy_demo". All real model tracing and interventions run through/api/v1/models/{model_id}/*. - Scientific claims: WeightForge distinguishes bitwise weight identity (R1), same-environment output identity (R2), numerical equivalence (R3), and statistical equivalence (R4). A changed output on finite prompts does not prove erased internal representations or universal off-target preservation, and checkpoint weight differences without a verified original do not establish tampering or intent.
The verified setup uses Python 3.14 and Node.js 24. The package declares Python 3.11+ and the frontend declares Node.js 22.12+, but the checked-in Python lock is validated on 3.14. On this Windows machine, the python on PATH is older; use the launcher and project virtualenv.
py -3.14 -m venv .venv
.venv\Scripts\python -m pip install -e ".[dev]" -c requirements.lock
npm ci --prefix frontendOn macOS/Linux, create .venv with a supported Python and use .venv/bin/python. CI explicitly installs a CPU Torch wheel before the constrained install; a CUDA build is optional and is not required for correctness tests. The checked-in dependency patch is applied during npm ci; do not skip its postinstall.
Settings come from WEIGHTFORGE_* environment variables or .env; see .env.example.
- Backend files live under
WEIGHTFORGE_DATA_DIR(default~/.weightforge). - Checkpoints are read from
<data dir>/modelsandWEIGHTFORGE_ALLOWED_MODEL_DIRS(a JSON list). Relative paths resolve insidemodels/. - A bearer token is generated on first run at
<data dir>/auth-tokenand printed in the startup terminal. An optionalWEIGHTFORGE_AUTH_TOKENoverride must contain at least 32 ASCII characters without whitespace.
.venv\Scripts\weightforge setup # First-run setup: initialize data_dir, token, DB migrations, and 4 starter datasets
.venv\Scripts\weightforge dev # API :8000 and workbench http://127.0.0.1:5280
.venv\Scripts\weightforge serve # API only at 127.0.0.1:8000
.venv\Scripts\weightforge mcp # Model Context Protocol (MCP) JSON-RPC 2.0 server over stdioEnter the terminal token in the workbench connection form. It is verified and stored for the browser tab's session; Disconnect clears credentials and cached queries. Port 5280 avoids another local project on 5173. Change it with WEIGHTFORGE_UI_PORT.
The CLI binds to loopback by default; other bind addresses require --allow-remote. Request bodies have a default 2 MiB cap, with smaller per-path limits configurable in settings. Domain failures carry {detail, code, request_id} and X-Request-ID. See the input-surface inventory and the threat model for implemented protections.
from weightforge.client import WeightForgeClient
wf = WeightForgeClient() # reads ~/.weightforge/auth-token automatically
model = wf.load_model("my-gpt2-checkpoint", dtype="float32")
# Trace activations and logit lens
trace = wf.trace_tokens(
model.model_id,
prompts=["The Eiffel Tower is in"],
hook_points=["blocks[0].resid_post", "blocks[1].resid_post"],
include_logit_lens=True,
)
# One-backward-pass attribution patching & circuit graph
attr = wf.attribution_patching(
model.model_id,
{
"prompt": "clean",
"donor_prompt": "corrupt",
"hook_points": ["blocks[0].resid_post", "blocks[1].mlp.out", "blocks[1].resid_post"],
"target_token": "target",
},
)
# Apply a reversible weight edit and export to GGUF / Ollama with R3 parity verification
patch = wf.apply_patch(
{
"model_id": model.model_id,
"target_layer": "lm_head.weight",
"operation": "sparse_edit",
"indices": [[6, 0]],
"values": [0.25],
"max_delta_l2": 2.0,
}
)
exported = wf.export_model(model.model_id, target_format="ollama", quantization="F16")
wf.revert_patch(model.model_id, patch.patch_id)Interactive reference: http://127.0.0.1:8000/docs (Authorize with the startup token). All /api/v1 routes require bearer authentication; /health is public.
| Endpoint Group | Key Routes | Current Purpose |
|---|---|---|
| System & Observability | GET /api/v1/system/resources, GET/POST/DELETE /api/v1/system/caches*, GET /api/v1/system/debug-bundle |
Real RAM/VRAM/cache telemetry, pinned artifact retention, and secret-redacted diagnostic bundle |
| Model Runtime & Checkpoints | POST /api/v1/models/load, GET /api/v1/models, GET/DELETE /api/v1/models/{id}, POST /api/v1/models/{id}/save, POST /api/v1/models/export |
Load/unload real or quantised (8bit/4bit) models, save verified merged/delta checkpoints, and export GGUF v3 / Ollama .Modelfile with R3 parity checks |
| Structure, Tracing & Interventions | GET /api/v1/models/{id}/structure, POST /api/v1/models/{id}/trace, POST/GET/DELETE /api/v1/models/{id}/traces*, POST /api/v1/models/{id}/interventions*, POST/GET/DELETE /api/v1/models/{id}/vectors* |
Module/parameter ownership, per-token traces, logit lens, cached snapshots, causal interventions, 256-cell sweeps, and steering vectors |
| Frontier Research (Phase 9) | POST /api/v1/models/{id}/attribution, /probes/train, /saes*, /rome, /task-arithmetic, /circuits, POST /api/v1/models/compare-checkpoints, POST /api/v1/models/{id}/selective-restore |
Attribution patching, linear probes, SAEs, ROME rank-1 editing, task vectors, circuit graphs, checkpoint diffing, and R1 selective restoration |
| Weight Transforms & Patch Stacks | POST /api/v1/transforms/apply, /transforms/factors, /transforms/rollback, GET /api/v1/models/{id}/patches, POST .../revert, .../replay, .../restore, .../verify, .../reset |
Budgeted sparse/row/col/scalar/low-rank edits, streamed factor uploads, individual revert, durable journal restore, and fast/full state verification |
| Datasets & Evaluations | POST/GET /api/v1/datasets*, POST/GET /api/v1/evaluations/run, /comparisons/run, /regressions/run, /protocols/freeze, /split-leakage/{id}, /final/run |
Strict JSONL datasets, descriptive evaluations, controlled comparisons, 4–5 check off-target regression gates, and locked-test confirmatory evaluations |
| Supervised Agent, MCP & Jobs | GET /api/v1/agent/tools, /agent/recipes, POST /api/v1/agent/session, /agent/tool_call, /agent/run, GET /api/v1/agent/sessions/{id}/stream, POST/GET /api/v1/agent/sessions/{id}/approvals*, POST /api/v1/mcp, POST/GET /api/v1/jobs*, GET/POST /api/v1/agent/harness/* |
Generated tool schemas, MCP server, atomic budgets, evidence policies, state-bound approvals, SSE live streaming, background jobs, and planted-answer harness |
| Experiment DAG & Catalog v2 | POST /api/v1/experiments/specs/run, GET /api/v1/experiments/{id}/lineage, GET/POST /api/v1/catalog/entries*, /catalog/register, /catalog/import, /catalog/entries/{id}/replay, /catalog/archives/* |
Branching experiment DAG, 64-cell experiment matrices, verified .wfpatch export/import, R1–R4 replay, and unverified experiment archives |
.venv\Scripts\python -m pytest # T1: offline deterministic correctness
.venv\Scripts\python -m pytest -m empirical # T2: offline pretrained experiments and latency; recorded outcomes
.venv\Scripts\python -m scripts.empirical_summary # table against declared bands
.venv\Scripts\python -m ruff check weightforge tests scripts
.venv\Scripts\python -m ruff format --check weightforge tests scripts
.venv\Scripts\python -m mypy # strict core checks
.venv\Scripts\python -m scripts.check_contracts
npm --prefix frontend run build
npm --prefix frontend run test:tooling
npm --prefix frontend exec -- playwright install chromium # once for browser tests
npm --prefix frontend run test:e2eAfter any API change, regenerate and review both contracts:
.venv\Scripts\weightforge openapi
npm --prefix frontend run gen:apiT1 gates correctness. T2 records empirical observations, environment and seeds; missing bands are unassessed, and declared band violations are reported separately. The current latency demonstration does not evaluate pretrained-model capability. CI, audit commands and hosted evidence are documented in docs/ci.md.
Produced deterministically by .venv\Scripts\python -m scripts.benchmark_performance:
| Operation | Scope / Input | Measured latency (ms) | Notes |
|---|---|---|---|
| Header-only safetensors enumeration | 16 layers (1,048,576 params) | 191.12 | Zero-copy metadata parse without full payload read |
Tensor spectral analysis (truncated_lowrank) |
256x256 fp32 matrix (top-8 SVD) | 5.99 | torch.svd_lowrank default on matrices >=64x64 |
Tensor spectral analysis (exact) |
256x256 fp32 matrix (full svdvals) |
5.41 | Explicit exact_svd=True opt-in |
| Local GPT-2 load & digest verification | 2-layer analytic GPT-2 (CPU) | 64.41 | Full parameter Merkle digest + writable clone |
| Batched token trace + logit lens | 2 prompts x 2 hooks + 2-layer lens | 149.08 | torch.inference_mode() with before/after state verification |
The project is motivated by Weight-Space Programming. The planned sequence is one live model runtime, trustworthy persistent edits, real dataset evaluation, reproducible catalog artifacts, then supervised agents. Successes and negative results must both be recorded. The roadmap distinguishes exact weights (R1), exact outputs in the same environment (R2), numerical equivalence (R3) and statistical evaluation equivalence (R4); these are design requirements, not current platform-wide guarantees.
The original generated ARCHITECTURE.json, CONTRACTS.json and BUILD_REPORT.json are archived in docs/generated/. They are historical output and contradict the current system. Use ROADMAP.md, ARCHITECTURE.md, docs/user-guide.md, and the generated OpenAPI (frontend/openapi.json) as the authoritative references.
WeightForge is distributed under the WeightForge Research and Collaboration Licence (Version 2.0) — see LICENSE.md. Copyright © 2026–present Edward Jonathan Bentley. All rights reserved.