diff --git a/.agents/skills/fine-tuning/SKILL.md b/.agents/skills/fine-tuning/SKILL.md index b5ceb0926..7d05d48b5 100644 --- a/.agents/skills/fine-tuning/SKILL.md +++ b/.agents/skills/fine-tuning/SKILL.md @@ -83,6 +83,7 @@ Train language models with SFT, KTO, and GRPO locally or on supported cloud prov | **GRPO** | Optimize against rewards | 5e-6 | 1 | Prompts + ground truth | Final online stage | | **Embedding** | Train a retrieval bi-encoder | 2e-5 | 1 | Triplets / pairs | Retrieval / RAG embedders | | **Decision** | Calibrated typed decisions (yes/no, choice, score) | 1e-4 (+1e-3 head) | 1 | State + typed question + gold | Routing / triage / policy checks (Jev-style) | +| **MechInterp Weight Patch** | Experimental base-weight patch/export, in-memory patch evaluation, module-site capture, bounded weight inspection | `reference/mechinterp-weight-patch.md` | | **Image LoRA** | Teach a diffusion model named characters, objects, places and a style | 1e-4 | steps, not epochs (~3-5k) | Images + caption .txt (trigger + entity tokens) | Illustration consistency (ai-toolkit on Modal) | **Recommended pipeline:** SFT → KTO → GRPO @@ -227,6 +228,7 @@ Load the specific reference you need: | **Image LoRA** | Qwen-Image LoRAs via ai-toolkit on Modal: dataset recipes, captions/tokens, sizing, cost cap, fetch/verify/cleanup | `reference/image-lora.md` | | **Troubleshooting** | OOM errors, instability, platform issues | `reference/troubleshooting.md` | | **Tokenizer Profiling** | Offline token-length distributions and sequence-budget sizing | `reference/tokenizer-profiling.md` | +| **Batch Generation** | Pinned vLLM, HF schema-decoding fallback, repeatability and resume qualification | `reference/batch-generation.md` | | **Derived Training Images** | Immutable package-overlay planning, capture, diagnostic reporting, and live launch verification | `reference/derived-training-images.md` | | **Nexus Note Snapshot** | Read-only, explicit private-note snapshots for config-driven analysis | `reference/nexus-note-snapshot.md` | | **Env Alignment Protocol** | Canonical SynthChat → SFT → merge/publish → KTO → env-GRPO flow | `protocols/environment-backed-alignment-pipeline.md` | diff --git a/.agents/skills/fine-tuning/reference/batch-generation.md b/.agents/skills/fine-tuning/reference/batch-generation.md new file mode 100644 index 000000000..ff9199bf0 --- /dev/null +++ b/.agents/skills/fine-tuning/reference/batch-generation.md @@ -0,0 +1,30 @@ +# Batch generation and structured decoding + +Use the existing public `batch-generate` verb. Prefer pinned vLLM with +`VLLM_BATCH_INVARIANT=1` when the model's attention backend supports it. Model +support alone does not establish batch-invariance support. Never bypass the +backend's capability refusal. + +An HF fallback can preserve the configured JSON interface: + +```bash +synaptic batch-generate --engine hf-batched --model LOCAL_CHECKPOINT \ + --prompts PROMPTS_JSONL --out-dir OUTPUT --batch-size 1 \ + --json-schema SCHEMA_JSON --structured-output-backend xgrammar --resume +``` + +HF JSON-schema decoding requires the optional `xgrammar` package. Pin its +version alongside Torch, Transformers, model/tokenizer revisions, dtype and +hardware in the consuming study. A fresh grammar matcher is created per batch. +No grammar dependency is loaded when a schema is absent. Registered conditional +generation models can serve text-only inputs through their Transformers auto +model class; no architecture-name heuristic or retry after a weight error is used. + +HF batch size one avoids changes in batch composition. It is not a claim of +cross-version or cross-hardware bitwise determinism. Qualify exact prompt/token +bytes, repeated and permuted completions, natural termination, whole-schema +validation, and hard-kill/resume on the actual model before scientific use. +Never silently change a signed backend or resume across different configuration +hashes. HF does not accept the vLLM-only arbitrary-whitespace control. + +The XGrammar HF integration follows its [official quick start](https://xgrammar.mlc.ai/docs/latest/start/quick_start.html). diff --git a/.agents/skills/fine-tuning/reference/mechinterp-weight-patch.md b/.agents/skills/fine-tuning/reference/mechinterp-weight-patch.md new file mode 100644 index 000000000..01d0e542d --- /dev/null +++ b/.agents/skills/fine-tuning/reference/mechinterp-weight-patch.md @@ -0,0 +1,67 @@ +# MechInterp weight patches, module-site capture and weight inspection (experimental) + +Experimental, CLI-only MechInterp capabilities (not part of any stable public API). +Everything is config-driven; engine code names no model, tensor, direction or +dataset. The full contract and examples live in `docs/MECH_INTERP_CELLS.md` +("Experimental: weight patches, module-site capture, weight inspection"); this page +carries the working rules. + +## Commands + +```bash +python tuner.py mechinterp weights-inspect --weights-config inspect.yaml --json +python tuner.py mechinterp weights-patch --weights-config patch.yaml --validate --json +python tuner.py mechinterp weights-patch --weights-config patch.yaml --export --json +``` + +Use `mechinterp run --dry-run` for planning; `steer --dry-run` does not exist. +Pipeline stages are compiled as `python -m tuner mechinterp ...`; `dose-calibrate` +forwards `--model-revision`. + +## Rules + +- Specs are `mechinterp-weight-patch/v1` / `mechinterp-weights-inspect/v1` YAML or + JSON; pin every targeted tensor's dtype, shape and raw-byte sha256, the exact + 40-hex `base.revision`, and `index_sha256`/`files_sha256`. Author the pins from + `weights-inspect` with `hash_tensors: true`. +- Budgets are required and finite (`allowed_tensors`, `max_modified_tensors`, + `max_modified_entries`, per-tensor `max_relative_frobenius`). The patch is + all-or-nothing; a refusal changes nothing. +- Always `--validate` before `--export`. Export is create-only into a new directory + and verifies untouched bytes by re-hashing; it never overwrites. Large outputs + (including to external drives) are chosen by `export.output_dir`, never by code. +- External filesystems may reject exclusive directory rename. Export then uses + exclusive directory creation, verified file copies and a completion manifest + written last. Require that manifest before consuming an export. A kill can + leave an incomplete directory; retain it and retry into a fresh destination. + This fallback preserves create-only behavior, not atomic directory publication. +- Evaluate candidates with `surface.weight_patch: {path, sha256}` (in-memory, no + export per candidate). The run must pass `--model-revision` equal to + `base.revision`; use a fresh output path when the patch changes (stale lineage + exits 6; a refused patch exits 7 before any row). +- Compare retained `generated_token_ids` for zero-patch, batch and export parity; + matching decoded text alone is insufficient. Old outputs without IDs need a + fresh parity run. +- `extract` `capture_sites` use decoder BLOCK indices (`law.layer` convention), not + `hidden_states` indices. Set `use_cache: true` for hybrid/KV-sharing models, and + `forward_only: true` with `families: [anchor]` for anchor-only reads. +- Use `resume: true` for long extraction. `capture.runlog.jsonl` commits each row + after its tensor files are fsynced and hashed. Resume verifies source/settings/ + patch identity and every completed file, then skips completed rows. Without + resume the output directory must be empty. Probe fitting requires a completed + manifest and verifies its captured files. Use the manifest's filenames: unsafe + keys are hash-encoded for portable storage, and collisions are refused. +- Inspect projections are bounded numeric reads (dot/cosine/slice over selected + rows or columns); keep `max_output_values` small and do the interpretation in + project-side analysis, not in engine code. +- A bare revision string is not authenticated by file bytes: the byte pins are the + binding. Hub-id loads verify only the targeted tensors. + +## Test + +```bash +# dedicated CPU-only venv (never the main Unsloth/GPU env): torch (CPU wheel), +# safetensors, pydantic, pyyaml, pytest, transformers, pandas, scikit-learn, +# jsonschema, python-dotenv, packaging +python -m pytest tests/mech_interp +``` diff --git a/.claude/skills/fine-tuning/SKILL.md b/.claude/skills/fine-tuning/SKILL.md index b5ceb0926..7d05d48b5 100644 --- a/.claude/skills/fine-tuning/SKILL.md +++ b/.claude/skills/fine-tuning/SKILL.md @@ -83,6 +83,7 @@ Train language models with SFT, KTO, and GRPO locally or on supported cloud prov | **GRPO** | Optimize against rewards | 5e-6 | 1 | Prompts + ground truth | Final online stage | | **Embedding** | Train a retrieval bi-encoder | 2e-5 | 1 | Triplets / pairs | Retrieval / RAG embedders | | **Decision** | Calibrated typed decisions (yes/no, choice, score) | 1e-4 (+1e-3 head) | 1 | State + typed question + gold | Routing / triage / policy checks (Jev-style) | +| **MechInterp Weight Patch** | Experimental base-weight patch/export, in-memory patch evaluation, module-site capture, bounded weight inspection | `reference/mechinterp-weight-patch.md` | | **Image LoRA** | Teach a diffusion model named characters, objects, places and a style | 1e-4 | steps, not epochs (~3-5k) | Images + caption .txt (trigger + entity tokens) | Illustration consistency (ai-toolkit on Modal) | **Recommended pipeline:** SFT → KTO → GRPO @@ -227,6 +228,7 @@ Load the specific reference you need: | **Image LoRA** | Qwen-Image LoRAs via ai-toolkit on Modal: dataset recipes, captions/tokens, sizing, cost cap, fetch/verify/cleanup | `reference/image-lora.md` | | **Troubleshooting** | OOM errors, instability, platform issues | `reference/troubleshooting.md` | | **Tokenizer Profiling** | Offline token-length distributions and sequence-budget sizing | `reference/tokenizer-profiling.md` | +| **Batch Generation** | Pinned vLLM, HF schema-decoding fallback, repeatability and resume qualification | `reference/batch-generation.md` | | **Derived Training Images** | Immutable package-overlay planning, capture, diagnostic reporting, and live launch verification | `reference/derived-training-images.md` | | **Nexus Note Snapshot** | Read-only, explicit private-note snapshots for config-driven analysis | `reference/nexus-note-snapshot.md` | | **Env Alignment Protocol** | Canonical SynthChat → SFT → merge/publish → KTO → env-GRPO flow | `protocols/environment-backed-alignment-pipeline.md` | diff --git a/.claude/skills/fine-tuning/reference/batch-generation.md b/.claude/skills/fine-tuning/reference/batch-generation.md new file mode 100644 index 000000000..ff9199bf0 --- /dev/null +++ b/.claude/skills/fine-tuning/reference/batch-generation.md @@ -0,0 +1,30 @@ +# Batch generation and structured decoding + +Use the existing public `batch-generate` verb. Prefer pinned vLLM with +`VLLM_BATCH_INVARIANT=1` when the model's attention backend supports it. Model +support alone does not establish batch-invariance support. Never bypass the +backend's capability refusal. + +An HF fallback can preserve the configured JSON interface: + +```bash +synaptic batch-generate --engine hf-batched --model LOCAL_CHECKPOINT \ + --prompts PROMPTS_JSONL --out-dir OUTPUT --batch-size 1 \ + --json-schema SCHEMA_JSON --structured-output-backend xgrammar --resume +``` + +HF JSON-schema decoding requires the optional `xgrammar` package. Pin its +version alongside Torch, Transformers, model/tokenizer revisions, dtype and +hardware in the consuming study. A fresh grammar matcher is created per batch. +No grammar dependency is loaded when a schema is absent. Registered conditional +generation models can serve text-only inputs through their Transformers auto +model class; no architecture-name heuristic or retry after a weight error is used. + +HF batch size one avoids changes in batch composition. It is not a claim of +cross-version or cross-hardware bitwise determinism. Qualify exact prompt/token +bytes, repeated and permuted completions, natural termination, whole-schema +validation, and hard-kill/resume on the actual model before scientific use. +Never silently change a signed backend or resume across different configuration +hashes. HF does not accept the vLLM-only arbitrary-whitespace control. + +The XGrammar HF integration follows its [official quick start](https://xgrammar.mlc.ai/docs/latest/start/quick_start.html). diff --git a/.claude/skills/fine-tuning/reference/mechinterp-weight-patch.md b/.claude/skills/fine-tuning/reference/mechinterp-weight-patch.md new file mode 100644 index 000000000..01d0e542d --- /dev/null +++ b/.claude/skills/fine-tuning/reference/mechinterp-weight-patch.md @@ -0,0 +1,67 @@ +# MechInterp weight patches, module-site capture and weight inspection (experimental) + +Experimental, CLI-only MechInterp capabilities (not part of any stable public API). +Everything is config-driven; engine code names no model, tensor, direction or +dataset. The full contract and examples live in `docs/MECH_INTERP_CELLS.md` +("Experimental: weight patches, module-site capture, weight inspection"); this page +carries the working rules. + +## Commands + +```bash +python tuner.py mechinterp weights-inspect --weights-config inspect.yaml --json +python tuner.py mechinterp weights-patch --weights-config patch.yaml --validate --json +python tuner.py mechinterp weights-patch --weights-config patch.yaml --export --json +``` + +Use `mechinterp run --dry-run` for planning; `steer --dry-run` does not exist. +Pipeline stages are compiled as `python -m tuner mechinterp ...`; `dose-calibrate` +forwards `--model-revision`. + +## Rules + +- Specs are `mechinterp-weight-patch/v1` / `mechinterp-weights-inspect/v1` YAML or + JSON; pin every targeted tensor's dtype, shape and raw-byte sha256, the exact + 40-hex `base.revision`, and `index_sha256`/`files_sha256`. Author the pins from + `weights-inspect` with `hash_tensors: true`. +- Budgets are required and finite (`allowed_tensors`, `max_modified_tensors`, + `max_modified_entries`, per-tensor `max_relative_frobenius`). The patch is + all-or-nothing; a refusal changes nothing. +- Always `--validate` before `--export`. Export is create-only into a new directory + and verifies untouched bytes by re-hashing; it never overwrites. Large outputs + (including to external drives) are chosen by `export.output_dir`, never by code. +- External filesystems may reject exclusive directory rename. Export then uses + exclusive directory creation, verified file copies and a completion manifest + written last. Require that manifest before consuming an export. A kill can + leave an incomplete directory; retain it and retry into a fresh destination. + This fallback preserves create-only behavior, not atomic directory publication. +- Evaluate candidates with `surface.weight_patch: {path, sha256}` (in-memory, no + export per candidate). The run must pass `--model-revision` equal to + `base.revision`; use a fresh output path when the patch changes (stale lineage + exits 6; a refused patch exits 7 before any row). +- Compare retained `generated_token_ids` for zero-patch, batch and export parity; + matching decoded text alone is insufficient. Old outputs without IDs need a + fresh parity run. +- `extract` `capture_sites` use decoder BLOCK indices (`law.layer` convention), not + `hidden_states` indices. Set `use_cache: true` for hybrid/KV-sharing models, and + `forward_only: true` with `families: [anchor]` for anchor-only reads. +- Use `resume: true` for long extraction. `capture.runlog.jsonl` commits each row + after its tensor files are fsynced and hashed. Resume verifies source/settings/ + patch identity and every completed file, then skips completed rows. Without + resume the output directory must be empty. Probe fitting requires a completed + manifest and verifies its captured files. Use the manifest's filenames: unsafe + keys are hash-encoded for portable storage, and collisions are refused. +- Inspect projections are bounded numeric reads (dot/cosine/slice over selected + rows or columns); keep `max_output_values` small and do the interpretation in + project-side analysis, not in engine code. +- A bare revision string is not authenticated by file bytes: the byte pins are the + binding. Hub-id loads verify only the targeted tensors. + +## Test + +```bash +# dedicated CPU-only venv (never the main Unsloth/GPU env): torch (CPU wheel), +# safetensors, pydantic, pyyaml, pytest, transformers, pandas, scikit-learn, +# jsonschema, python-dotenv, packaging +python -m pytest tests/mech_interp +``` diff --git a/.skills/fine-tuning/SKILL.md b/.skills/fine-tuning/SKILL.md index b5ceb0926..7d05d48b5 100644 --- a/.skills/fine-tuning/SKILL.md +++ b/.skills/fine-tuning/SKILL.md @@ -83,6 +83,7 @@ Train language models with SFT, KTO, and GRPO locally or on supported cloud prov | **GRPO** | Optimize against rewards | 5e-6 | 1 | Prompts + ground truth | Final online stage | | **Embedding** | Train a retrieval bi-encoder | 2e-5 | 1 | Triplets / pairs | Retrieval / RAG embedders | | **Decision** | Calibrated typed decisions (yes/no, choice, score) | 1e-4 (+1e-3 head) | 1 | State + typed question + gold | Routing / triage / policy checks (Jev-style) | +| **MechInterp Weight Patch** | Experimental base-weight patch/export, in-memory patch evaluation, module-site capture, bounded weight inspection | `reference/mechinterp-weight-patch.md` | | **Image LoRA** | Teach a diffusion model named characters, objects, places and a style | 1e-4 | steps, not epochs (~3-5k) | Images + caption .txt (trigger + entity tokens) | Illustration consistency (ai-toolkit on Modal) | **Recommended pipeline:** SFT → KTO → GRPO @@ -227,6 +228,7 @@ Load the specific reference you need: | **Image LoRA** | Qwen-Image LoRAs via ai-toolkit on Modal: dataset recipes, captions/tokens, sizing, cost cap, fetch/verify/cleanup | `reference/image-lora.md` | | **Troubleshooting** | OOM errors, instability, platform issues | `reference/troubleshooting.md` | | **Tokenizer Profiling** | Offline token-length distributions and sequence-budget sizing | `reference/tokenizer-profiling.md` | +| **Batch Generation** | Pinned vLLM, HF schema-decoding fallback, repeatability and resume qualification | `reference/batch-generation.md` | | **Derived Training Images** | Immutable package-overlay planning, capture, diagnostic reporting, and live launch verification | `reference/derived-training-images.md` | | **Nexus Note Snapshot** | Read-only, explicit private-note snapshots for config-driven analysis | `reference/nexus-note-snapshot.md` | | **Env Alignment Protocol** | Canonical SynthChat → SFT → merge/publish → KTO → env-GRPO flow | `protocols/environment-backed-alignment-pipeline.md` | diff --git a/.skills/fine-tuning/reference/batch-generation.md b/.skills/fine-tuning/reference/batch-generation.md new file mode 100644 index 000000000..ff9199bf0 --- /dev/null +++ b/.skills/fine-tuning/reference/batch-generation.md @@ -0,0 +1,30 @@ +# Batch generation and structured decoding + +Use the existing public `batch-generate` verb. Prefer pinned vLLM with +`VLLM_BATCH_INVARIANT=1` when the model's attention backend supports it. Model +support alone does not establish batch-invariance support. Never bypass the +backend's capability refusal. + +An HF fallback can preserve the configured JSON interface: + +```bash +synaptic batch-generate --engine hf-batched --model LOCAL_CHECKPOINT \ + --prompts PROMPTS_JSONL --out-dir OUTPUT --batch-size 1 \ + --json-schema SCHEMA_JSON --structured-output-backend xgrammar --resume +``` + +HF JSON-schema decoding requires the optional `xgrammar` package. Pin its +version alongside Torch, Transformers, model/tokenizer revisions, dtype and +hardware in the consuming study. A fresh grammar matcher is created per batch. +No grammar dependency is loaded when a schema is absent. Registered conditional +generation models can serve text-only inputs through their Transformers auto +model class; no architecture-name heuristic or retry after a weight error is used. + +HF batch size one avoids changes in batch composition. It is not a claim of +cross-version or cross-hardware bitwise determinism. Qualify exact prompt/token +bytes, repeated and permuted completions, natural termination, whole-schema +validation, and hard-kill/resume on the actual model before scientific use. +Never silently change a signed backend or resume across different configuration +hashes. HF does not accept the vLLM-only arbitrary-whitespace control. + +The XGrammar HF integration follows its [official quick start](https://xgrammar.mlc.ai/docs/latest/start/quick_start.html). diff --git a/.skills/fine-tuning/reference/mechinterp-weight-patch.md b/.skills/fine-tuning/reference/mechinterp-weight-patch.md new file mode 100644 index 000000000..01d0e542d --- /dev/null +++ b/.skills/fine-tuning/reference/mechinterp-weight-patch.md @@ -0,0 +1,67 @@ +# MechInterp weight patches, module-site capture and weight inspection (experimental) + +Experimental, CLI-only MechInterp capabilities (not part of any stable public API). +Everything is config-driven; engine code names no model, tensor, direction or +dataset. The full contract and examples live in `docs/MECH_INTERP_CELLS.md` +("Experimental: weight patches, module-site capture, weight inspection"); this page +carries the working rules. + +## Commands + +```bash +python tuner.py mechinterp weights-inspect --weights-config inspect.yaml --json +python tuner.py mechinterp weights-patch --weights-config patch.yaml --validate --json +python tuner.py mechinterp weights-patch --weights-config patch.yaml --export --json +``` + +Use `mechinterp run --dry-run` for planning; `steer --dry-run` does not exist. +Pipeline stages are compiled as `python -m tuner mechinterp ...`; `dose-calibrate` +forwards `--model-revision`. + +## Rules + +- Specs are `mechinterp-weight-patch/v1` / `mechinterp-weights-inspect/v1` YAML or + JSON; pin every targeted tensor's dtype, shape and raw-byte sha256, the exact + 40-hex `base.revision`, and `index_sha256`/`files_sha256`. Author the pins from + `weights-inspect` with `hash_tensors: true`. +- Budgets are required and finite (`allowed_tensors`, `max_modified_tensors`, + `max_modified_entries`, per-tensor `max_relative_frobenius`). The patch is + all-or-nothing; a refusal changes nothing. +- Always `--validate` before `--export`. Export is create-only into a new directory + and verifies untouched bytes by re-hashing; it never overwrites. Large outputs + (including to external drives) are chosen by `export.output_dir`, never by code. +- External filesystems may reject exclusive directory rename. Export then uses + exclusive directory creation, verified file copies and a completion manifest + written last. Require that manifest before consuming an export. A kill can + leave an incomplete directory; retain it and retry into a fresh destination. + This fallback preserves create-only behavior, not atomic directory publication. +- Evaluate candidates with `surface.weight_patch: {path, sha256}` (in-memory, no + export per candidate). The run must pass `--model-revision` equal to + `base.revision`; use a fresh output path when the patch changes (stale lineage + exits 6; a refused patch exits 7 before any row). +- Compare retained `generated_token_ids` for zero-patch, batch and export parity; + matching decoded text alone is insufficient. Old outputs without IDs need a + fresh parity run. +- `extract` `capture_sites` use decoder BLOCK indices (`law.layer` convention), not + `hidden_states` indices. Set `use_cache: true` for hybrid/KV-sharing models, and + `forward_only: true` with `families: [anchor]` for anchor-only reads. +- Use `resume: true` for long extraction. `capture.runlog.jsonl` commits each row + after its tensor files are fsynced and hashed. Resume verifies source/settings/ + patch identity and every completed file, then skips completed rows. Without + resume the output directory must be empty. Probe fitting requires a completed + manifest and verifies its captured files. Use the manifest's filenames: unsafe + keys are hash-encoded for portable storage, and collisions are refused. +- Inspect projections are bounded numeric reads (dot/cosine/slice over selected + rows or columns); keep `max_output_values` small and do the interpretation in + project-side analysis, not in engine code. +- A bare revision string is not authenticated by file bytes: the byte pins are the + binding. Hub-id loads verify only the targeted tensors. + +## Test + +```bash +# dedicated CPU-only venv (never the main Unsloth/GPU env): torch (CPU wheel), +# safetensors, pydantic, pyyaml, pytest, transformers, pandas, scikit-learn, +# jsonschema, python-dotenv, packaging +python -m pytest tests/mech_interp +``` diff --git a/MechInterp/cell.py b/MechInterp/cell.py index 702431f49..ba127cdbc 100644 --- a/MechInterp/cell.py +++ b/MechInterp/cell.py @@ -74,10 +74,22 @@ def compute_config_sha(config: SteerCellConfig | DoseCalibrationConfig) -> str: """ payload = config.model_dump(mode="json") payload.get("surface", {}).pop("expected_config_sha", None) + # An absent weight patch must hash exactly as it did before the field + # existed, so historical config shas and recorded smokes stay valid. + if payload.get("surface", {}).get("weight_patch") is None: + payload.get("surface", {}).pop("weight_patch", None) canon = json.dumps(payload, sort_keys=True, separators=(",", ":")) return hashlib.sha256(canon.encode("utf-8")).hexdigest() +def _surface_dump(config: SteerCellConfig | DoseCalibrationConfig) -> dict: + """Surface block for manifests; an absent weight_patch is omitted entirely.""" + surface = config.surface.model_dump(mode="json") + if surface.get("weight_patch") is None: + surface.pop("weight_patch", None) + return surface + + def _active_keys_for_arm(arm: ArmConfig, rows: list[dict]) -> list[str]: """Return the row keys an arm activates, in row order.""" keys = [row_key_of(r) for r in rows] @@ -374,6 +386,7 @@ def write_dose_manifest( config: DoseCalibrationConfig, config_sha: str, run_summaries: dict, + weight_patch: dict | None = None, ) -> Path: """Write a dose-calibration manifest next to the checkpoint JSONL.""" p = Path(output_path) @@ -383,9 +396,11 @@ def write_dose_manifest( "law": config.law.model_dump(mode="json"), "readouts": [r.model_dump(mode="json") for r in config.readouts], "calibration": config.calibration.model_dump(mode="json"), - "surface": config.surface.model_dump(mode="json"), + "surface": _surface_dump(config), "runs": run_summaries, } + if weight_patch is not None: + manifest["weight_patch"] = weight_patch with open(manifest_path, "w") as f: json.dump(manifest, f, indent=2) return manifest_path @@ -401,8 +416,16 @@ def smoke_state_path(output_path: str | Path) -> Path: return p.with_suffix(p.suffix + ".smoke_ok.json") -def smoke_passed(output_path: str | Path, config_sha: str) -> bool: - """True if a smoke pass for this exact config sha has been recorded.""" +def smoke_passed( + output_path: str | Path, config_sha: str, patch_digest: str | None = None +) -> bool: + """True if a smoke pass for this exact config sha has been recorded. + + ``patch_digest`` is the applied weight patch's lineage digest (None when no + patch is applied). The recorded smoke must have been taken under the same + patch; a state file that predates patches records none, which matches + ``None`` exactly as before. + """ sp = smoke_state_path(output_path) if not sp.exists(): return False @@ -411,15 +434,92 @@ def smoke_passed(output_path: str | Path, config_sha: str) -> bool: state = json.load(f) except (json.JSONDecodeError, OSError): return False - return bool(state.get("passed")) and state.get("config_sha") == config_sha + return ( + bool(state.get("passed")) + and state.get("config_sha") == config_sha + and state.get("weight_patch_digest") == patch_digest + ) -def record_smoke(output_path: str | Path, config_sha: str, readback: dict) -> None: +def record_smoke( + output_path: str | Path, + config_sha: str, + readback: dict, + patch_digest: str | None = None, +) -> None: sp = smoke_state_path(output_path) sp.parent.mkdir(parents=True, exist_ok=True) + state = { + "passed": bool(readback.get("passed")), + "config_sha": config_sha, + "readback": readback, + } + if patch_digest is not None: + state["weight_patch_digest"] = patch_digest with open(sp, "w") as f: + json.dump(state, f, indent=2) + + +# -------------------------------------------------------------------------- +# Weight-patch resume lineage +# -------------------------------------------------------------------------- + + +class WeightPatchLineageError(ValueError): + """Existing output rows were produced under a different weight-patch lineage.""" + + +def weight_patch_lineage_path(output_path: str | Path) -> Path: + p = Path(output_path) + return p.with_suffix(p.suffix + ".weight_patch.json") + + +def enforce_weight_patch_lineage( + output_path: str | Path, receipt: dict | None +) -> None: + """Bind a per-row output JSONL to the weight patch that produced it. + + - No patch and no lineage file: nothing to do (historical behavior). + - Patch, output absent/empty: create-only lineage record before any row. + - Otherwise the recorded ``patch_digest`` must equal the current one; a patch + appearing, disappearing or changing under existing rows is refused, so a + resume can never splice rows from a different patched model. + + The digest covers the spec bytes, payload bytes, declared revision and the + exact before/after bytes of every targeted tensor, so a changed patch file or + a different base source both change it. + """ + out = Path(output_path) + lineage = weight_patch_lineage_path(out) + has_rows = out.exists() and out.stat().st_size > 0 + recorded = None + if lineage.exists(): + try: + with open(lineage) as f: + recorded = json.load(f).get("patch_digest") + except (json.JSONDecodeError, OSError, AttributeError): + raise WeightPatchLineageError( + f"unreadable weight-patch lineage record {lineage.name}; refusing to resume" + ) from None + current = receipt["patch_digest"] if receipt is not None else None + if current is None and recorded is None: + return + if has_rows or recorded is not None: + if recorded != current: + raise WeightPatchLineageError( + "existing output rows were produced under weight-patch lineage " + f"{recorded!r} but this run uses {current!r}; use a fresh output path" + ) + return + lineage.parent.mkdir(parents=True, exist_ok=True) + with open(lineage, "x") as f: json.dump( - {"passed": bool(readback.get("passed")), "config_sha": config_sha, "readback": readback}, + { + "patch_digest": current, + "spec_sha256": receipt["spec_sha256"], + "payload_sha256": receipt["payload_sha256"], + "revision": receipt["revision"], + }, f, indent=2, ) @@ -461,6 +561,7 @@ def write_manifest( config: SteerCellConfig, config_sha: str, arm_summaries: dict, + weight_patch: dict | None = None, ) -> Path: """Write a run manifest next to the output JSONL.""" p = Path(output_path) @@ -470,8 +571,10 @@ def write_manifest( "law": config.law.model_dump(mode="json"), "readouts": [r.model_dump(mode="json") for r in config.readouts], "arms": arm_summaries, - "surface": config.surface.model_dump(mode="json"), + "surface": _surface_dump(config), } + if weight_patch is not None: + manifest["weight_patch"] = weight_patch with open(manifest_path, "w") as f: json.dump(manifest, f, indent=2) return manifest_path diff --git a/MechInterp/cli.py b/MechInterp/cli.py index 04cfc1504..3bc4565e8 100644 --- a/MechInterp/cli.py +++ b/MechInterp/cli.py @@ -43,10 +43,22 @@ # -------------------------------------------------------------------------- -def _load_model_and_tokenizer(model_name: str, adapter: Optional[str] = None, revision: Optional[str] = None): +def _load_model_and_tokenizer( + model_name: str, + adapter: Optional[str] = None, + revision: Optional[str] = None, + post_base_load: Optional[Callable] = None, +): + """Load the base model (+ optional adapter). + + ``post_base_load(model)`` runs on the freshly loaded BASE model, before an + adapter is attached and before the model is returned for any generation or + capture. It is how an in-memory weight patch is applied. + """ import torch import transformers - from transformers import AutoModelForCausalLM, AutoTokenizer + from transformers import AutoTokenizer + from shared.utilities.text_model import load_text_generation_model major = int(transformers.__version__.split(".")[0]) dtype_kwarg = {"dtype": torch.bfloat16} if major >= 5 else {"torch_dtype": torch.bfloat16} @@ -54,9 +66,11 @@ def _load_model_and_tokenizer(model_name: str, adapter: Optional[str] = None, re tokenizer = AutoTokenizer.from_pretrained(model_name, revision=revision, token=token) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token - model = AutoModelForCausalLM.from_pretrained( + model = load_text_generation_model( model_name, revision=revision, token=token, device_map="auto", **dtype_kwarg ) + if post_base_load is not None: + post_base_load(model) if adapter: from peft import PeftModel @@ -82,24 +96,97 @@ def _load_callable(spec: str) -> Callable: return getattr(importlib.import_module(module_path), attr) +# -------------------------------------------------------------------------- +# weight patch (optional surface.weight_patch / extract weight_patch) +# -------------------------------------------------------------------------- + +# Exit codes added by this capability: 6 = stale weight-patch lineage on resume, +# 7 = weight patch refused (nothing applied). +EXIT_PATCH_LINEAGE = 6 +EXIT_PATCH_REFUSED = 7 + + +class _PatchSession: + """Verifies a pinned patch before the model loads and applies it after. + + ``hook`` is passed as ``post_base_load``. ``receipt`` is the applied patch's + receipt dict (None when no patch is configured). + """ + + def __init__(self, ref, revision: Optional[str], context: ProjectContext | None): + self.receipt: Optional[dict] = None + self._applied = None + self._prepared = None + if ref is None: + return + from MechInterp.weights.runtime import check_declared_revision, prepare_patch + + self._prepared = prepare_patch(ref.path, ref.sha256, context=context) + check_declared_revision(self._prepared, revision) + + @property + def active(self) -> bool: + return self._prepared is not None + + @property + def hook(self) -> Optional[Callable]: + return self._apply if self._prepared is not None else None + + @property + def digest(self) -> Optional[str]: + return self.receipt["patch_digest"] if self.receipt else None + + def _apply(self, model) -> None: + from MechInterp.weights.runtime import apply_patch, check_loaded_commit + + commit = check_loaded_commit(self._prepared, model) + self._applied = apply_patch(model, self._prepared) + self.receipt = self._applied.receipt + self.receipt["loaded_commit_hash"] = commit + + +def _patch_refusal(exc: Exception) -> int: + print(f"Weight patch refused: {exc}") + return EXIT_PATCH_REFUSED + + # -------------------------------------------------------------------------- # extract # -------------------------------------------------------------------------- -def run_extract(config: ExtractConfig, model_name: str, revision: Optional[str], adapter: Optional[str], gpu_ack: bool) -> int: +def run_extract( + config: ExtractConfig, + model_name: str, + revision: Optional[str], + adapter: Optional[str], + gpu_ack: bool, + project_context: ProjectContext | None = None, +) -> int: guard = _require_gpu_ack(gpu_ack) if guard is not None: return guard from MechInterp.extraction import PositionSpec, extract_rows + from MechInterp.weights.errors import WeightPatchError rows = cell_mod.load_jsonl(config.rows_path) render_fn = _load_callable(config.render_fn) - content_end_fn = _load_callable(config.content_end_fn) - model, tokenizer = _load_model_and_tokenizer(model_name, adapter, revision) + content_end_fn = ( + _load_callable(config.content_end_fn) if config.content_end_fn else None + ) + try: + patch = _PatchSession(config.weight_patch, revision, project_context) + model, tokenizer = _load_model_and_tokenizer( + model_name, adapter, revision, post_base_load=patch.hook + ) + except WeightPatchError as exc: + return _patch_refusal(exc) spec = PositionSpec( families=config.families, every_k=config.every_k, layers=config.layers ) + from MechInterp.extraction.persistence import capture_run_identity + + identity = capture_run_identity(model_name, revision, adapter, render_fn, content_end_fn) if config.resume else None manifest = extract_rows( model, tokenizer, @@ -109,6 +196,12 @@ def run_extract(config: ExtractConfig, model_name: str, revision: Optional[str], spec=spec, out_dir=config.output_dir, max_new_tokens=config.max_new_tokens, + capture_sites=config.capture_sites, + use_cache=config.use_cache, + forward_only=config.forward_only, + resume=config.resume, + run_identity=identity, + manifest_extra={"weight_patch": patch.receipt} if patch.receipt else None, ) print( f"Extracted {manifest['n_answered']}/{manifest['n_rows']} answered rows " @@ -132,15 +225,44 @@ def _load_activation_matrix(activations_dir: str, family: str, labels: list[dict from safetensors.torch import load_file act_dir = Path(activations_dir) + from MechInterp.extraction.persistence import verified_file + + manifest = json.loads((act_dir / "manifest.json").read_text(encoding="utf-8")) + modern = manifest.get("schema_version") == "mechinterp-capture/v2" + if modern and manifest.get("complete") is not True: + raise ValueError("probe-fit requires a completed extraction manifest") + if not modern and (manifest.get("weight_patch") or (act_dir / "capture.runlog.jsonl.meta.json").exists()): + raise ValueError("patched or resumable captures require a v2 manifest") + capture_rows = {rec["row_key"]: rec for rec in manifest["rows"]} + if len(capture_rows) != len(manifest["rows"]): + raise ValueError("duplicate row keys in extraction manifest") per_layer: dict[int, list] = {} y = [] + seen = set() for rec in labels: rk = str(rec.get("row_key", rec.get("id"))) - safe_key = rk.replace("::", "__").replace("|", "_").replace("/", "_") - f = act_dir / f"{safe_key}__{family}.safetensors" - if not f.exists(): + if rk in seen: + raise ValueError("duplicate row keys in probe labels") + seen.add(rk) + captured = capture_rows.get(rk) + if not captured or not captured.get("answered"): continue + if modern: + info = captured.get("capture_files", {}).get(family) + if info is None: + continue + f = verified_file(act_dir, info) + else: + # Read historical manifests, never stray files absent from their row set. + if family not in captured.get("captured_families", []): + continue + safe_key = rk.replace("::", "__").replace("|", "_").replace("/", "_") + f = act_dir / f"{safe_key}__{family}.safetensors" + if f.parent.resolve() != act_dir.resolve() or not f.is_file(): + raise ValueError("historical capture file is missing or unsafe") tensors = load_file(str(f)) + if per_layer and set(tensors) != {f"L{li}" for li in per_layer}: + raise ValueError("capture layer sets differ between probe rows") for key, t in tensors.items(): li = int(key[1:]) # "L23" -> 23 per_layer.setdefault(li, []).append(t[0].numpy()) # first captured pos @@ -212,6 +334,7 @@ def _direction_tensor(readout_record: dict): "answer_text", "prompt_len", "n_new_tokens", + "generated_token_ids", "terminated_naturally", } ) @@ -311,6 +434,7 @@ def _continuation_record(tokenizer, continuation, generation) -> dict: text = tokenizer.decode(effective_ids, skip_special_tokens=True) return { "answer_text": text, + "generated_token_ids": effective_ids, "n_new_tokens": int(stop_len), "terminated_naturally": bool(stop_len < generation.max_new_tokens), } @@ -486,7 +610,20 @@ def run_steer( active_readout = readout_by_name[config.law.readout] layer = config.law.layer if config.law.layer is not None else active_readout["layer"] - model, tokenizer = _load_model_and_tokenizer(model_name, adapter, revision) + from MechInterp.weights.errors import WeightPatchError + + try: + patch = _PatchSession(config.surface.weight_patch, revision, project_context) + model, tokenizer = _load_model_and_tokenizer( + model_name, adapter, revision, post_base_load=patch.hook + ) + except WeightPatchError as exc: + return _patch_refusal(exc) + try: + cell_mod.enforce_weight_patch_lineage(config.execution.output_path, patch.receipt) + except cell_mod.WeightPatchLineageError as exc: + print(f"Refusing to resume: {exc}") + return EXIT_PATCH_LINEAGE direction = _direction_tensor(active_readout) sigma = float(active_readout.get("sigma", 1.0)) hook = InterventionHook( @@ -506,7 +643,9 @@ def run_steer( ) # Smoke gate: run n_rows through the intervention with readback and record. - if not force and not cell_mod.smoke_passed(config.execution.output_path, config_sha): + if not force and not cell_mod.smoke_passed( + config.execution.output_path, config_sha, patch.digest + ): readback = _run_smoke( model, tokenizer, config, rows, render_fn, direction, sigma, layer ) @@ -535,7 +674,12 @@ def run_steer( verdict["gen_stream_fired"] = gen_stream_fired readback["passed"] = verdict["passed"] - cell_mod.record_smoke(config.execution.output_path, config_sha, {**readback, **verdict}) + cell_mod.record_smoke( + config.execution.output_path, + config_sha, + {**readback, **verdict}, + patch_digest=patch.digest, + ) if not verdict["passed"]: handle.remove() if gen_stream_fired is False: @@ -578,6 +722,8 @@ def run_steer( config.law.generation_mode, render_fn, ) rec["arm"] = arm.name + if patch.digest: + rec["weight_patch_digest"] = patch.digest if grader is not None: rec.update(grader(rec)) _write_checkpoint_record(out, rec, redact_fields) @@ -590,12 +736,16 @@ def run_steer( ) for rec in recs: rec["arm"] = arm.name + if patch.digest: + rec["weight_patch_digest"] = patch.digest if grader is not None: rec.update(grader(rec)) _write_checkpoint_record(out, rec, redact_fields) handle.remove() - cell_mod.write_manifest(out_path, config, config_sha, arm_summaries) + cell_mod.write_manifest( + out_path, config, config_sha, arm_summaries, weight_patch=patch.receipt + ) print(f"Steer cell complete. Output {out_path}, config_sha {config_sha}") return 0 @@ -646,6 +796,7 @@ def run_dose_calibration( render_fn_spec: str, gpu_ack: bool, project_context: ProjectContext | None = None, + revision: Optional[str] = None, ) -> int: guard = _require_gpu_ack(gpu_ack) if guard is not None: @@ -682,7 +833,20 @@ def run_dose_calibration( for readout in config.readouts } - model, tokenizer = _load_model_and_tokenizer(model_name, adapter) + from MechInterp.weights.errors import WeightPatchError + + try: + patch = _PatchSession(config.surface.weight_patch, revision, project_context) + model, tokenizer = _load_model_and_tokenizer( + model_name, adapter, revision, post_base_load=patch.hook + ) + except WeightPatchError as exc: + return _patch_refusal(exc) + try: + cell_mod.enforce_weight_patch_lineage(config.execution.output_path, patch.receipt) + except cell_mod.WeightPatchLineageError as exc: + print(f"Refusing to resume: {exc}") + return EXIT_PATCH_LINEAGE out_path = Path(config.execution.output_path) out_path.parent.mkdir(parents=True, exist_ok=True) summary_path = Path(config.execution.summary_path) @@ -766,6 +930,8 @@ def run_dose_calibration( } ) rec.update(_readback_for_record(readback, idx)) + if patch.digest: + rec["weight_patch_digest"] = patch.digest if grader is not None: rec.update(grader(rec)) _write_checkpoint_record(out, rec, redact_fields) @@ -776,7 +942,9 @@ def run_dose_calibration( summary["config_sha"] = config_sha with open(summary_path, "w") as f: json.dump(summary, f, indent=2) - cell_mod.write_dose_manifest(out_path, config, config_sha, run_summaries) + cell_mod.write_dose_manifest( + out_path, config, config_sha, run_summaries, weight_patch=patch.receipt + ) print( f"Dose calibration complete. Output {out_path}, summary {summary_path}, " f"config_sha {config_sha}" diff --git a/MechInterp/config.py b/MechInterp/config.py index 8017da369..d8f840975 100644 --- a/MechInterp/config.py +++ b/MechInterp/config.py @@ -25,7 +25,7 @@ import yaml from tuner.project import ProjectContext, resolve_path -from pydantic import BaseModel, Field, model_validator +from pydantic import BaseModel, ConfigDict, Field, model_validator # -------------------------------------------------------------------------- @@ -52,6 +52,39 @@ class ReadoutRef(BaseModel): path: str = Field(..., min_length=1, description="Path to a frozen direction JSON") +class WeightPatchRef(BaseModel): + """Pins an optional ``mechinterp-weight-patch/v1`` spec applied to the base + weights in memory, after the model loads and before any generation/capture. + + ``sha256`` is the sha256 of the spec file's bytes (required: the patch is + bound by content, not by path). The spec itself pins the exact base revision + and base tensor bytes. Experimental MechInterp CLI surface. + """ + + model_config = ConfigDict(extra="forbid") + + path: str = Field(..., min_length=1, description="Path to the weight-patch spec") + sha256: str = Field(..., pattern=r"^[0-9a-f]{64}$") + + +class CaptureSite(BaseModel): + """An explicit module-site activation capture (extract only). + + ``layer`` is the decoder BLOCK index, resolved with ``get_decoder_layer`` -- + the same convention as ``law.layer`` in steer cells, and NOT the + ``hidden_states`` index used by residual ``layers`` (where index ``k`` is the + output of block ``k-1`` and index 0 is the embeddings). ``module`` is a dotted + path relative to that block; ``tensor`` is the module's ``input`` (first + positional argument) or ``output``. + """ + + model_config = ConfigDict(extra="forbid") + + layer: int = Field(..., ge=0) + module: str = Field(..., pattern=r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)*$") + tensor: Literal["input", "output"] + + # -------------------------------------------------------------------------- # Steer cell # -------------------------------------------------------------------------- @@ -67,6 +100,13 @@ class SurfaceConfig(BaseModel): default=None, description="If set, the run aborts unless the computed config sha matches.", ) + weight_patch: Optional[WeightPatchRef] = Field( + default=None, + description=( + "Optional in-memory base-weight patch (see WeightPatchRef). Absent " + "leaves behavior and the config sha unchanged." + ), + ) class LawConfig(BaseModel): @@ -348,13 +388,59 @@ class ExtractConfig(BaseModel): every_k: int = 4 layers: Optional[list[int]] = None max_new_tokens: int = 48 + resume: bool = Field(default=False, description="Resume a matching per-row capture journal; otherwise output must be empty.") render_fn: str = Field( ..., description="Callable spec 'module.path:callable' returning a prompt" ) - content_end_fn: str = Field( - ..., description="Callable spec resolving the last content-token index" + content_end_fn: Optional[str] = Field( + default=None, + description=( + "Callable spec resolving the last content-token index. Required " + "unless forward_only is true." + ), + ) + use_cache: bool = Field( + default=False, + description=( + "use_cache for the teacher-forced capture forward pass. False keeps " + "historical behavior; true is needed by models whose cache-less " + "forward differs from their normal one (hybrid / KV-sharing)." + ), + ) + forward_only: bool = Field( + default=False, + description=( + "Skip generation; capture the 'anchor' family (last prompt token) " + "from one forward pass over the prompt. max_new_tokens is ignored." + ), + ) + weight_patch: Optional[WeightPatchRef] = Field( + default=None, + description="Optional in-memory base-weight patch applied before capture.", + ) + capture_sites: Optional[list[CaptureSite]] = Field( + default=None, + description=( + "Optional explicit module-site captures at the selected position " + "families. Absent leaves residual extraction unchanged." + ), ) + @model_validator(mode="after") + def _unique_sites(self) -> "ExtractConfig": + if self.forward_only: + if list(self.families) != ["anchor"]: + raise ValueError("forward_only requires families: [anchor]") + elif self.content_end_fn is None: + raise ValueError("content_end_fn is required unless forward_only is true") + if self.capture_sites is not None: + keys = [(c.layer, c.module, c.tensor) for c in self.capture_sites] + if not keys: + raise ValueError("capture_sites must be omitted or non-empty") + if len(keys) != len(set(keys)): + raise ValueError("capture_sites entries must be unique") + return self + class ProbeFitConfig(BaseModel): activations_path: str = Field( @@ -414,7 +500,20 @@ def _resolve_steer_paths( update={ "rows_path": _resolved( config.surface.rows_path, context, declaring_file - ) + ), + "weight_patch": ( + config.surface.weight_patch.model_copy( + update={ + "path": _resolved( + config.surface.weight_patch.path, + context, + declaring_file, + ) + } + ) + if config.surface.weight_patch is not None + else None + ), } ), "readouts": [ @@ -462,6 +561,17 @@ def load_extract_config( "output_dir": _resolved( config.output_dir, context, declaring_file, access="write" ), + "weight_patch": ( + config.weight_patch.model_copy( + update={ + "path": _resolved( + config.weight_patch.path, context, declaring_file + ) + } + ) + if config.weight_patch is not None + else None + ), } ) diff --git a/MechInterp/extraction/capture.py b/MechInterp/extraction/capture.py index c4e3acab8..7a95673c2 100644 --- a/MechInterp/extraction/capture.py +++ b/MechInterp/extraction/capture.py @@ -25,12 +25,17 @@ from __future__ import annotations +import contextlib +import json +import hashlib from dataclasses import dataclass, field from pathlib import Path from typing import Callable, Optional, Sequence import torch +from MechInterp.extraction.persistence import CaptureJournal, file_info, row_key, safe_key + @dataclass class PositionSpec: @@ -90,13 +95,19 @@ def extract_rows( tokenizer, rows: list[dict], render_fn: Callable[[dict], str], - content_end_fn: Callable[[torch.Tensor, int, "object"], int], + content_end_fn: Optional[Callable[[torch.Tensor, int, "object"], int]], spec: PositionSpec, out_dir: str | Path, max_new_tokens: int = 48, - row_key_fn: Callable[[dict], str] = lambda r: str(r.get("row_key", r.get("id"))), + row_key_fn: Callable[[dict], str] = row_key, save_tensors: bool = True, device: Optional[str] = None, + capture_sites: Optional[Sequence] = None, + manifest_extra: Optional[dict] = None, + use_cache: bool = False, + forward_only: bool = False, + resume: bool = False, + run_identity: Optional[dict] = None, ) -> dict: """Generate + capture hidden states for each row; write safetensors + manifest. @@ -107,6 +118,22 @@ def extract_rows( produced no usable content. spec: which positions/layers to capture. out_dir: destination directory for __.safetensors + manifest. + capture_sites: optional explicit module sites (see sites.py). Captured + during the same clean forward pass at the selected position families + only, written to __.sites.safetensors (a separate file so + residual readers never see them). Absent = residual extraction only. + manifest_extra: extra top-level manifest keys (e.g. a weight-patch receipt). + use_cache: value passed as ``use_cache`` to the teacher-forced capture + forward. Default False (the historical behavior). Set True for models + whose cache-less forward is not equivalent to their normal one (e.g. + hybrid or KV-sharing architectures). + forward_only: skip generation entirely. Only the ``anchor`` family is + valid (the last prompt token); ``content_end_fn`` is not used and + ``max_new_tokens`` is ignored. Rows record ``answer_text == ""``. + resume: persist a per-row journal and resume the same run. Requires an + explicit run_identity. Without resume, out_dir must be empty. + run_identity: source identity used by the journal (CLI supplies hashes of + local source files or a pinned Hub revision and callable file hashes). Returns the manifest dict. """ @@ -116,93 +143,212 @@ def extract_rows( out_dir.mkdir(parents=True, exist_ok=True) dev = device or (next(model.parameters()).device if save_tensors else "cpu") + site_specs = None + if capture_sites: + from MechInterp.extraction.sites import resolve_sites, to_site_specs + + site_specs = to_site_specs(capture_sites) + resolve_sites(model, site_specs) # fail before any generation + + if forward_only: + if list(spec.families) != ["anchor"]: + raise ValueError("forward_only extraction supports exactly the 'anchor' family") + elif content_end_fn is None: + raise ValueError("content_end_fn is required unless forward_only is set") + + # Validate keys and rendered inputs before any generation or artifact writes. + keys = [row_key_fn(row) for row in rows] + if any(not isinstance(key, str) or not key for key in keys): + raise ValueError("extraction row keys must be non-empty strings") + names = [safe_key(key) for key in keys] + if len(set(keys)) != len(keys) or len({name.casefold() for name in names}) != len(names): + raise ValueError("extraction requires unique row keys and unique file names") + prompts = [render_fn(row) for row in rows] + if resume and not run_identity: + raise ValueError("resumable extraction requires an explicit run_identity") + identity = { + "schema_version": "mechinterp-capture-journal/v1", + "run": run_identity, + "inputs": [{"row_key": key, "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest()} + for key, prompt in zip(keys, prompts)], + "families": list(spec.families), "layers": spec.layers, "every_k": spec.every_k, + "max_new_tokens": max_new_tokens, "use_cache": use_cache, + "forward_only": forward_only, "save_tensors": save_tensors, + "sites": [vars(site) for site in site_specs] if site_specs else [], + "manifest_extra": manifest_extra, + } row_records = [] hidden_dim = None n_hidden_states = None - for row in rows: - prompt = render_fn(row) - enc = tokenizer(prompt, return_tensors="pt") - input_ids = enc["input_ids"].to(dev) - prompt_len = input_ids.shape[1] - - gen = model.generate( - input_ids=input_ids, - attention_mask=torch.ones_like(input_ids), - max_new_tokens=max_new_tokens, - do_sample=False, - num_beams=1, - return_dict_in_generate=True, - ) - full = gen.sequences[0] - seq_total = full.shape[0] - content_end = int(content_end_fn(full, prompt_len, tokenizer)) - answered = content_end >= prompt_len - - rec = { - "row_key": row_key_fn(row), - "prompt_len": int(prompt_len), - "seq_total": int(seq_total), - "content_end": int(content_end), - "answered": bool(answered), - "answer_text": tokenizer.decode( - full[prompt_len:], skip_special_tokens=True - ), - } + with CaptureJournal(out_dir, identity, resume=resume) as journal: + for row, key, prompt, filename_key in zip(rows, keys, prompts, names): + if key in journal.records: + rec = journal.records[key] + row_records.append(rec) + hidden_dim = rec.get("hidden_dim") or hidden_dim + n_hidden_states = rec.get("n_hidden_states") or n_hidden_states + continue + enc = tokenizer(prompt, return_tensors="pt") + input_ids = enc["input_ids"].to(dev) + prompt_len = input_ids.shape[1] - if answered and save_tensors: - fwd_ids = full[: content_end + 1].unsqueeze(0) - attn = torch.ones_like(fwd_ids) - with torch.no_grad(): - out = model( - input_ids=fwd_ids, - attention_mask=attn, - output_hidden_states=True, - use_cache=False, + if forward_only: + full = input_ids[0] + seq_total = full.shape[0] + content_end = prompt_len - 1 + answered = True + else: + gen = model.generate( + input_ids=input_ids, + attention_mask=torch.ones_like(input_ids), + max_new_tokens=max_new_tokens, + do_sample=False, + num_beams=1, + return_dict_in_generate=True, ) - hs = out.hidden_states - n_hidden_states = len(hs) - hidden_dim = hs[0].shape[-1] - layers = _layer_indices(spec, n_hidden_states) - positions = resolve_capture_positions( - spec, prompt_len, content_end, content_end + 1 - ) - safe_key = rec["row_key"].replace("::", "__").replace("|", "_").replace("/", "_") - for family, idxs in positions.items(): - if not idxs: - continue - tensors = {} - for li in layers: - cols = [ - hs[li][0, p, :].float().cpu().contiguous() - for p in idxs - if p < hs[li].shape[1] - ] - if cols: - tensors[f"L{li}"] = torch.stack(cols, dim=0) - if tensors: - save_file( - tensors, str(out_dir / f"{safe_key}__{family}.safetensors") + full = gen.sequences[0] + seq_total = full.shape[0] + content_end = int(content_end_fn(full, prompt_len, tokenizer)) + answered = content_end >= prompt_len + + rec = { + "row_key": key, + "prompt_len": int(prompt_len), + "seq_total": int(seq_total), + "content_end": int(content_end), + "answered": bool(answered), + "answer_text": tokenizer.decode( + full[prompt_len:], skip_special_tokens=True + ), + } + + if answered and save_tensors: + fwd_ids = full[: content_end + 1].unsqueeze(0) + attn = torch.ones_like(fwd_ids) + site_capture = None + site_positions: dict[str, list[int]] = {} + if site_specs: + from MechInterp.extraction.sites import SiteCapture + + site_positions = resolve_capture_positions( + spec, prompt_len, content_end, content_end + 1 ) - rec["captured_families"] = list(positions.keys()) - - row_records.append(rec) - - manifest = { - "n_rows": len(rows), - "n_answered": sum(1 for r in row_records if r["answered"]), - "hidden_dim": hidden_dim, - "n_hidden_states": n_hidden_states, - "position_families": list(spec.families), - "every_k": spec.every_k, - "layers": spec.layers if spec.layers is not None else "all", - "max_new_tokens": max_new_tokens, - "persist_dtype": "float32", - "decode": "greedy", - "rows": row_records, - } - import json + union = sorted({p for idxs in site_positions.values() for p in idxs}) + if union: + site_capture = SiteCapture(model, site_specs) + with site_capture if site_capture is not None else contextlib.nullcontext(): + if site_capture is not None: + site_capture.begin(union) + with torch.no_grad(): + out = model( + input_ids=fwd_ids, + attention_mask=attn, + output_hidden_states=True, + use_cache=use_cache, + ) + hs = out.hidden_states + n_hidden_states = len(hs) + hidden_dim = hs[0].shape[-1] + layers = _layer_indices(spec, n_hidden_states) + positions = resolve_capture_positions( + spec, prompt_len, content_end, content_end + 1 + ) + rec["capture_files"] = {} + rec["hidden_dim"] = hidden_dim + rec["n_hidden_states"] = n_hidden_states + for family, idxs in positions.items(): + if not idxs: + continue + tensors = {} + for li in layers: + cols = [ + hs[li][0, p, :].float().cpu().contiguous() + for p in idxs + if p < hs[li].shape[1] + ] + if cols: + tensors[f"L{li}"] = torch.stack(cols, dim=0) + if tensors: + path = out_dir / f"{filename_key}__{family}.safetensors" + save_file(tensors, str(path)) + rec["capture_files"][family] = file_info(path) + rec["captured_families"] = list(positions.keys()) + if site_capture is not None: + rec["site_captures"] = _save_site_captures( + site_capture, site_positions, out_dir, filename_key + ) + + journal.record(rec) + row_records.append(rec) + + manifest = { + "schema_version": "mechinterp-capture/v2", + "complete": True, + "n_rows": len(rows), + "n_answered": sum(1 for r in row_records if r["answered"]), + "hidden_dim": hidden_dim, + "n_hidden_states": n_hidden_states, + "position_families": list(spec.families), + "every_k": spec.every_k, + "layers": spec.layers if spec.layers is not None else "all", + "max_new_tokens": max_new_tokens, + "persist_dtype": "float32", + "decode": "greedy", + "rows": row_records, + } + # Only a non-default choice is recorded, so default manifests keep their bytes. + if use_cache: + manifest["capture_use_cache"] = True + if forward_only: + manifest["forward_only"] = True + if site_specs: + manifest["capture_sites"] = [ + {"key": c.key, "layer": c.layer, "module": c.module, "tensor": c.tensor} + for c in site_specs + ] + manifest["capture_site_layer_convention"] = "decoder_block" + manifest["capture_site_persist_dtype"] = "float32" + if manifest_extra: + manifest.update(manifest_extra) + + journal.finalize(manifest) + return manifest + - with open(out_dir / "manifest.json", "w") as f: - json.dump(manifest, f, indent=2) - return manifest +def _save_site_captures(site_capture, family_positions, out_dir: Path, safe_key: str) -> dict: + """Write each family's selected-position site activations; return metadata.""" + from safetensors.torch import save_file + + results = site_capture.results() + meta = site_capture.metadata() + row_of = {p: i for i, p in enumerate(site_capture.positions)} + summary: dict[str, dict] = {} + for family, idxs in family_positions.items(): + if not idxs: + continue + sel = [row_of[p] for p in idxs] + tensors = {key: t[sel].contiguous() for key, t in results.items()} + file_meta = { + "layer_convention": "decoder_block", + "family": family, + "positions": json.dumps(list(idxs)), + } + save_file( + tensors, + str(out_dir / f"{safe_key}__{family}.sites.safetensors"), + metadata=file_meta, + ) + summary[family] = { + **file_info(out_dir / f"{safe_key}__{family}.sites.safetensors"), + "positions": list(idxs), + "sites": { + key: { + "shape": list(t.shape), + "persist_dtype": "float32", + "source_dtype": meta[key]["source_dtype"], + } + for key, t in tensors.items() + }, + } + return summary diff --git a/MechInterp/extraction/persistence.py b/MechInterp/extraction/persistence.py new file mode 100644 index 000000000..80ab8d820 --- /dev/null +++ b/MechInterp/extraction/persistence.py @@ -0,0 +1,148 @@ +"""Capture file names, integrity checks, and optional per-row resume journal.""" + +from __future__ import annotations + +import hashlib +import inspect +import json +import os +from pathlib import Path +import re + +from shared.utilities.run_log import RunLog + + +def capture_run_identity(model: str, revision: str | None, adapter: str | None, + render_fn, content_end_fn) -> dict: + """Bind CLI resumes to pinned Hub sources or complete local file bytes.""" + def source_identity(source, *, allow_hub): + if source is None: + return None + path = Path(source) + if path.is_dir(): + # Include tokenizer/config and all checkpoint shards. Local adapters + # include their complete file set; no revision string authenticates them. + files = sorted(p for p in path.rglob("*") if p.is_file()) + if not files: + raise ValueError("empty local source cannot identify a capture resume") + return {"path": str(path.resolve()), "files": { + str(p.relative_to(path)): file_info(p)["sha256"] for p in files}} + if not allow_hub or not revision or not re.fullmatch(r"[0-9a-f]{40}", revision): + raise ValueError("resumable capture requires a pinned Hub model or a local source directory") + return {"model": source, "revision": revision} + + def callable_identity(fn): + if fn is None: + return None + source = inspect.getsourcefile(fn) + if not source or not Path(source).is_file(): + raise ValueError("capture resume requires file-backed render/content-end callables") + return {"callable": f"{fn.__module__}:{fn.__qualname__}", + "source_sha256": file_info(Path(source))["sha256"]} + + return {"model": source_identity(model, allow_hub=True), + "revision": revision, "adapter": source_identity(adapter, allow_hub=False), + "render": callable_identity(render_fn), "content_end": callable_identity(content_end_fn)} + + +def row_key(row: dict) -> str: + value = row.get("row_key", row.get("id")) + if value is None or not str(value): + raise ValueError("extraction requires a non-empty row_key or id") + return str(value) + + +def safe_key(key: str) -> str: + """Keep simple historical names; encode unsafe names without lossy rewrites. + + The caller also rejects duplicate resulting names before writing anything. + This covers a deliberately chosen key matching an encoded key's name. + """ + reserved = {"CON", "PRN", "AUX", "NUL"} | { + f"{prefix}{i}" for prefix in ("COM", "LPT") for i in range(1, 10) + } + if re.fullmatch(r"[A-Za-z0-9_-]{1,80}", key) and key.upper() not in reserved: + return key + return "row-" + hashlib.sha256(key.encode("utf-8")).hexdigest() + + +def file_info(path: Path) -> dict: + digest = hashlib.sha256() + with path.open("rb") as stream: + # Persist tensor bytes before the journal can mark this row complete. + os.fsync(stream.fileno()) + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return {"file": path.name, "sha256": digest.hexdigest()} + + +def verified_file(root: Path, info: dict) -> Path: + name = info["file"] + if not isinstance(name, str) or Path(name).name != name or "/" in name or "\\" in name: + raise ValueError("capture manifest contains an unsafe file name") + path = root / name + if path.is_symlink() or not path.is_file(): + raise ValueError("committed capture file is missing or symlinked") + if file_info(path)["sha256"] != info["sha256"]: + raise ValueError("committed capture file hash mismatch") + return path + + +def verify_record(root: Path, record: dict) -> None: + for info in record.get("capture_files", {}).values(): + verified_file(root, info) + for info in record.get("site_captures", {}).values(): + verified_file(root, info) + + +def write_manifest(root: Path, manifest: dict) -> None: + temporary = root / "manifest.json.tmp" + with temporary.open("w", encoding="utf-8") as stream: + json.dump(manifest, stream, indent=2) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, root / "manifest.json") + + +class CaptureJournal: + """Single-writer journal. A resume verifies identity and all committed files.""" + + def __init__(self, root: Path, identity: dict, *, resume: bool): + self.root = root + self.identity = identity + self.resume = resume + self.log = None + self.records: dict[str, dict] = {} + + def __enter__(self): + self.root.mkdir(parents=True, exist_ok=True) + path = self.root / "capture.runlog.jsonl" + if any(self.root.iterdir()) and (not self.resume or not path.with_name(path.name + ".meta.json").is_file()): + raise ValueError("extraction output is non-empty; use a new directory or resume its matching journal") + if self.resume: + self.log = RunLog(path, self.identity, key_field="row_key") + try: + for line in path.read_text(encoding="utf-8").splitlines(): + record = json.loads(line) + key = record["row_key"] + if key in self.records: + raise ValueError("duplicate row key in capture journal") + verify_record(self.root, record) + self.records[key] = record + except BaseException: + self.log.close() + raise + return self + + def record(self, record: dict) -> None: + if self.log: + self.log.record(record["row_key"], record) + + def finalize(self, manifest: dict) -> None: + write_manifest(self.root, manifest) + if self.log: + self.log.finalize({"n_rows": manifest["n_rows"], "manifest": "manifest.json"}) + + def __exit__(self, *exc): + if self.log: + self.log.close() diff --git a/MechInterp/extraction/sites.py b/MechInterp/extraction/sites.py new file mode 100644 index 000000000..561cf79bc --- /dev/null +++ b/MechInterp/extraction/sites.py @@ -0,0 +1,183 @@ +"""Explicit module-site activation capture. + +A *site* is ``(layer, module, tensor)``: the ``input`` (first positional +argument) or ``output`` of a named submodule inside a decoder block. Examples +of what a recipe may name -- all supplied by config, none known to this module: +a block's ``mlp.down_proj`` input, an attention projection's output. + +``layer`` is the decoder BLOCK index resolved with ``get_decoder_layer`` (the +convention steering uses), not a ``hidden_states`` index. + +``SiteCapture`` registers hooks only for the duration of a ``with`` block and +removes every one of them on exit, including when registration or the forward +pass raises. Only the selected token positions are indexed out inside the hook, +so no per-sequence activation cache is retained. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Sequence + +import torch + +from MechInterp.intervention.hooks import get_decoder_layer + +LAYER_CONVENTION = "decoder_block" + + +@dataclass(frozen=True) +class SiteSpec: + layer: int + module: str + tensor: str # "input" | "output" + + @property + def key(self) -> str: + return f"L{self.layer}.{self.module}.{self.tensor}" + + +def to_site_specs(sites) -> list[SiteSpec]: + """Accept SiteSpec or any object/dict with layer/module/tensor.""" + out = [] + for s in sites: + if isinstance(s, SiteSpec): + out.append(s) + elif isinstance(s, dict): + out.append(SiteSpec(int(s["layer"]), str(s["module"]), str(s["tensor"]))) + else: + out.append(SiteSpec(int(s.layer), str(s.module), str(s.tensor))) + for s in out: + if s.tensor not in ("input", "output"): + raise ValueError(f"site {s.key}: tensor must be 'input' or 'output'") + if len({s.key for s in out}) != len(out): + raise ValueError("capture sites must be unique") + return out + + +def resolve_sites(model, sites: Sequence[SiteSpec]) -> dict[str, torch.nn.Module]: + """Resolve each site to its module; raise ValueError naming the bad site.""" + resolved: dict[str, torch.nn.Module] = {} + for site in sites: + try: + block = get_decoder_layer(model, site.layer) + except IndexError: + raise ValueError(f"site {site.key}: decoder block {site.layer} is out of range") from None + except AttributeError as exc: + raise ValueError(f"site {site.key}: {exc}") from None + try: + resolved[site.key] = block.get_submodule(site.module) + except AttributeError: + raise ValueError( + f"site {site.key}: block {site.layer} has no submodule {site.module!r}" + ) from None + return resolved + + +class SiteCapture: + """Context manager capturing selected token positions at explicit sites.""" + + def __init__(self, model, sites: Sequence[SiteSpec]): + self.sites = to_site_specs(sites) + self._modules = resolve_sites(model, self.sites) + self._handles: list = [] + self._positions: list[int] = [] + self._armed = False + self._captured: dict[str, torch.Tensor] = {} + self._meta: dict[str, dict] = {} + + # -- lifecycle --------------------------------------------------------- + + def __enter__(self) -> "SiteCapture": + try: + for site in self.sites: + module = self._modules[site.key] + if site.tensor == "input": + handle = module.register_forward_pre_hook( + self._pre_hook(site), with_kwargs=True + ) + else: + handle = module.register_forward_hook(self._post_hook(site)) + self._handles.append(handle) + except BaseException: + self.remove() + raise + return self + + def __exit__(self, *exc) -> None: + self.remove() + + def remove(self) -> None: + handles, self._handles = self._handles, [] + for handle in handles: + handle.remove() + self._armed = False + + # -- capture ----------------------------------------------------------- + + def begin(self, positions: Sequence[int]) -> None: + """Arm for the next forward pass: capture exactly these columns.""" + pos = sorted({int(p) for p in positions}) + if not pos or pos[0] < 0: + raise ValueError("capture positions must be a non-empty set of non-negative indices") + self._positions = pos + self._armed = True + self._captured = {} + self._meta = {} + + def _record(self, site: SiteSpec, x) -> None: + if not self._armed: + return + if not isinstance(x, torch.Tensor): + raise ValueError(f"site {site.key}: expected a tensor, got {type(x).__name__}") + if x.ndim != 3 or x.shape[0] != 1: + raise ValueError( + f"site {site.key}: expected shape [1, seq, features], got {list(x.shape)}" + ) + if site.key in self._captured: + raise ValueError(f"site {site.key}: module fired more than once in one forward pass") + if self._positions[-1] >= x.shape[1]: + raise ValueError( + f"site {site.key}: position {self._positions[-1]} outside sequence length {x.shape[1]}" + ) + index = torch.tensor(self._positions, dtype=torch.long, device=x.device) + selected = x.detach()[0].index_select(0, index) + self._captured[site.key] = selected.to("cpu", torch.float32).contiguous() + self._meta[site.key] = { + "layer": site.layer, + "module": site.module, + "tensor": site.tensor, + "source_dtype": str(x.dtype).removeprefix("torch."), + "layer_convention": LAYER_CONVENTION, + } + + def _pre_hook(self, site: SiteSpec): + def hook(module, args, kwargs): + if not args: + raise ValueError(f"site {site.key}: module was called without a positional input") + self._record(site, args[0]) + + return hook + + def _post_hook(self, site: SiteSpec): + def hook(module, args, output): + value = output + if isinstance(output, (tuple, list)) and output: + value = output[0] + self._record(site, value) + + return hook + + def results(self) -> dict[str, torch.Tensor]: + """{site key: float32 [n_positions, features]} for the armed positions.""" + missing = [s.key for s in self.sites if s.key not in self._captured] + if missing: + raise ValueError(f"sites did not fire during the forward pass: {missing}") + return dict(self._captured) + + @property + def positions(self) -> list[int]: + return list(self._positions) + + def metadata(self) -> dict[str, dict]: + return {k: dict(v) for k, v in self._meta.items()} diff --git a/MechInterp/intervention/hooks.py b/MechInterp/intervention/hooks.py index 5da47d43a..3fec90f43 100644 --- a/MechInterp/intervention/hooks.py +++ b/MechInterp/intervention/hooks.py @@ -456,7 +456,10 @@ def _readback(self, hidden, c, per_row, final_pos, columns, gain_row, pre_proj, on ~1-sigma natural projections while an ungated arm made the check vacuous (empty inactive set). """ - c64 = c.detach().to(torch.float64) + # Read both snapshots in the same canonical measurement basis. The + # write uses model dtype, but quantizing only the post-read direction + # fabricates movement for bit-identical inactive bf16 rows. + c64 = self.direction.detach().to(device=hidden.device, dtype=torch.float64) active = _resolve_active(gain_row, active_override) rows = torch.nonzero(active, as_tuple=False).squeeze(1) inactive = torch.nonzero(~active, as_tuple=False).squeeze(1) diff --git a/MechInterp/pipeline.py b/MechInterp/pipeline.py index e5c8fc03b..0caeaa5f1 100644 --- a/MechInterp/pipeline.py +++ b/MechInterp/pipeline.py @@ -253,8 +253,9 @@ def compile_stage_command( force: bool = False, ) -> list[str] | str: python = cfg.runtime.python or sys.executable - engine_root = context.engine_root if context is not None else repo_root - tuner = str(engine_root / "tuner.py") + # Module form: an installed wheel has no tuner.py script. _env_for_stage puts a + # source checkout's engine root on PYTHONPATH so `-m tuner` resolves there too. + launcher = [python, "-m", "tuner"] if stage.kind == "command": if isinstance(stage.command, list): return [str(item) for item in stage.command] @@ -262,8 +263,7 @@ def compile_stage_command( if stage.kind == "mechinterp.extract": cmd = [ - python, - tuner, + *launcher, "mechinterp", "extract", "--mi-config", @@ -283,8 +283,7 @@ def compile_stage_command( if stage.kind == "mechinterp.probe-fit": cmd = [ - python, - tuner, + *launcher, "mechinterp", "probe-fit", "--mi-config", @@ -294,8 +293,7 @@ def compile_stage_command( if stage.kind == "mechinterp.steer": cmd = [ - python, - tuner, + *launcher, "mechinterp", "steer", "--mi-config", @@ -320,8 +318,7 @@ def compile_stage_command( if stage.kind == "mechinterp.dose-calibrate": cmd = [ - python, - tuner, + *launcher, "mechinterp", "dose-calibrate", "--mi-config", @@ -329,6 +326,9 @@ def compile_stage_command( "--model", _stage_model(cfg, stage), ] + revision = _stage_model_revision(cfg, stage) + if revision: + cmd.extend(["--model-revision", revision]) adapter = _stage_adapter(cfg, stage) render_fn = _execution_render_fn(stage, repo_root, context) if adapter: @@ -341,8 +341,7 @@ def compile_stage_command( if stage.kind == "mechinterp.score-gates": cmd = [ - python, - tuner, + *launcher, "mechinterp", "score-gates", "--gates-config", @@ -410,6 +409,10 @@ def _env_for_stage( ) -> dict[str, str]: env = {**os.environ, **cfg.runtime.env, **stage.env} paths = [str(repo_root / p) if not Path(p).is_absolute() else p for p in cfg.runtime.pythonpath] + engine_root = context.engine_root if context is not None else repo_root + if (stage.kind != "command" and (Path(engine_root) / "tuner.py").is_file() + and (Path(engine_root) / "pyproject.toml").is_file()): + paths = [str(engine_root)] + [p for p in paths if p != str(engine_root)] if paths: env["PYTHONPATH"] = os.pathsep.join(paths + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else [])) if context is not None: diff --git a/MechInterp/weights/__init__.py b/MechInterp/weights/__init__.py new file mode 100644 index 000000000..f4c8a94d1 --- /dev/null +++ b/MechInterp/weights/__init__.py @@ -0,0 +1,13 @@ +"""Generic weight-patch capability for MechInterp (experimental, CLI-only). + + spec.py the declarative ``mechinterp-weight-patch/v1`` schema + safetensors_io strict pickle-free safetensors header parsing + byte hashing + checkpoint.py inspect/bind a LOCAL safetensors checkpoint + patch.py validate + apply patch operations (pure, transactional) + runtime.py in-memory application to a loaded torch module (revertable) + export.py create-only export of an exact modified checkpoint + manifest + +Nothing here names a model, tensor, direction or dataset: every selection, +shape, value and restriction comes from the spec and its payload. Importing the +package does not import torch; only patch/runtime/export do. +""" diff --git a/MechInterp/weights/checkpoint.py b/MechInterp/weights/checkpoint.py new file mode 100644 index 000000000..9066cd59a --- /dev/null +++ b/MechInterp/weights/checkpoint.py @@ -0,0 +1,341 @@ +"""Inspect and bind a LOCAL safetensors checkpoint (no download, no pickle). + +A checkpoint is either one ``.safetensors`` file or a directory holding +``model.safetensors.index.json`` + its shards (or a single ``model.safetensors``). +Everything is validated structurally before any byte is trusted: + + * shard names in the index must be plain file names (no separators, no ``..``), + * no symlinks unless the spec opts in, and then only to regular files, + * every shard header must parse strictly (see safetensors_io.read_header), + * the index ``weight_map`` and the shard headers must agree exactly + (no missing, extra, or duplicated tensors). + +Revision binding. A bare revision string cannot be authenticated from file +bytes, so the binding has two independent legs: (1) exact content pins +(``base.index_sha256``/``base.files_sha256`` here, plus per-tensor byte hashes in +the spec), and (2) local revision evidence when the layout carries it (a Hugging +Face snapshot directory name, or ``.cache/huggingface/download/*.metadata`` +commit lines). Any contradicting evidence refuses; with no evidence the content +pins must be present. +""" + +from __future__ import annotations + +import fnmatch +import os +import re +import stat +from dataclasses import dataclass, field +from pathlib import Path +from typing import Optional + +from MechInterp.weights.errors import WeightPatchError +from MechInterp.weights.safetensors_io import ( + SafetensorsFile, + TensorEntry, + file_sha256, + hash_file_with_regions, + read_header, + strict_json_loads, +) + +INDEX_NAME = "model.safetensors.index.json" +SINGLE_NAME = "model.safetensors" +_REV40 = re.compile(r"^[0-9a-f]{40}$") +_MAX_INDEX_BYTES = 64 * 1024 * 1024 + + +@dataclass +class LocalCheckpoint: + root: Path # directory containing the weight files + files: dict[str, SafetensorsFile] # file name -> parsed header + tensor_to_file: dict[str, str] + index_path: Optional[Path] + index_total_size: Optional[int] + is_single_file_input: bool + _hash_cache: dict[str, tuple[str, dict[str, str]]] = field(default_factory=dict) + + def entry(self, tensor: str) -> tuple[SafetensorsFile, TensorEntry]: + fname = self.tensor_to_file.get(tensor) + if fname is None: + raise WeightPatchError("binding", f"tensor {tensor!r} is not in this checkpoint") + sf = self.files[fname] + return sf, sf.entries[tensor] + + def file_hashes(self, fname: str) -> tuple[str, dict[str, str]]: + """(whole-file sha256, per-tensor region sha256), computed once.""" + if fname not in self._hash_cache: + self._hash_cache[fname] = hash_file_with_regions(self.files[fname]) + return self._hash_cache[fname] + + def tensor_sha256(self, tensor: str) -> str: + fname = self.tensor_to_file[tensor] + return self.file_hashes(fname)[1][tensor] + + def index_or_file_sha256(self) -> str: + if self.index_path is not None: + return file_sha256(self.index_path) + (only,) = self.files.values() + return self.file_hashes(only.path.name)[0] + + def total_tensor_bytes(self) -> int: + return sum(e.nbytes for sf in self.files.values() for e in sf.entries.values()) + + +def _check_regular(path: Path, root_real: Path, allow_symlinks: bool, label: str) -> None: + try: + st = os.lstat(path) + except OSError: + raise WeightPatchError("path", f"{label}: file does not exist") from None + if stat.S_ISLNK(st.st_mode): + if not allow_symlinks: + raise WeightPatchError( + "path", f"{label}: symlinked weight files are refused (base.allow_symlinked_files)" + ) + try: + target = path.resolve(strict=True) + except OSError: + raise WeightPatchError("path", f"{label}: dangling symlink") from None + if not target.is_file(): + raise WeightPatchError("path", f"{label}: symlink target is not a regular file") + return + if not stat.S_ISREG(st.st_mode): + raise WeightPatchError("path", f"{label}: not a regular file") + # A regular leaf can still sit behind a symlinked directory component. + if not allow_symlinks and path.resolve(strict=True).parent != root_real: + raise WeightPatchError("path", f"{label}: resolves outside the checkpoint directory") + + +def _plain_name(name: str) -> bool: + return ( + isinstance(name, str) + and name not in {"", ".", ".."} + and "/" not in name + and "\\" not in name + and "\x00" not in name + and not name.startswith(".") + and name.endswith(".safetensors") + ) + + +def open_checkpoint(path: str | Path, *, allow_symlinked_files: bool = False) -> LocalCheckpoint: + p = Path(path) + if not p.exists(): + raise WeightPatchError("path", "checkpoint path does not exist") + if p.is_file(): + root = p.parent + root_real = root.resolve(strict=True) + if not _plain_name(p.name): + raise WeightPatchError("path", "a checkpoint file must be a plain .safetensors name") + _check_regular(p, root_real, allow_symlinked_files, p.name) + sf = read_header(p) + return LocalCheckpoint( + root, {p.name: sf}, {name: p.name for name in sf.entries}, None, None, True + ) + if not p.is_dir(): + raise WeightPatchError("path", "checkpoint path is neither a file nor a directory") + root = p + root_real = root.resolve(strict=True) + + index_path = root / INDEX_NAME + single_path = root / SINGLE_NAME + has_index = os.path.lexists(index_path) + has_single = os.path.lexists(single_path) + if has_index and has_single: + raise WeightPatchError( + "index", f"both {INDEX_NAME} and {SINGLE_NAME} exist; layout is ambiguous" + ) + if not has_index and not has_single: + raise WeightPatchError("index", f"no {INDEX_NAME} or {SINGLE_NAME} in checkpoint directory") + + if has_single: + _check_regular(single_path, root_real, allow_symlinked_files, SINGLE_NAME) + sf = read_header(single_path) + return LocalCheckpoint( + root, {SINGLE_NAME: sf}, {n: SINGLE_NAME for n in sf.entries}, None, None, False + ) + + _check_regular(index_path, root_real, allow_symlinked_files, INDEX_NAME) + if index_path.stat().st_size > _MAX_INDEX_BYTES: + raise WeightPatchError("index", f"{INDEX_NAME} is too large") + index = strict_json_loads(index_path.read_bytes()) + if not isinstance(index, dict) or not isinstance(index.get("weight_map"), dict): + raise WeightPatchError("index", f"{INDEX_NAME}: weight_map must be an object") + weight_map = index["weight_map"] + if not weight_map: + raise WeightPatchError("index", f"{INDEX_NAME}: weight_map is empty") + total_size = None + meta = index.get("metadata") + if isinstance(meta, dict) and isinstance(meta.get("total_size"), int) and not isinstance( + meta.get("total_size"), bool + ): + total_size = meta["total_size"] + for tensor, fname in weight_map.items(): + if not isinstance(tensor, str) or not tensor: + raise WeightPatchError("index", f"{INDEX_NAME}: invalid tensor name") + if not _plain_name(fname): + raise WeightPatchError( + "index", f"{INDEX_NAME}: shard name for {tensor!r} must be a plain .safetensors file name" + ) + + files: dict[str, SafetensorsFile] = {} + for fname in sorted(set(weight_map.values())): + fpath = root / fname + _check_regular(fpath, root_real, allow_symlinked_files, fname) + files[fname] = read_header(fpath) + + for tensor, fname in weight_map.items(): + if tensor not in files[fname].entries: + raise WeightPatchError( + "index", f"{INDEX_NAME} maps {tensor!r} to {fname}, which does not contain it" + ) + for fname, sf in files.items(): + extra = [t for t in sf.entries if weight_map.get(t) != fname] + if extra: + raise WeightPatchError( + "index", f"{fname} holds tensors not mapped to it by the index: {extra[:3]}" + ) + return LocalCheckpoint(root, files, dict(weight_map), index_path, total_size, False) + + +def revision_evidence(ckpt: LocalCheckpoint) -> list[dict]: + """Local, non-network evidence about which revision this directory holds.""" + evidence: list[dict] = [] + root_real = ckpt.root.resolve(strict=True) + if root_real.parent.name == "snapshots" and _REV40.match(root_real.name): + evidence.append({"source": "hf_snapshot_directory", "value": root_real.name}) + for fname in sorted(ckpt.files): + meta = ckpt.root / ".cache" / "huggingface" / "download" / f"{fname}.metadata" + try: + if meta.is_file() and meta.stat().st_size <= 4096: + first = meta.read_text(encoding="utf-8", errors="strict").splitlines() + if first and _REV40.match(first[0].strip()): + evidence.append( + {"source": f"hf_download_metadata:{fname}", "value": first[0].strip()} + ) + except (OSError, UnicodeDecodeError): + continue + return evidence + + +def verify_binding(spec, ckpt: LocalCheckpoint) -> dict: + """Verify the spec's source declaration against this local checkpoint. + + Refuses on any contradiction. Returns a report of what was proven. + """ + base = spec.base + report: dict = {"revision": base.revision, "model_id": base.model_id} + + content_pinned = False + if base.index_sha256 is not None: + actual = ckpt.index_or_file_sha256() + if actual != base.index_sha256: + raise WeightPatchError("binding", "checkpoint index/file sha256 does not match base.index_sha256") + content_pinned = True + report["index_sha256"] = ckpt.index_or_file_sha256() if content_pinned else None + + if base.files_sha256 is not None: + if set(base.files_sha256) != set(ckpt.files): + raise WeightPatchError( + "binding", + "base.files_sha256 must list exactly the checkpoint's weight files " + f"(declared {sorted(base.files_sha256)}, found {sorted(ckpt.files)})", + ) + for fname, expected in base.files_sha256.items(): + if ckpt.file_hashes(fname)[0] != expected: + raise WeightPatchError("binding", f"file sha256 mismatch for {fname}") + content_pinned = True + + evidence = revision_evidence(ckpt) + for item in evidence: + item["matches"] = item["value"] == base.revision + report["revision_evidence"] = evidence + if any(not item["matches"] for item in evidence): + raise WeightPatchError( + "binding", "local revision evidence contradicts the declared base.revision" + ) + if not content_pinned and not evidence: + raise WeightPatchError( + "binding", + "cannot bind the declared revision: provide base.index_sha256 or base.files_sha256, " + "or use a checkpoint layout that carries revision evidence", + ) + + for name, pin in base.tensors.items(): + if name not in ckpt.tensor_to_file: + raise WeightPatchError("binding", f"targeted tensor {name!r} is not in the checkpoint") + _, entry = ckpt.entry(name) + if entry.torch_dtype != pin.dtype or list(entry.shape) != pin.shape: + raise WeightPatchError( + "base_hash_mismatch", + f"{name}: checkpoint is {entry.torch_dtype}{list(entry.shape)}, " + f"spec pins {pin.dtype}{pin.shape}", + ) + if ckpt.tensor_sha256(name) != pin.sha256: + raise WeightPatchError("base_hash_mismatch", f"{name}: base tensor bytes differ from the pin") + report["content_pinned"] = content_pinned + report["targeted_tensors_verified"] = len(base.tensors) + return report + + +def inspect_checkpoint(request, ckpt: Optional[LocalCheckpoint] = None) -> dict: + """Build the ``weights-inspect`` report (JSON-serializable).""" + ckpt = ckpt or open_checkpoint( + request.checkpoint, allow_symlinked_files=request.allow_symlinked_files + ) + dtypes: dict[str, int] = {} + for sf in ckpt.files.values(): + for e in sf.entries.values(): + dtypes[e.torch_dtype] = dtypes.get(e.torch_dtype, 0) + 1 + total = ckpt.total_tensor_bytes() + report: dict = { + "schema_version": request.schema_version, + "layout": "single_file" if ckpt.index_path is None else "sharded_index", + "n_files": len(ckpt.files), + "n_tensors": len(ckpt.tensor_to_file), + "tensor_bytes": total, + "dtype_counts": dict(sorted(dtypes.items())), + "index_total_size_declared": ckpt.index_total_size, + "index_total_size_matches": ( + None if ckpt.index_total_size is None else ckpt.index_total_size == total + ), + "revision_evidence": revision_evidence(ckpt), + "files": [], + "tensors": [], + } + for fname, sf in sorted(ckpt.files.items()): + item = {"name": fname, "size": sf.size, "n_tensors": len(sf.entries)} + if request.hash_files: + item["sha256"] = ckpt.file_hashes(fname)[0] + report["files"].append(item) + if ckpt.index_path is not None: + report["index_sha256"] = file_sha256(ckpt.index_path) + + names = sorted( + n + for n in ckpt.tensor_to_file + if any(fnmatch.fnmatchcase(n, pat) for pat in request.tensors) + ) + report["n_tensors_matched"] = len(names) + report["listing_truncated"] = len(names) > request.max_listed_tensors + snippet: dict[str, dict] = {} + for name in names[: request.max_listed_tensors]: + sf, entry = ckpt.entry(name) + item = { + "name": name, + "file": sf.path.name, + "dtype": entry.torch_dtype, + "shape": list(entry.shape), + "nbytes": entry.nbytes, + } + if request.hash_tensors: + item["sha256"] = ckpt.tensor_sha256(name) + snippet[name] = {"dtype": entry.torch_dtype, "shape": list(entry.shape), "sha256": item["sha256"]} + report["tensors"].append(item) + if snippet: + report["base_tensors_snippet"] = snippet + if request.projections: + from MechInterp.weights.projection import run_projections + + report["projections"] = run_projections(request, ckpt) + return report diff --git a/MechInterp/weights/errors.py b/MechInterp/weights/errors.py new file mode 100644 index 000000000..c8e121ffe --- /dev/null +++ b/MechInterp/weights/errors.py @@ -0,0 +1,32 @@ +"""Closed error vocabulary for the weight-patch capability.""" + +from __future__ import annotations + +ERROR_CODES = frozenset( + { + "schema", # malformed or unsupported spec/inspect document + "path", # missing/unsafe/escaping path, symlink, non-regular file + "index", # malformed safetensors header or checkpoint index + "binding", # declared source/revision/hash does not match local bytes + "base_hash_mismatch", # targeted base tensor bytes differ from the pin + "payload", # payload hash/shape/dtype/index problem + "nonfinite", # NaN/Inf in a payload, base, or result + "budget", # patch exceeds a declared finite budget + "output_exists", # export destination already exists + "apply", # in-memory application failed (rolled back) + } +) + + +class WeightPatchError(Exception): + """A refusal. ``code`` is one of ``ERROR_CODES``; nothing was applied.""" + + def __init__(self, code: str, message: str): + if code not in ERROR_CODES: # pragma: no cover - programming error + raise ValueError(f"unknown weight-patch error code {code!r}") + super().__init__(message) + self.code = code + self.message = message + + def __str__(self) -> str: + return f"[{self.code}] {self.message}" diff --git a/MechInterp/weights/export.py b/MechInterp/weights/export.py new file mode 100644 index 000000000..f9e26df81 --- /dev/null +++ b/MechInterp/weights/export.py @@ -0,0 +1,294 @@ +"""Create-only export of an exact modified checkpoint plus a lineage manifest. + +Because patching never changes a tensor's dtype or shape, the output keeps every +shard's header and layout byte-for-byte: each shard is copied and ONLY the byte +ranges of modified tensors are overwritten. Untouched tensors (and untouched +shards entirely) are therefore preserved exactly, and this is verified by +re-hashing the output against the base. The checkpoint is staged in a sibling +directory and published only after verification; an existing destination is +refused, never overwritten. Filesystems without exclusive directory rename use +an exclusively created directory, verified file copies and a completion manifest +written last. A killed fallback export can leave an incomplete directory without +that manifest; consumers must require the manifest before using an export. +""" + +from __future__ import annotations + +import fnmatch +import ctypes +import errno +import hashlib +import json +import os +import shutil +import stat +import sys +import tempfile +from pathlib import Path + +from MechInterp.weights.checkpoint import ( + INDEX_NAME, + LocalCheckpoint, +) +from MechInterp.weights.errors import WeightPatchError +from MechInterp.weights.patch import PatchPlan, tensor_to_bytes +from MechInterp.weights.safetensors_io import ( + fsync_path, + hash_file_with_regions, + read_header, +) +from MechInterp.weights.spec import WeightPatchSpec, canonical_sha256 + +MANIFEST_NAME = "mechinterp-weight-export.manifest.json" +_COPY_CHUNK = 8 * 1024 * 1024 + + +def _copy_file(src: Path, dst: Path) -> None: + with open(src, "rb") as fin, open(dst, "xb") as fout: + for chunk in iter(lambda: fin.read(_COPY_CHUNK), b""): + fout.write(chunk) + fout.flush() + os.fsync(fout.fileno()) + + +def _sidecars(spec: WeightPatchSpec, ckpt: LocalCheckpoint, root_real: Path) -> list[Path]: + cfg = spec.export + chosen: list[Path] = [] + for entry in sorted(os.listdir(ckpt.root)): + if entry.endswith(".safetensors") or entry == MANIFEST_NAME: + continue + if not any(fnmatch.fnmatchcase(entry, pat) for pat in cfg.sidecar_files): + continue + path = ckpt.root / entry + try: + st = os.lstat(path) + except OSError: + continue + if stat.S_ISLNK(st.st_mode): + target = path.resolve(strict=False) + if not spec.base.allow_symlinked_files or not target.is_file(): + raise WeightPatchError("path", f"sidecar {entry!r} is a disallowed or broken symlink") + st = os.stat(target) + if not stat.S_ISREG(st.st_mode): + continue + if st.st_size > cfg.max_sidecar_bytes: + raise WeightPatchError("path", f"sidecar {entry!r} exceeds export.max_sidecar_bytes") + chosen.append(path) + return chosen + + +def _sha_of(path: Path) -> str: + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(_COPY_CHUNK), b""): + h.update(chunk) + return h.hexdigest() + + +def _rename_create_only(source: Path, destination: Path) -> None: + """Publish atomically without replacing even an empty racing directory.""" + if sys.platform == "win32": + # Windows rename refuses an existing destination, unlike POSIX rename. + os.rename(source, destination) + return + libc = ctypes.CDLL(None, use_errno=True) + if sys.platform.startswith("linux") and hasattr(libc, "renameat2"): + rename = libc.renameat2 + rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint] + rename.restype = ctypes.c_int + result = rename(-100, os.fsencode(source), -100, os.fsencode(destination), 1) # RENAME_NOREPLACE + elif sys.platform == "darwin" and hasattr(libc, "renamex_np"): + rename = libc.renamex_np + rename.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint] + rename.restype = ctypes.c_int + result = rename(os.fsencode(source), os.fsencode(destination), 4) # RENAME_EXCL + else: + raise WeightPatchError("path", "atomic create-only directory publication is unsupported on this platform") + if result != 0: + code = ctypes.get_errno() + if code in (errno.EEXIST, errno.ENOTEMPTY): + raise WeightPatchError("output_exists", "export destination appeared during export") + raise OSError(code, os.strerror(code)) + + +def _publish_manifest_last(source: Path, destination: Path, manifest: dict) -> None: + """Create-only publication for filesystems without RENAME_NOREPLACE. + + Directory creation arbitrates concurrent exporters. No existing file is + opened for writing. The manifest appears only after all copied bytes have + been fsynced and checked against the staged export's recorded hashes. + """ + try: + destination.mkdir(mode=0o700) + except FileExistsError as exc: + raise WeightPatchError("output_exists", "export destination appeared during publication") from exc + created: list[Path] = [] + try: + expected = {**manifest["output"]["weight_files"], **manifest["output"]["copied_files"]} + for name, info in sorted(expected.items()): + src, dst = source / name, destination / name + with dst.open("xb") as sink: + created.append(dst) + with src.open("rb") as stream: + shutil.copyfileobj(stream, sink, length=_COPY_CHUNK) + sink.flush() + os.fsync(sink.fileno()) + if _sha_of(dst) != info["sha256"]: + raise WeightPatchError("apply", f"{name}: published bytes differ from the verified export") + manifest["publication"] = {"method": "exclusive_directory_manifest_last", "atomic_directory_rename": False} + with (destination / MANIFEST_NAME).open("x", encoding="utf-8") as sink: + created.append(destination / MANIFEST_NAME) + json.dump(manifest, sink, indent=2, sort_keys=True) + sink.write("\n") + sink.flush() + os.fsync(sink.fileno()) + try: + fsync_path(destination) + except OSError: + pass # Some supported filesystems cannot fsync a directory. + except BaseException: + # Never remove a competing writer's unrecognized files or directory. + for path in reversed(created): + try: + path.unlink() + except OSError: + pass + try: + destination.rmdir() + except OSError: + pass + raise + shutil.rmtree(source) + + +def export_checkpoint( + spec: WeightPatchSpec, + spec_sha256: str, + plan: PatchPlan, + ckpt: LocalCheckpoint, + binding_report: dict, +) -> dict: + """Write the patched checkpoint to ``spec.export.output_dir``; return the manifest.""" + if spec.export is None: + raise WeightPatchError("schema", "the spec has no export block") + final = Path(spec.export.output_dir) + if os.path.lexists(final): + raise WeightPatchError("output_exists", "export destination already exists; refusing to overwrite") + parent = final.parent + parent.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix=f".{final.name}.partial-", dir=parent)) + try: + manifest = _build(spec, spec_sha256, plan, ckpt, binding_report, staging) + if os.path.lexists(final): # re-check immediately before the rename + raise WeightPatchError("output_exists", "export destination appeared during export") + fsync_path(staging) + try: + _rename_create_only(staging, final) + except OSError as exc: + unsupported = {errno.EINVAL, errno.ENOSYS, errno.EOPNOTSUPP, errno.ENOTSUP} + if exc.errno not in unsupported: + raise + _publish_manifest_last(staging, final, manifest) + try: + fsync_path(parent) + except OSError: # some filesystems (e.g. drvfs/exFAT) cannot fsync a directory + pass + return manifest + except BaseException: + shutil.rmtree(staging, ignore_errors=True) + raise + + +def _build(spec, spec_sha256, plan: PatchPlan, ckpt: LocalCheckpoint, binding_report, staging: Path) -> dict: + root_real = ckpt.root.resolve(strict=True) + modified_by_file: dict[str, list[str]] = {} + for name in plan.modified: + modified_by_file.setdefault(ckpt.tensor_to_file[name], []).append(name) + + out_files: dict[str, dict] = {} + for fname, sf in sorted(ckpt.files.items()): + src_whole, src_regions = ckpt.file_hashes(fname) + dst = staging / fname + _copy_file(sf.path, dst) + names = modified_by_file.get(fname, []) + if names: + with open(dst, "r+b") as fh: + for name in names: + entry = sf.entries[name] + start, _ = sf.absolute_range(entry) + fh.seek(start) + data = tensor_to_bytes(plan.modified[name].new_tensor) + if len(data) != entry.nbytes: + raise WeightPatchError("apply", f"{name}: patched byte length changed") + fh.write(data) + fh.flush() + os.fsync(fh.fileno()) + # Readback verification against the base, whole shard. + dst_sf = read_header(dst) + with open(sf.path, "rb") as a, open(dst, "rb") as b: + if a.read(sf.data_start) != b.read(sf.data_start): + raise WeightPatchError("apply", f"{fname}: output header differs from the base header") + if dst_sf.entries != sf.entries: + raise WeightPatchError("apply", f"{fname}: output tensor layout differs from the base") + dst_whole, dst_regions = hash_file_with_regions(dst_sf) + for tname, region in dst_regions.items(): + if tname in plan.modified: + if region != plan.modified[tname].after_sha256: + raise WeightPatchError("apply", f"{tname}: output bytes differ from the plan") + elif region != src_regions[tname]: + raise WeightPatchError("apply", f"{tname}: untouched tensor changed in the output") + if not names and dst_whole != src_whole: + raise WeightPatchError("apply", f"{fname}: unmodified shard is not byte-identical") + out_files[fname] = {"sha256": dst_whole, "size": dst_sf.size, "modified_tensors": sorted(names)} + + copied: dict[str, dict] = {} + if ckpt.index_path is not None: + shutil.copyfile(ckpt.index_path, staging / INDEX_NAME) + copied[INDEX_NAME] = {"sha256": _sha_of(staging / INDEX_NAME)} + for path in _sidecars(spec, ckpt, root_real): + if path.name == INDEX_NAME: + continue + shutil.copyfile(path, staging / path.name) + copied[path.name] = {"sha256": _sha_of(staging / path.name)} + + try: + import torch + + versions = {"python": sys.version.split()[0], "torch": torch.__version__} + except Exception: # pragma: no cover + versions = {"python": sys.version.split()[0]} + manifest = { + "schema_version": "mechinterp-weight-export/v1", + "patch_digest": plan.patch_digest(), + "spec": { + "sha256": spec_sha256, + "canonical_sha256": canonical_sha256(spec), + "description": spec.description, + }, + "payload": {"sha256": plan.payload_sha256}, + "base": { + "model_id": spec.base.model_id, + "revision": spec.base.revision, + "binding": binding_report, + "files": {f: {"sha256": ckpt.file_hashes(f)[0]} for f in sorted(ckpt.files)}, + }, + "budget": spec.budget.model_dump(mode="json"), + "totals": { + "tensors_modified": len(plan.modified), + "entries_changed": plan.total_entries_changed, + "noop": plan.is_noop, + }, + "tensors": [ + {**t.summary(), "file": ckpt.tensor_to_file[t.name]} + for _, t in sorted(plan.targeted.items()) + ], + "output": {"weight_files": out_files, "copied_files": copied}, + "engine": versions, + } + manifest_path = staging / MANIFEST_NAME + with open(manifest_path, "x", encoding="utf-8") as fh: + json.dump(manifest, fh, indent=2, sort_keys=True) + fh.write("\n") + fh.flush() + os.fsync(fh.fileno()) + return manifest diff --git a/MechInterp/weights/patch.py b/MechInterp/weights/patch.py new file mode 100644 index 000000000..a1047ff8d --- /dev/null +++ b/MechInterp/weights/patch.py @@ -0,0 +1,413 @@ +"""Pure patch planning: validate a spec against base tensors, compute new bytes. + +``build_plan`` never mutates anything. It reads each targeted base tensor through +a caller-supplied ``read_tensor``, checks it against the spec's pinned dtype / +shape / byte hash, applies the operations to private copies, and enforces the +declared finite budget on the REALIZED result (entries whose stored value +actually changed, per-tensor relative Frobenius norm of the realized delta). +Any violation raises before a single byte is written anywhere, so application +(in memory or to disk) is all-or-nothing by construction. + +Zero-patch semantics: an operation only replaces entries whose new value (after +casting to the tensor dtype) differs numerically from the old one, so a +zero-valued patch leaves every byte of the tensor identical and is a true no-op. +""" + +from __future__ import annotations + +import hashlib +import json +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, Optional + +import torch + +from MechInterp.weights.errors import WeightPatchError +from MechInterp.weights.safetensors_io import ( + FLOAT_TORCH_NAMES, + file_sha256, + read_header, + read_region, +) +from MechInterp.weights.spec import Operation, WeightPatchSpec + +if sys.byteorder != "little": # pragma: no cover - safetensors is little-endian + raise ImportError("weight patching requires a little-endian host") + +_CHUNK_ELEMENTS = 4 * 1024 * 1024 +_DIRECTION_NORM_TOL = 1e-3 + + +def torch_dtype_name(dtype: torch.dtype) -> str: + return str(dtype).removeprefix("torch.") + + +# -------------------------------------------------------------------------- +# Byte-exact hashing and (de)serialization +# -------------------------------------------------------------------------- + + +def tensor_bytes_view(t: torch.Tensor): + """Flat uint8 numpy view of a CPU tensor's stored dtype bytes.""" + flat = t.detach().to("cpu").contiguous().reshape(-1) + return flat.view(torch.uint8).numpy() + + +def tensor_sha256(t: torch.Tensor) -> str: + """sha256 of the tensor's raw little-endian dtype bytes (bf16 included).""" + flat = t.detach().to("cpu").contiguous().reshape(-1) + h = hashlib.sha256() + if flat.numel(): + step = max(1, _CHUNK_ELEMENTS) + for i in range(0, flat.numel(), step): + h.update(flat[i : i + step].view(torch.uint8).numpy()) + return h.hexdigest() + + +def tensor_to_bytes(t: torch.Tensor) -> bytes: + flat = t.detach().to("cpu").contiguous().reshape(-1) + return flat.view(torch.uint8).numpy().tobytes() if flat.numel() else b"" + + +def buffer_to_tensor(buf: bytearray, dtype_name: str, shape: tuple[int, ...]) -> torch.Tensor: + dtype = getattr(torch, dtype_name) + if len(buf) == 0: + return torch.empty(shape, dtype=dtype) + return torch.frombuffer(buf, dtype=dtype).reshape(shape) + + +def _is_finite(t: torch.Tensor) -> bool: + return bool(torch.isfinite(t).all().item()) if t.numel() else True + + +def _sq_diff_sum(a: torch.Tensor, b: Optional[torch.Tensor]) -> float: + fa = a.reshape(-1) + fb = b.reshape(-1) if b is not None else None + total = 0.0 + for i in range(0, fa.numel(), _CHUNK_ELEMENTS): + x = fa[i : i + _CHUNK_ELEMENTS].to(torch.float64) + if fb is not None: + x = x - fb[i : i + _CHUNK_ELEMENTS].to(torch.float64) + total += float((x * x).sum().item()) + return total + + +# -------------------------------------------------------------------------- +# Payload +# -------------------------------------------------------------------------- + + +@dataclass +class Payload: + sha256: str + arrays: dict[str, torch.Tensor] + + +def _op_array_names(spec: WeightPatchSpec) -> set[str]: + return {name for op in spec.operations for name in op.arrays.values()} + + +def load_payload(spec: WeightPatchSpec) -> Payload: + """Verify and load the safetensors payload named by the spec.""" + path = Path(spec.payload.path) + try: + if not path.is_file(): + raise WeightPatchError("path", "payload file does not exist") + if path.is_symlink(): + raise WeightPatchError("path", "payload must not be a symlink") + size = path.stat().st_size + except OSError: + raise WeightPatchError("path", "payload file is not accessible") from None + if size > spec.budget.max_payload_bytes: + raise WeightPatchError("budget", "payload exceeds budget.max_payload_bytes") + if file_sha256(path) != spec.payload.sha256: + raise WeightPatchError("payload", "payload sha256 does not match payload.sha256") + sf = read_header(path) + needed = _op_array_names(spec) + missing = needed - set(sf.entries) + if missing: + raise WeightPatchError("payload", f"payload lacks arrays: {sorted(missing)[:3]}") + extra = set(sf.entries) - needed + if extra: + raise WeightPatchError( + "payload", f"payload holds arrays no operation references: {sorted(extra)[:3]}" + ) + arrays: dict[str, torch.Tensor] = {} + for name in sorted(needed): + entry = sf.entries[name] + if entry.torch_dtype not in FLOAT_TORCH_NAMES and entry.torch_dtype not in {"int32", "int64"}: + raise WeightPatchError("payload", f"array {name!r} has unsupported dtype {entry.torch_dtype}") + t = buffer_to_tensor(read_region(sf, entry), entry.torch_dtype, entry.shape) + if t.is_floating_point() and not _is_finite(t): + raise WeightPatchError("nonfinite", f"payload array {name!r} contains NaN/Inf") + arrays[name] = t + return Payload(spec.payload.sha256, arrays) + + +# -------------------------------------------------------------------------- +# Operations +# -------------------------------------------------------------------------- + + +def _resolve_indices( + op: Operation, role: str, payload: Payload, dim: int, max_count: int +) -> Optional[torch.Tensor]: + inline = getattr(op, role) + if inline is not None: + idx = torch.tensor(inline, dtype=torch.int64) if inline else None + if idx is None: + raise WeightPatchError("payload", f"op {op.id}: {role} must not be empty") + elif role in op.arrays: + raw = payload.arrays[op.arrays[role]] + if raw.dtype not in (torch.int32, torch.int64) or raw.ndim != 1 or raw.numel() == 0: + raise WeightPatchError("payload", f"op {op.id}: {role} array must be a non-empty 1-D integer array") + idx = raw.to(torch.int64) + else: + return None + if idx.numel() > max_count: + raise WeightPatchError("budget", f"op {op.id}: {role} has {idx.numel()} indices (> max_index_count)") + if int(idx.min()) < 0 or int(idx.max()) >= dim: + raise WeightPatchError("payload", f"op {op.id}: {role} index out of range [0, {dim})") + if int(torch.unique(idx).numel()) != idx.numel(): + raise WeightPatchError("payload", f"op {op.id}: {role} indices are not distinct") + return idx + + +def _vector(op: Operation, role: str, payload: Payload, length: int) -> torch.Tensor: + t = payload.arrays[op.arrays[role]] + if t.ndim != 1 or t.numel() != length: + raise WeightPatchError( + "payload", f"op {op.id}: array {role!r} must be 1-D of length {length}, got {tuple(t.shape)}" + ) + return t + + +def _gather(w: torch.Tensor, rows, cols) -> torch.Tensor: + sub = w + if rows is not None: + sub = sub.index_select(0, rows) + if cols is not None: + sub = sub.index_select(1, cols) + return sub.clone() if sub is w else sub + + +def _scatter(w: torch.Tensor, rows, cols, new: torch.Tensor) -> None: + if rows is not None and cols is not None: + w[rows[:, None], cols[None, :]] = new + elif rows is not None: + w[rows] = new + elif cols is not None: + w[:, cols] = new + else: + w.copy_(new) + + +def _apply_operation( + w: torch.Tensor, op: Operation, payload: Payload, max_index_count: int +) -> None: + """Apply one operation to ``w`` (a private working copy) in place.""" + if w.ndim != 2: + raise WeightPatchError("payload", f"op {op.id}: {op.tensor} is {w.ndim}-D; operations need a 2-D tensor") + out_dim, in_dim = w.shape + rows = _resolve_indices(op, "rows", payload, out_dim, max_index_count) + cols = _resolve_indices(op, "cols", payload, in_dim, max_index_count) + n_rows = out_dim if rows is None else rows.numel() + n_cols = in_dim if cols is None else cols.numel() + compute = torch.float64 if w.dtype == torch.float64 else torch.float32 + old = _gather(w, rows, cols) + + if op.op == "add_rank_one": + u = _vector(op, "u", payload, n_rows).to(compute) + v = _vector(op, "v", payload, n_cols).to(compute) + new = (old.to(compute) + float(op.scale) * torch.outer(u, v)).to(w.dtype) + elif op.op == "project": + d_len = out_dim if op.axis == "output" else in_dim + d = _vector(op, "direction", payload, d_len).to(torch.float64) + norm = float(torch.linalg.vector_norm(d).item()) + if norm == 0.0: + raise WeightPatchError("payload", f"op {op.id}: direction has zero norm") + if op.normalize: + d = d / norm + elif abs(norm - 1.0) > _DIRECTION_NORM_TOL: + raise WeightPatchError( + "payload", f"op {op.id}: direction norm {norm:.6g} is not 1 (set normalize: true)" + ) + d = d.to(compute) + block = old.to(compute) + if op.axis == "output": + new = (block - float(op.scale) * torch.outer(d, d @ block)).to(w.dtype) + else: + new = (block - float(op.scale) * torch.outer(block @ d, d)).to(w.dtype) + else: # replace_rows / replace_cols + values = payload.arrays[op.arrays["values"]] + expected = (n_rows, in_dim) if op.op == "replace_rows" else (out_dim, n_cols) + if tuple(values.shape) != expected: + raise WeightPatchError( + "payload", f"op {op.id}: values must have shape {list(expected)}, got {list(values.shape)}" + ) + new = values.to(w.dtype) + + if not _is_finite(new): + raise WeightPatchError("nonfinite", f"op {op.id}: result contains NaN/Inf") + new = torch.where(new != old, new, old) # unchanged values keep their exact bytes + _scatter(w, rows, cols, new) + + +# -------------------------------------------------------------------------- +# Plan +# -------------------------------------------------------------------------- + + +@dataclass +class TensorPlan: + name: str + dtype: str + shape: tuple[int, ...] + before_sha256: str + after_sha256: str + entries_changed: int + delta_frobenius: float + base_frobenius: float + relative_frobenius: float + op_ids: list[str] + new_tensor: Optional[torch.Tensor] = field(default=None, repr=False) + + @property + def modified(self) -> bool: + return self.entries_changed > 0 + + def summary(self) -> dict: + return { + "name": self.name, + "dtype": self.dtype, + "shape": list(self.shape), + "before_sha256": self.before_sha256, + "after_sha256": self.after_sha256, + "entries_changed": self.entries_changed, + "delta_frobenius": self.delta_frobenius, + "base_frobenius": self.base_frobenius, + "relative_frobenius": self.relative_frobenius, + "operations": list(self.op_ids), + } + + +@dataclass +class PatchPlan: + spec_sha256: str + payload_sha256: str + revision: str + targeted: dict[str, TensorPlan] + + @property + def modified(self) -> dict[str, TensorPlan]: + return {n: t for n, t in self.targeted.items() if t.modified} + + @property + def is_noop(self) -> bool: + return not self.modified + + @property + def total_entries_changed(self) -> int: + return sum(t.entries_changed for t in self.targeted.values()) + + def patch_digest(self) -> str: + """Lineage id: spec + payload + exact before/after bytes of every targeted tensor.""" + doc = { + "kind": "mechinterp-weight-patch-digest/v1", + "spec_sha256": self.spec_sha256, + "payload_sha256": self.payload_sha256, + "revision": self.revision, + "tensors": [ + [n, t.before_sha256, t.after_sha256] for n, t in sorted(self.targeted.items()) + ], + } + return hashlib.sha256( + json.dumps(doc, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + + def receipt(self) -> dict: + return { + "schema_version": "mechinterp-weight-patch-receipt/v1", + "patch_digest": self.patch_digest(), + "spec_sha256": self.spec_sha256, + "payload_sha256": self.payload_sha256, + "revision": self.revision, + "noop": self.is_noop, + "total_entries_changed": self.total_entries_changed, + "tensors": [t.summary() for _, t in sorted(self.targeted.items())], + } + + +def build_plan( + spec: WeightPatchSpec, + spec_sha256: str, + payload: Payload, + read_tensor: Callable[[str], torch.Tensor], +) -> PatchPlan: + """Validate and compute the patch result without mutating anything.""" + budget = spec.budget + targeted: dict[str, TensorPlan] = {} + for name in spec.targeted_tensors(): + pin = spec.base.tensors[name] + base = read_tensor(name) + if torch_dtype_name(base.dtype) != pin.dtype or list(base.shape) != pin.shape: + raise WeightPatchError( + "base_hash_mismatch", + f"{name}: base is {torch_dtype_name(base.dtype)}{list(base.shape)}, " + f"spec pins {pin.dtype}{pin.shape}", + ) + if tensor_sha256(base) != pin.sha256: + raise WeightPatchError("base_hash_mismatch", f"{name}: base tensor bytes differ from the pin") + if not _is_finite(base): + raise WeightPatchError("nonfinite", f"{name}: base tensor contains NaN/Inf") + + work = base.clone() + op_ids = [] + for op in spec.operations: + if op.tensor == name: + _apply_operation(work, op, payload, budget.max_index_count) + op_ids.append(op.id) + if not _is_finite(work): + raise WeightPatchError("nonfinite", f"{name}: patched tensor contains NaN/Inf") + + changed = int((work != base).sum().item()) + delta = _sq_diff_sum(work, base) ** 0.5 + norm = _sq_diff_sum(base, None) ** 0.5 + if delta == 0.0: + rel = 0.0 + elif norm == 0.0: + rel = float("inf") + else: + rel = delta / norm + if rel > budget.max_relative_frobenius: + raise WeightPatchError( + "budget", + f"{name}: relative Frobenius change {rel:.6g} exceeds " + f"max_relative_frobenius {budget.max_relative_frobenius:.6g}", + ) + targeted[name] = TensorPlan( + name=name, + dtype=pin.dtype, + shape=tuple(base.shape), + before_sha256=pin.sha256, + after_sha256=tensor_sha256(work) if changed else pin.sha256, + entries_changed=changed, + delta_frobenius=delta, + base_frobenius=norm, + relative_frobenius=rel, + op_ids=op_ids, + new_tensor=work if changed else None, + ) + + plan = PatchPlan(spec_sha256, payload.sha256, spec.base.revision, targeted) + if len(plan.modified) > budget.max_modified_tensors: + raise WeightPatchError("budget", "modified tensor count exceeds max_modified_tensors") + if plan.total_entries_changed > budget.max_modified_entries: + raise WeightPatchError( + "budget", + f"{plan.total_entries_changed} modified entries exceed max_modified_entries " + f"{budget.max_modified_entries}", + ) + return plan diff --git a/MechInterp/weights/projection.py b/MechInterp/weights/projection.py new file mode 100644 index 000000000..b10ee0106 --- /dev/null +++ b/MechInterp/weights/projection.py @@ -0,0 +1,183 @@ +"""Bounded numeric reads of checkpoint tensors for ``weights-inspect``. + +Answers questions like "what is the dot product of each of these selected +columns of a 2-D tensor with this configured vector" without loading the model +and without emitting unbounded arrays. Exactly one tensor is read at a time (its +size is capped), only the selected lines are converted to float64, and the total +number of emitted values is capped by the request. Nothing here knows what the +tensor, vector or indices mean. +""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +import torch + +from MechInterp.weights.checkpoint import LocalCheckpoint +from MechInterp.weights.errors import WeightPatchError +from MechInterp.weights.patch import buffer_to_tensor +from MechInterp.weights.safetensors_io import ( + FLOAT_TORCH_NAMES, + file_sha256, + read_header, + read_region, + strict_json_loads, +) +from MechInterp.weights.spec import InspectRequest, ProjectionRequest, VectorSource + +_MAX_VECTOR_FILE_BYTES = 64 * 1024 * 1024 +_MAX_DIRECTION_JSON_BYTES = 8 * 1024 * 1024 +_DIRECTION_SCHEMA = "mechinterp-direction/v1" + + +def _pinned_file(path: str, expected_sha: str, limit: int, what: str) -> Path: + p = Path(path) + if not p.is_file() or p.is_symlink(): + raise WeightPatchError("path", f"{what} must be an existing regular, non-symlink file") + if p.stat().st_size > limit: + raise WeightPatchError("budget", f"{what} exceeds {limit} bytes") + if file_sha256(p) != expected_sha: + raise WeightPatchError("payload", f"{what} sha256 does not match its pin") + return p + + +def load_vector(src: VectorSource) -> tuple[torch.Tensor, dict]: + """(float64 1-D vector, provenance dict).""" + if src.inline is not None: + vec = torch.tensor(src.inline, dtype=torch.float64) + info = {"source": "inline", "sha256": None} + elif src.safetensors is not None: + ref = src.safetensors + p = _pinned_file(ref.path, ref.sha256, _MAX_VECTOR_FILE_BYTES, "vector file") + sf = read_header(p) + entry = sf.entries.get(ref.key) + if entry is None: + raise WeightPatchError("payload", f"vector file has no array {ref.key!r}") + if entry.torch_dtype not in FLOAT_TORCH_NAMES or len(entry.shape) != 1: + raise WeightPatchError("payload", "vector array must be a 1-D float array") + vec = buffer_to_tensor(read_region(sf, entry), entry.torch_dtype, entry.shape).to(torch.float64) + info = {"source": "safetensors", "sha256": ref.sha256} + else: + ref = src.direction_json + p = _pinned_file(ref.path, ref.sha256, _MAX_DIRECTION_JSON_BYTES, "direction file") + doc = strict_json_loads(p.read_bytes()) + values = doc.get("vector") if isinstance(doc, dict) else None + if ( + not isinstance(doc, dict) + or doc.get("schema_version") != _DIRECTION_SCHEMA + or not isinstance(values, list) + or not values + or not all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values) + ): + raise WeightPatchError("payload", f"direction file must be a {_DIRECTION_SCHEMA} document with a numeric vector") + vec = torch.tensor(values, dtype=torch.float64) + info = {"source": "direction_json", "sha256": ref.sha256} + if not bool(torch.isfinite(vec).all()): + raise WeightPatchError("nonfinite", "vector contains NaN/Inf") + info["length"] = int(vec.numel()) + info["l2_norm"] = float(torch.linalg.vector_norm(vec).item()) + return vec, info + + +def _indices(values, dim: int, label: str, pid: str) -> torch.Tensor: + if values is None: + return torch.arange(dim, dtype=torch.int64) + idx = torch.tensor(values, dtype=torch.int64) + if int(idx.min()) < 0 or int(idx.max()) >= dim: + raise WeightPatchError("payload", f"projection {pid}: {label} index out of range [0, {dim})") + if int(torch.unique(idx).numel()) != idx.numel(): + raise WeightPatchError("payload", f"projection {pid}: {label} are not distinct") + return idx + + +def _count(values, dim: int) -> int: + return dim if values is None else len(values) + + +def run_projections(request: InspectRequest, ckpt: LocalCheckpoint) -> list[dict]: + results: list[dict] = [] + emitted = 0 + for req in request.projections: + results.append(_one(req, request, ckpt, emitted)) + emitted += results[-1]["n_values"] + return results + + +def _one(req: ProjectionRequest, request: InspectRequest, ckpt: LocalCheckpoint, emitted: int) -> dict: + if req.tensor not in ckpt.tensor_to_file: + raise WeightPatchError("binding", f"projection {req.id}: tensor {req.tensor!r} is not in the checkpoint") + sf, entry = ckpt.entry(req.tensor) + if entry.torch_dtype not in FLOAT_TORCH_NAMES or len(entry.shape) != 2: + raise WeightPatchError("payload", f"projection {req.id}: {req.tensor} must be a 2-D float tensor") + if entry.nbytes > request.max_tensor_bytes: + raise WeightPatchError("budget", f"projection {req.id}: tensor exceeds max_tensor_bytes") + n_rows, n_cols = entry.shape + line_dim, pos_dim = (n_cols, n_rows) if req.axis == "cols" else (n_rows, n_cols) + + n_lines = _count(req.indices, line_dim) + n_pos = _count(req.other_indices, pos_dim) + if req.kind == "slice": + n_values = n_lines * n_pos + else: + n_values = n_lines * (2 if req.include_norms else 1) + if emitted + n_values > request.max_output_values: + raise WeightPatchError( + "budget", + f"projection {req.id}: output would exceed max_output_values {request.max_output_values}", + ) + + lines = _indices(req.indices, line_dim, "indices", req.id) + pos = _indices(req.other_indices, pos_dim, "other_indices", req.id) + + raw = read_region(sf, entry) + tensor_sha = hashlib.sha256(raw).hexdigest() + w = buffer_to_tensor(raw, entry.torch_dtype, entry.shape) + if req.axis == "cols": + sub = w.index_select(1, lines).index_select(0, pos).to(torch.float64).T # [lines, positions] + else: + sub = w.index_select(0, lines).index_select(1, pos).to(torch.float64) + if not bool(torch.isfinite(sub).all()): + raise WeightPatchError("nonfinite", f"projection {req.id}: selected values contain NaN/Inf") + + out: dict = { + "id": req.id, + "tensor": req.tensor, + "kind": req.kind, + "axis": req.axis, + "dtype": entry.torch_dtype, + "shape": [n_rows, n_cols], + "tensor_sha256": tensor_sha, + "n_lines": n_lines, + "n_positions": n_pos, + "n_values": n_values, + "indices": lines.tolist() if req.indices is not None else "all", + } + if req.other_indices is not None: + out["other_indices"] = pos.tolist() + if req.kind == "slice": + out["values"] = sub.tolist() + return out + + vec, info = load_vector(req.vector) + if vec.numel() != n_pos: + raise WeightPatchError( + "payload", f"projection {req.id}: vector length {vec.numel()} != line length {n_pos}" + ) + out["vector"] = info + dots = sub @ vec + norms = torch.linalg.vector_norm(sub, dim=1) + if req.kind == "dot": + out["values"] = dots.tolist() + else: + vnorm = float(info["l2_norm"]) + if vnorm == 0.0: + raise WeightPatchError("payload", f"projection {req.id}: cosine with a zero vector") + out["values"] = [ + None if float(n) == 0.0 else float(d) / (float(n) * vnorm) + for d, n in zip(dots.tolist(), norms.tolist()) + ] + if req.include_norms: + out["line_norms"] = norms.tolist() + return out diff --git a/MechInterp/weights/runtime.py b/MechInterp/weights/runtime.py new file mode 100644 index 000000000..9dc0e75d2 --- /dev/null +++ b/MechInterp/weights/runtime.py @@ -0,0 +1,196 @@ +"""Transactional in-memory application of a weight patch to a loaded module. + +This is the path ``steer`` / ``extract`` / ``dose-calibrate`` use: no checkpoint +is exported per candidate. The patch is planned against the loaded module's own +bytes (so a wrong base is refused by hash, whatever the model's config claims), +then committed all-or-nothing with the originals retained for exact revert. + + prepared = prepare_patch(ref_path, ref_sha256, context=ctx) + check_declared_revision(prepared, revision=cli_revision) # pre-load + ...load the model... + with patched(model, prepared) as applied: # reverts on exit + ... + applied = apply_patch(model, prepared) # keep applied + applied.revert() # exact undo +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Optional + +import torch + +from MechInterp.weights.errors import WeightPatchError +from MechInterp.weights.patch import ( + PatchPlan, + Payload, + build_plan, + load_payload, + tensor_sha256, +) +from MechInterp.weights.spec import WeightPatchSpec, load_patch_spec + + +@dataclass +class PreparedPatch: + """A spec whose file bytes and payload bytes have been verified (not yet applied).""" + + spec: WeightPatchSpec + spec_sha256: str + payload: Payload + + +def prepare_patch(path: str | Path, expected_sha256: str, *, context=None) -> PreparedPatch: + """Load a patch spec, require its file sha256 to equal ``expected_sha256``, + and verify + load its payload. Cheap; call before loading any model.""" + spec, digest = load_patch_spec(path, context=context) + if digest != expected_sha256: + raise WeightPatchError( + "binding", "weight patch spec sha256 does not match the pinned weight_patch.sha256" + ) + return PreparedPatch(spec, digest, load_payload(spec)) + + +def check_declared_revision(prepared: PreparedPatch, revision: Optional[str]) -> None: + """The run's declared model revision must equal the patch's base.revision.""" + declared = prepared.spec.base.revision + if revision is None: + raise WeightPatchError( + "binding", + f"the patch binds base.revision {declared}; pass --model-revision {declared} " + "(an unpinned load cannot be tied to the patch's base)", + ) + if revision != declared: + raise WeightPatchError( + "binding", f"declared model revision {revision!r} != patch base.revision {declared!r}" + ) + + +def check_loaded_commit(prepared: PreparedPatch, model) -> Optional[str]: + """If the loaded model carries a resolved commit hash, it must match. + + This is corroboration only (transformers records ``config._commit_hash`` for + Hub loads). The binding that matters is the targeted-tensor byte hash check + performed when the patch is planned against the module. + """ + commit = getattr(getattr(model, "config", None), "_commit_hash", None) + if isinstance(commit, str) and commit and commit != prepared.spec.base.revision: + raise WeightPatchError( + "binding", + f"loaded model resolved commit {commit!r} != patch base.revision " + f"{prepared.spec.base.revision!r}", + ) + return commit if isinstance(commit, str) and commit else None + + +def runtime_name(spec: WeightPatchSpec, checkpoint_name: str) -> str: + for rule in spec.base.runtime_prefix_rules: + if checkpoint_name.startswith(rule.checkpoint_prefix): + return rule.runtime_prefix + checkpoint_name[len(rule.checkpoint_prefix) :] + return checkpoint_name + + +def _module_tensors(model) -> dict[str, torch.Tensor]: + tensors = dict(model.named_parameters(remove_duplicate=False)) + for name, buf in model.named_buffers(remove_duplicate=False): + tensors.setdefault(name, buf) + return tensors + + +class AppliedPatch: + """A committed patch with its originals retained for exact, verified revert.""" + + def __init__(self, plan: PatchPlan, targets: dict[str, torch.Tensor], originals: dict[str, torch.Tensor]): + self.plan = plan + self._targets = targets + self._originals = originals + self.reverted = False + + @property + def receipt(self) -> dict: + return self.plan.receipt() + + def revert(self) -> None: + if self.reverted: + return + with torch.no_grad(): + for name, original in self._originals.items(): + self._targets[name].copy_(original.to(self._targets[name].device)) + for name in self._originals: + if tensor_sha256(self._targets[name]) != self.plan.targeted[name].before_sha256: + raise WeightPatchError("apply", f"{name}: revert did not restore the original bytes") + self._originals = {} + self.reverted = True + + def __enter__(self) -> "AppliedPatch": + return self + + def __exit__(self, *exc) -> None: + self.revert() + + +def apply_patch(model, prepared: PreparedPatch) -> AppliedPatch: + """Plan against the module's own bytes, then commit all-or-nothing.""" + spec = prepared.spec + tensors = _module_tensors(model) + targets: dict[str, torch.Tensor] = {} + for name in spec.targeted_tensors(): + rname = runtime_name(spec, name) + target = tensors.get(rname) + if target is None: + raise WeightPatchError("binding", f"loaded module has no tensor {rname!r} (for {name!r})") + if target.device.type == "meta": + raise WeightPatchError("binding", f"{rname!r} is on the meta device (not materialized)") + if not target.is_floating_point(): + raise WeightPatchError("binding", f"{rname!r} is not a floating-point tensor") + targets[name] = target + + # A write through one name must not modify an unbudgeted alias, including + # overlapping views. Refuse shared storage conservatively (even disjoint views). + for name, target in targets.items(): + target_storage = (target.device, target.untyped_storage().data_ptr()) + aliases = [other for other, tensor in tensors.items() + if other != runtime_name(spec, name) and tensor.device.type != "meta" + and tensor.numel() and target.numel() + and (tensor.device, tensor.untyped_storage().data_ptr()) == target_storage] + if aliases: + raise WeightPatchError("binding", f"{name}: target shares storage with another parameter or buffer") + + def read_tensor(name: str) -> torch.Tensor: + return targets[name].detach().to("cpu").contiguous().clone() + + plan = build_plan(spec, prepared.spec_sha256, prepared.payload, read_tensor) + + originals: dict[str, torch.Tensor] = {} + written: list[str] = [] + try: + with torch.no_grad(): + for name, tp in plan.modified.items(): + originals[name] = targets[name].detach().clone() + written.append(name) + targets[name].copy_(tp.new_tensor.to(device=targets[name].device, dtype=targets[name].dtype)) + for name, tp in plan.modified.items(): + if tensor_sha256(targets[name]) != tp.after_sha256: + raise WeightPatchError("apply", f"{name}: committed bytes differ from the plan") + except BaseException: + try: + with torch.no_grad(): + for name in written: + targets[name].copy_(originals[name]) + for name in written: + if tensor_sha256(targets[name]) != plan.targeted[name].before_sha256: + raise WeightPatchError("apply", f"{name}: rollback did not restore the original bytes") + except BaseException as rollback_exc: + raise WeightPatchError("apply", "patch failed and rollback verification failed") from rollback_exc + raise + # Free the planned copies; revert uses the retained originals. + for tp in plan.targeted.values(): + tp.new_tensor = None + return AppliedPatch(plan, targets, originals) + + +def patched(model, prepared: PreparedPatch) -> AppliedPatch: + """Context manager form: ``with patched(model, prepared) as applied: ...``""" + return apply_patch(model, prepared) diff --git a/MechInterp/weights/safetensors_io.py b/MechInterp/weights/safetensors_io.py new file mode 100644 index 000000000..39310a79d --- /dev/null +++ b/MechInterp/weights/safetensors_io.py @@ -0,0 +1,262 @@ +"""Strict, pickle-free, torch-free safetensors header reader and byte hashing. + +The weight-patch engine binds a patch to *exact bytes*. These helpers parse a +local ``.safetensors`` file's header with full structural validation and hash +raw tensor data regions straight from the file, so the digest covers the actual +stored dtype bytes (bfloat16 included) with no numeric round trip. + +Nothing here loads a tensor into memory except ``read_region`` (one tensor), and +nothing here ever unpickles or touches the network. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import struct +from dataclasses import dataclass +from pathlib import Path +from typing import Iterator + +from MechInterp.weights.errors import WeightPatchError + +MAX_HEADER_BYTES = 64 * 1024 * 1024 +_CHUNK = 8 * 1024 * 1024 + +# safetensors dtype tag -> (itemsize, torch dtype name) +DTYPES: dict[str, tuple[int, str]] = { + "F64": (8, "float64"), + "F32": (4, "float32"), + "F16": (2, "float16"), + "BF16": (2, "bfloat16"), + "I64": (8, "int64"), + "I32": (4, "int32"), + "I16": (2, "int16"), + "I8": (1, "int8"), + "U64": (8, "uint64"), + "U32": (4, "uint32"), + "U16": (2, "uint16"), + "U8": (1, "uint8"), + "BOOL": (1, "bool"), + "F8_E4M3": (1, "float8_e4m3fn"), + "F8_E5M2": (1, "float8_e5m2"), +} +FLOAT_TAGS = frozenset({"F64", "F32", "F16", "BF16"}) +TORCH_NAME_TO_TAG = {name: tag for tag, (_, name) in DTYPES.items()} +FLOAT_TORCH_NAMES = frozenset(DTYPES[t][1] for t in FLOAT_TAGS) + + +@dataclass(frozen=True) +class TensorEntry: + name: str + dtype_tag: str + shape: tuple[int, ...] + begin: int # data-region-relative start + end: int # data-region-relative end (exclusive) + + @property + def torch_dtype(self) -> str: + return DTYPES[self.dtype_tag][1] + + @property + def numel(self) -> int: + n = 1 + for d in self.shape: + n *= d + return n + + @property + def nbytes(self) -> int: + return self.end - self.begin + + +@dataclass(frozen=True) +class SafetensorsFile: + path: Path + size: int + header_len: int + entries: dict[str, TensorEntry] + metadata: dict[str, str] + + @property + def data_start(self) -> int: + return 8 + self.header_len + + def absolute_range(self, entry: TensorEntry) -> tuple[int, int]: + return self.data_start + entry.begin, self.data_start + entry.end + + def ordered_entries(self) -> list[TensorEntry]: + return sorted(self.entries.values(), key=lambda e: (e.begin, e.end, e.name)) + + +def _reject_duplicates(pairs): + out = {} + for key, value in pairs: + if key in out: + raise WeightPatchError("index", f"duplicate key {key!r} in JSON object") + out[key] = value + return out + + +def _reject_constant(token): + raise WeightPatchError("index", f"non-finite JSON constant {token!r}") + + +def strict_json_loads(data: bytes | str): + """JSON parse that refuses duplicate keys and NaN/Infinity constants.""" + try: + return json.loads( + data, object_pairs_hook=_reject_duplicates, parse_constant=_reject_constant + ) + except WeightPatchError: + raise + except (ValueError, UnicodeDecodeError) as exc: + raise WeightPatchError("index", f"malformed JSON: {exc}") from None + + +def _plain_int(value) -> bool: + return isinstance(value, int) and not isinstance(value, bool) + + +def read_header(path: str | Path) -> SafetensorsFile: + """Parse and structurally validate a safetensors header. + + Enforced: bounded header, UTF-8 JSON object without duplicate keys, known + dtype tags, non-negative integer shapes, ``end - begin == numel * itemsize``, + tensors tiling the data region exactly (no gaps, no overlap, no trailing + bytes), and a file size equal to ``8 + header + data``. + """ + p = Path(path) + try: + size = p.stat().st_size + with open(p, "rb") as fh: + prefix = fh.read(8) + if len(prefix) != 8: + raise WeightPatchError("index", f"{p.name}: truncated before header length") + (header_len,) = struct.unpack(" MAX_HEADER_BYTES or 8 + header_len > size: + raise WeightPatchError( + "index", f"{p.name}: invalid header length {header_len}" + ) + raw = fh.read(header_len) + except OSError as exc: + raise WeightPatchError("path", f"cannot read {p.name}: {exc.strerror}") from None + if len(raw) != header_len: + raise WeightPatchError("index", f"{p.name}: truncated header") + if not raw.lstrip(b" ").startswith(b"{"): + raise WeightPatchError("index", f"{p.name}: header is not a JSON object") + header = strict_json_loads(raw) + if not isinstance(header, dict): + raise WeightPatchError("index", f"{p.name}: header is not a JSON object") + + metadata: dict[str, str] = {} + entries: dict[str, TensorEntry] = {} + for name, spec in header.items(): + if name == "__metadata__": + if not isinstance(spec, dict) or not all( + isinstance(k, str) and isinstance(v, str) for k, v in spec.items() + ): + raise WeightPatchError("index", f"{p.name}: invalid __metadata__") + metadata = dict(spec) + continue + if not isinstance(spec, dict) or set(spec) != {"dtype", "shape", "data_offsets"}: + raise WeightPatchError("index", f"{p.name}: malformed entry for {name!r}") + tag = spec["dtype"] + if tag not in DTYPES: + raise WeightPatchError("index", f"{p.name}: unsupported dtype {tag!r} for {name!r}") + shape = spec["shape"] + if not isinstance(shape, list) or not all(_plain_int(d) and d >= 0 for d in shape): + raise WeightPatchError("index", f"{p.name}: invalid shape for {name!r}") + offsets = spec["data_offsets"] + if ( + not isinstance(offsets, list) + or len(offsets) != 2 + or not all(_plain_int(o) and o >= 0 for o in offsets) + or offsets[0] > offsets[1] + ): + raise WeightPatchError("index", f"{p.name}: invalid data_offsets for {name!r}") + numel = 1 + for d in shape: + numel *= d + if numel > 1 << 62: + raise WeightPatchError("index", f"{p.name}: shape too large for {name!r}") + if offsets[1] - offsets[0] != numel * DTYPES[tag][0]: + raise WeightPatchError( + "index", f"{p.name}: byte length does not match shape/dtype for {name!r}" + ) + entries[name] = TensorEntry(name, tag, tuple(shape), offsets[0], offsets[1]) + + data_len = size - 8 - header_len + cursor = 0 + for entry in sorted(entries.values(), key=lambda e: (e.begin, e.end, e.name)): + if entry.begin != cursor: + raise WeightPatchError( + "index", f"{p.name}: tensor data not contiguous at {entry.name!r}" + ) + cursor = entry.end + if cursor != data_len: + raise WeightPatchError("index", f"{p.name}: data region size mismatch") + return SafetensorsFile(p, size, header_len, entries, metadata) + + +def _stream(fh, count: int) -> Iterator[bytes]: + remaining = count + while remaining > 0: + chunk = fh.read(min(_CHUNK, remaining)) + if not chunk: + raise WeightPatchError("index", "file shorter than its header declares") + remaining -= len(chunk) + yield chunk + + +def file_sha256(path: str | Path) -> str: + h = hashlib.sha256() + try: + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(_CHUNK), b""): + h.update(chunk) + except OSError as exc: + raise WeightPatchError("path", f"cannot read file: {exc.strerror}") from None + return h.hexdigest() + + +def hash_file_with_regions(sf: SafetensorsFile) -> tuple[str, dict[str, str]]: + """One sequential pass: (whole-file sha256, {tensor name: data-region sha256}).""" + whole = hashlib.sha256() + regions: dict[str, str] = {} + with open(sf.path, "rb") as fh: + whole.update(fh.read(sf.data_start)) + for entry in sf.ordered_entries(): + region = hashlib.sha256() + for chunk in _stream(fh, entry.nbytes): + whole.update(chunk) + region.update(chunk) + regions[entry.name] = region.hexdigest() + if fh.read(1): + raise WeightPatchError("index", f"{sf.path.name}: trailing bytes after data") + return whole.hexdigest(), regions + + +def read_region(sf: SafetensorsFile, entry: TensorEntry) -> bytearray: + """Read exactly one tensor's raw bytes (a mutable buffer for torch.frombuffer).""" + start, end = sf.absolute_range(entry) + with open(sf.path, "rb") as fh: + fh.seek(start) + buf = bytearray(end - start) + view = memoryview(buf) + got = 0 + while got < len(buf): + n = fh.readinto(view[got:]) + if not n: + raise WeightPatchError("index", f"{sf.path.name}: short read for {entry.name!r}") + got += n + return buf + + +def fsync_path(path: str | Path) -> None: + fd = os.open(path, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) diff --git a/MechInterp/weights/spec.py b/MechInterp/weights/spec.py new file mode 100644 index 000000000..e74faf53a --- /dev/null +++ b/MechInterp/weights/spec.py @@ -0,0 +1,525 @@ +"""Declarative ``mechinterp-weight-patch/v1`` and ``mechinterp-weights-inspect/v1``. + +A patch spec is a YAML/JSON document that binds a patch to exact base bytes and +declares every restriction up front: + + base source identity: declared revision, optional index/file hashes, and + the dtype/shape/byte-hash of EVERY tensor an operation targets. + budget finite limits: allowed tensor patterns, max modified tensors and + entries, per-tensor relative Frobenius norm, payload size. + payload a safetensors file (+ sha256) holding all numeric arrays; the spec + itself carries no floating-point data except scalar scales. + operations the edits (``add_rank_one``, ``project``, ``replace_rows``, + ``replace_cols``); indices inline or from integer payload arrays. + export optional destination for ``weights-patch --export``. + +This module only validates *structure*. Byte-level checks happen in +checkpoint.py / patch.py. No tensor name, shape or value is hardcoded here. +""" + +from __future__ import annotations + +import fnmatch +import hashlib +import json +import re +from pathlib import Path +from typing import Annotated, Literal, Optional + +import yaml +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, model_validator + +from MechInterp.weights.errors import WeightPatchError +from MechInterp.weights.safetensors_io import FLOAT_TORCH_NAMES + +PATCH_SCHEMA = "mechinterp-weight-patch/v1" +INSPECT_SCHEMA = "mechinterp-weights-inspect/v1" + +_HEX64 = re.compile(r"^[0-9a-f]{64}$") +_REV40 = re.compile(r"^[0-9a-f]{40}$") +_MAX_SPEC_BYTES = 8 * 1024 * 1024 + +FiniteFloat = Annotated[float, Field(strict=True, allow_inf_nan=False)] +Hex64 = Annotated[str, Field(pattern=_HEX64.pattern)] + + +class _Strict(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class BaseTensorBinding(_Strict): + """Exact identity of one targeted base tensor.""" + + dtype: StrictStr + shape: list[StrictInt] = Field(..., min_length=1) + sha256: Hex64 + + @model_validator(mode="after") + def _check(self) -> "BaseTensorBinding": + if self.dtype not in FLOAT_TORCH_NAMES: + raise ValueError( + f"dtype {self.dtype!r} is not patchable; allowed {sorted(FLOAT_TORCH_NAMES)}" + ) + if any(d < 0 for d in self.shape): + raise ValueError("shape must be non-negative integers") + return self + + +class RuntimePrefixRule(_Strict): + """Maps checkpoint tensor-name prefixes to in-memory parameter-name prefixes. + + Only needed when the loaded module names differ from checkpoint file names + (some wrapper architectures). First matching rule wins; no rule = identity. + """ + + checkpoint_prefix: StrictStr + runtime_prefix: StrictStr + + +class BaseBinding(_Strict): + model_id: Optional[StrictStr] = None + revision: StrictStr = Field(..., description="Full 40-hex commit/revision id") + checkpoint: Optional[StrictStr] = Field( + default=None, + description="LOCAL safetensors directory or file; required by weights-patch.", + ) + index_sha256: Optional[Hex64] = Field( + default=None, + description="sha256 of model.safetensors.index.json (sharded) or of the single file.", + ) + files_sha256: Optional[dict[StrictStr, Hex64]] = Field( + default=None, description="Whole-file sha256 per weight file name." + ) + allow_symlinked_files: bool = False + runtime_prefix_rules: list[RuntimePrefixRule] = Field(default_factory=list) + tensors: dict[StrictStr, BaseTensorBinding] = Field(..., min_length=1) + + @model_validator(mode="after") + def _check(self) -> "BaseBinding": + if not _REV40.match(self.revision): + raise ValueError("base.revision must be a full 40-character lowercase hex id") + for name in self.tensors: + if not name or len(name) > 512: + raise ValueError("tensor names must be 1..512 characters") + if self.files_sha256 is not None: + for fname in self.files_sha256: + if "/" in fname or "\\" in fname or fname in {"", ".", ".."}: + raise ValueError(f"files_sha256 key {fname!r} must be a plain file name") + return self + + +class Budget(_Strict): + allowed_tensors: list[StrictStr] = Field(..., min_length=1) + max_modified_tensors: StrictInt = Field(..., ge=1, le=100_000) + max_modified_entries: StrictInt = Field(..., ge=1) + max_relative_frobenius: FiniteFloat = Field(..., ge=0.0) + max_payload_bytes: StrictInt = Field(default=256 * 1024 * 1024, ge=1, le=4 * 1024**3) + max_index_count: StrictInt = Field(default=1_000_000, ge=1, le=100_000_000) + + +class PayloadRef(_Strict): + path: StrictStr = Field(..., min_length=1) + sha256: Hex64 + + +OpName = Literal["add_rank_one", "project", "replace_rows", "replace_cols"] + +# role -> required? (per op) +_ROLES: dict[str, dict[str, bool]] = { + "add_rank_one": {"u": True, "v": True}, + "project": {"direction": True}, + "replace_rows": {"values": True}, + "replace_cols": {"values": True}, +} +_INDEX_ROLES = {"rows", "cols"} + + +class Operation(_Strict): + """One edit of a 2-D tensor ``W`` of shape ``[out, in]``. + + add_rank_one ``W[R][:, C] += scale * outer(u, v)`` with optional row set R + (``rows``) and column set C (``cols``); ``len(u)==|R|``, + ``len(v)==|C|`` (omitted set = every index). + project remove (scaled) component along unit ``direction``: + ``axis: output`` -> ``W[:, C] -= scale * d (d^T W[:, C])`` + (d has length ``out``; optional ``cols``); + ``axis: input`` -> ``W[R] -= scale * (W[R] d) d^T`` + (d has length ``in``; optional ``rows``). + replace_rows ``W[R] = values`` (``values`` is ``[|R|, in]``; ``rows`` required). + replace_cols ``W[:, C] = values`` (``values`` is ``[out, |C|]``; ``cols`` required). + + ``arrays`` maps each role to a payload tensor name. ``rows``/``cols`` are + either inline integer lists or payload integer arrays via + ``arrays: {rows: }`` (never both). + """ + + id: StrictStr = Field(..., min_length=1, max_length=128) + tensor: StrictStr = Field(..., min_length=1, max_length=512) + op: OpName + scale: Optional[FiniteFloat] = None + axis: Optional[Literal["output", "input"]] = None + normalize: bool = False + rows: Optional[list[StrictInt]] = None + cols: Optional[list[StrictInt]] = None + arrays: dict[StrictStr, StrictStr] = Field(default_factory=dict) + + @model_validator(mode="after") + def _check(self) -> "Operation": + roles = _ROLES[self.op] + allowed = set(roles) | _INDEX_ROLES + for role, name in self.arrays.items(): + if role not in allowed: + raise ValueError(f"op {self.id}: unknown array role {role!r} for {self.op}") + if not name: + raise ValueError(f"op {self.id}: empty payload name for role {role!r}") + for role, required in roles.items(): + if required and role not in self.arrays: + raise ValueError(f"op {self.id}: {self.op} requires arrays.{role}") + for role in _INDEX_ROLES: + inline = getattr(self, role) + if inline is not None and role in self.arrays: + raise ValueError(f"op {self.id}: {role} given both inline and as an array") + has_rows = self.rows is not None or "rows" in self.arrays + has_cols = self.cols is not None or "cols" in self.arrays + + if self.op in {"add_rank_one", "project"}: + if self.scale is None: + self.scale = 1.0 + elif self.scale is not None: + raise ValueError(f"op {self.id}: scale is not valid for {self.op}") + + if self.op == "project": + if self.axis is None: + raise ValueError(f"op {self.id}: project requires axis") + if self.axis == "output" and has_rows: + raise ValueError(f"op {self.id}: axis=output cannot restrict rows") + if self.axis == "input" and has_cols: + raise ValueError(f"op {self.id}: axis=input cannot restrict cols") + else: + if self.axis is not None or self.normalize: + raise ValueError(f"op {self.id}: axis/normalize are only valid for project") + if self.op == "replace_rows" and (not has_rows or has_cols): + raise ValueError(f"op {self.id}: replace_rows needs rows and no cols") + if self.op == "replace_cols" and (not has_cols or has_rows): + raise ValueError(f"op {self.id}: replace_cols needs cols and no rows") + return self + + +class ExportConfig(_Strict): + output_dir: StrictStr = Field(..., min_length=1) + sidecar_files: list[StrictStr] = Field(default_factory=lambda: ["*.json", "*.model", "*.jinja", "*.txt", "*.tiktoken", "*.py"]) + max_sidecar_bytes: StrictInt = Field(default=64 * 1024 * 1024, ge=1) + + +class WeightPatchSpec(_Strict): + schema_version: Literal["mechinterp-weight-patch/v1"] + description: Optional[StrictStr] = None + base: BaseBinding + budget: Budget + payload: PayloadRef + operations: list[Operation] = Field(..., min_length=1, max_length=256) + export: Optional[ExportConfig] = None + + @model_validator(mode="after") + def _check(self) -> "WeightPatchSpec": + ids = [op.id for op in self.operations] + if len(ids) != len(set(ids)): + raise ValueError("operation ids must be unique") + targeted = [] + for op in self.operations: + if op.tensor not in self.base.tensors: + raise ValueError( + f"op {op.id}: tensor {op.tensor!r} has no entry in base.tensors" + ) + if not any(fnmatch.fnmatchcase(op.tensor, pat) for pat in self.budget.allowed_tensors): + raise ValueError( + f"op {op.id}: tensor {op.tensor!r} is not matched by budget.allowed_tensors" + ) + if op.tensor not in targeted: + targeted.append(op.tensor) + if len(targeted) > self.budget.max_modified_tensors: + raise ValueError( + f"{len(targeted)} targeted tensors exceed budget.max_modified_tensors" + ) + unused = set(self.base.tensors) - set(targeted) + if unused: + raise ValueError( + f"base.tensors lists tensors no operation targets: {sorted(unused)[:3]}" + ) + return self + + def targeted_tensors(self) -> list[str]: + out: list[str] = [] + for op in self.operations: + if op.tensor not in out: + out.append(op.tensor) + return out + + +class VectorFile(_Strict): + """A 1-D float vector stored in a safetensors file (hash-pinned).""" + + path: StrictStr = Field(..., min_length=1) + key: StrictStr = Field(..., min_length=1) + sha256: Hex64 + + +class DirectionFile(_Strict): + """A ``mechinterp-direction/v1`` JSON (its ``vector`` field), hash-pinned.""" + + path: StrictStr = Field(..., min_length=1) + sha256: Hex64 + + +class VectorSource(_Strict): + """Exactly one of: inline numbers, a safetensors vector, a direction JSON.""" + + inline: Optional[list[FiniteFloat]] = Field(default=None, min_length=1, max_length=65536) + safetensors: Optional[VectorFile] = None + direction_json: Optional[DirectionFile] = None + + @model_validator(mode="after") + def _one(self) -> "VectorSource": + given = [ + n + for n in ("inline", "safetensors", "direction_json") + if getattr(self, n) is not None + ] + if len(given) != 1: + raise ValueError("vector needs exactly one of inline / safetensors / direction_json") + return self + + +class ProjectionRequest(_Strict): + """A bounded numeric read of one 2-D tensor ``W``. + + ``axis`` picks which lines are selected: ``cols`` -> columns ``W[:, j]`` (e.g. + the output vector one hidden unit writes), ``rows`` -> rows ``W[i, :]``. + ``indices`` selects lines (omitted = every line). ``other_indices`` restricts + positions along each line (omitted = the whole line). + + kind ``dot`` value per selected line: ``line . vector`` + ``cosine`` ``line . vector / (|line| |vector|)`` (null for a zero line) + ``slice`` the raw values, ``[lines, positions]`` (no vector) + + All arithmetic is float64 on the stored values; output size is capped by the + request's ``max_output_values``. + """ + + id: StrictStr = Field(..., min_length=1, max_length=128) + tensor: StrictStr = Field(..., min_length=1, max_length=512) + kind: Literal["dot", "cosine", "slice"] = "dot" + axis: Literal["cols", "rows"] + indices: Optional[list[StrictInt]] = Field(default=None, min_length=1) + other_indices: Optional[list[StrictInt]] = Field(default=None, min_length=1) + vector: Optional[VectorSource] = None + include_norms: bool = False + + @model_validator(mode="after") + def _check(self) -> "ProjectionRequest": + if self.kind == "slice": + if self.vector is not None or self.include_norms: + raise ValueError(f"projection {self.id}: slice takes no vector/include_norms") + elif self.vector is None: + raise ValueError(f"projection {self.id}: {self.kind} requires a vector") + return self + + +class InspectRequest(_Strict): + schema_version: Literal["mechinterp-weights-inspect/v1"] + checkpoint: StrictStr = Field(..., min_length=1) + allow_symlinked_files: bool = False + hash_files: bool = False + tensors: list[StrictStr] = Field( + default_factory=list, description="fnmatch patterns of tensors to list" + ) + hash_tensors: bool = False + max_listed_tensors: StrictInt = Field(default=512, ge=1, le=100_000) + projections: list[ProjectionRequest] = Field(default_factory=list, max_length=64) + max_output_values: StrictInt = Field( + default=16384, + ge=1, + le=1_000_000, + description="Total numeric values all projections may emit.", + ) + max_tensor_bytes: StrictInt = Field( + default=2 * 1024**3, + ge=1, + le=16 * 1024**3, + description="Largest single tensor a projection may read into memory.", + ) + + @model_validator(mode="after") + def _unique_projection_ids(self) -> "InspectRequest": + ids = [p.id for p in self.projections] + if len(ids) != len(set(ids)): + raise ValueError("projection ids must be unique") + return self + + +# -------------------------------------------------------------------------- +# Loading +# -------------------------------------------------------------------------- + + +class _DupSafeLoader(yaml.SafeLoader): + pass + + +def _construct_mapping(loader, node, deep=False): + keys = set() + for key_node, _ in node.value: + key = loader.construct_object(key_node, deep=deep) + if key in keys: + raise yaml.constructor.ConstructorError( + None, None, f"duplicate key {key!r}", key_node.start_mark + ) + keys.add(key) + return yaml.SafeLoader.construct_mapping(loader, node, deep=deep) + + +_DupSafeLoader.add_constructor( + yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _construct_mapping +) + + +def read_document(path: str | Path) -> tuple[dict, str]: + """Read a YAML/JSON document (bounded, duplicate-key-safe). + + Returns ``(data, sha256_of_file_bytes)``. + """ + p = Path(path) + try: + with open(p, "rb") as fh: + raw = fh.read(_MAX_SPEC_BYTES + 1) + except OSError as exc: + raise WeightPatchError("path", f"cannot read {p.name}: {exc.strerror}") from None + if len(raw) > _MAX_SPEC_BYTES: + raise WeightPatchError("schema", f"{p.name} exceeds {_MAX_SPEC_BYTES} bytes") + try: + data = yaml.load(raw.decode("utf-8"), Loader=_DupSafeLoader) # noqa: S506 - safe subclass + except (yaml.YAMLError, UnicodeDecodeError) as exc: + raise WeightPatchError("schema", f"{p.name}: invalid document: {exc}") from None + if not isinstance(data, dict): + raise WeightPatchError("schema", f"{p.name}: document must be a mapping") + return data, hashlib.sha256(raw).hexdigest() + + +def _wrap_validation(model, data, label: str): + from pydantic import ValidationError + + try: + return model(**data) + except ValidationError as exc: + details = "; ".join( + f"{'.'.join(str(x) for x in err['loc'])}: {err['msg']}" for err in exc.errors()[:8] + ) + raise WeightPatchError("schema", f"{label}: {details}") from None + + +def parse_patch_spec(data: dict) -> WeightPatchSpec: + return _wrap_validation(WeightPatchSpec, data, "weight patch spec") + + +def parse_inspect_request(data: dict) -> InspectRequest: + return _wrap_validation(InspectRequest, data, "weights inspect request") + + +def canonical_sha256(model: BaseModel) -> str: + payload = json.dumps( + model.model_dump(mode="json"), sort_keys=True, separators=(",", ":") + ) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +def load_patch_spec( + path: str | Path, *, context=None +) -> tuple[WeightPatchSpec, str]: + """Load a patch spec; resolve its paths through the project context if given. + + Returns ``(spec, spec_file_sha256)``. The hash is of the on-disk bytes, which + is what ``surface.weight_patch.sha256`` pins. + """ + declaring = Path(path).resolve() + data, digest = read_document(declaring) + spec = parse_patch_spec(data) + if context is not None: + spec = resolve_spec_paths(spec, context, declaring) + else: + spec = _resolve_plain(spec, declaring) + return spec, digest + + +def _resolve_plain(spec: WeightPatchSpec, declaring_file: Path) -> WeightPatchSpec: + """Without a project context, relative paths are relative to the spec file.""" + + def res(value: str) -> str: + p = Path(value) + return str(p if p.is_absolute() else (declaring_file.parent / p).resolve(strict=False)) + + update: dict = {"payload": spec.payload.model_copy(update={"path": res(spec.payload.path)})} + if spec.base.checkpoint: + update["base"] = spec.base.model_copy(update={"checkpoint": res(spec.base.checkpoint)}) + if spec.export is not None: + update["export"] = spec.export.model_copy( + update={"output_dir": res(spec.export.output_dir)} + ) + return spec.model_copy(update=update) + + +def _resolve_in_document(value: str, context, declaring_file: Path, access: str = "read") -> str: + """Resolve a path declared inside a weights document. + + Scheme references (``project://``, ``config://``...) and strict project mode + follow the project path rules. A plain relative path in legacy (standalone) + mode is relative to the declaring document -- the same meaning it has in + strict mode -- rather than to the process's working directory. + """ + from tuner.project import PathRef, resolve_path + + if context.path_mode == "legacy" and PathRef.parse(value).scheme is None: + p = Path(value) + return str(p if p.is_absolute() else (declaring_file.parent / p).resolve(strict=False)) + return str(resolve_path(value, context, declaring_file=declaring_file, access=access)) + + +def resolve_spec_paths(spec: WeightPatchSpec, context, declaring_file: Path) -> WeightPatchSpec: + def res(value: str, access: str = "read") -> str: + return _resolve_in_document(value, context, declaring_file, access) + + base_update = {} + if spec.base.checkpoint: + base_update["checkpoint"] = res(spec.base.checkpoint) + update: dict = { + "base": spec.base.model_copy(update=base_update), + "payload": spec.payload.model_copy(update={"path": res(spec.payload.path)}), + } + if spec.export is not None: + update["export"] = spec.export.model_copy( + update={"output_dir": res(spec.export.output_dir, "write")} + ) + return spec.model_copy(update=update) + + +def load_inspect_request(path: str | Path, *, context=None) -> InspectRequest: + declaring = Path(path).resolve() + data, _ = read_document(declaring) + req = parse_inspect_request(data) + def res(value: str) -> str: + if context is not None: + return _resolve_in_document(value, context, declaring) + p = Path(value) + return str(p if p.is_absolute() else (declaring.parent / p).resolve(strict=False)) + + projections = [] + for proj in req.projections: + if proj.vector is not None and proj.vector.safetensors is not None: + vf = proj.vector.safetensors.model_copy(update={"path": res(proj.vector.safetensors.path)}) + proj = proj.model_copy(update={"vector": proj.vector.model_copy(update={"safetensors": vf})}) + elif proj.vector is not None and proj.vector.direction_json is not None: + df = proj.vector.direction_json.model_copy( + update={"path": res(proj.vector.direction_json.path)} + ) + proj = proj.model_copy(update={"vector": proj.vector.model_copy(update={"direction_json": df})}) + projections.append(proj) + return req.model_copy(update={"checkpoint": res(req.checkpoint), "projections": projections}) diff --git a/MechInterp/weights/workflow.py b/MechInterp/weights/workflow.py new file mode 100644 index 000000000..3b267be96 --- /dev/null +++ b/MechInterp/weights/workflow.py @@ -0,0 +1,89 @@ +"""Orchestration for ``mechinterp weights-inspect`` / ``weights-patch``. + +``validate`` = open the LOCAL checkpoint, verify the declared source binding and +the targeted base bytes, load/verify the payload, and plan the patch against the +checkpoint's own tensors (budget enforced on the realized result). Nothing is +written. ``export`` does the same and then writes the exact modified checkpoint. +""" + +from __future__ import annotations + +from pathlib import Path + +from MechInterp.weights.checkpoint import ( + LocalCheckpoint, + inspect_checkpoint, + open_checkpoint, + verify_binding, +) +from MechInterp.weights.errors import WeightPatchError +from MechInterp.weights.export import export_checkpoint +from MechInterp.weights.patch import ( + PatchPlan, + Payload, + buffer_to_tensor, + build_plan, + load_payload, +) +from MechInterp.weights.safetensors_io import read_region +from MechInterp.weights.spec import ( + InspectRequest, + WeightPatchSpec, + load_inspect_request, + load_patch_spec, +) + + +def inspect_from_config(path: str | Path, *, context=None) -> dict: + request: InspectRequest = load_inspect_request(path, context=context) + return inspect_checkpoint(request) + + +def _read_from_checkpoint(ckpt: LocalCheckpoint): + def read_tensor(name: str): + sf, entry = ckpt.entry(name) + return buffer_to_tensor(read_region(sf, entry), entry.torch_dtype, entry.shape) + + return read_tensor + + +def plan_against_checkpoint( + spec: WeightPatchSpec, spec_sha256: str +) -> tuple[LocalCheckpoint, dict, Payload, PatchPlan]: + if not spec.base.checkpoint: + raise WeightPatchError("schema", "base.checkpoint is required for weights-patch") + ckpt = open_checkpoint( + spec.base.checkpoint, allow_symlinked_files=spec.base.allow_symlinked_files + ) + binding = verify_binding(spec, ckpt) + payload = load_payload(spec) + plan = build_plan(spec, spec_sha256, payload, _read_from_checkpoint(ckpt)) + return ckpt, binding, payload, plan + + +def validate_patch_config(path: str | Path, *, context=None) -> dict: + spec, digest = load_patch_spec(path, context=context) + _, binding, _, plan = plan_against_checkpoint(spec, digest) + return { + "mode": "validate", + "written": False, + "binding": binding, + "budget": spec.budget.model_dump(mode="json"), + "receipt": plan.receipt(), + } + + +def export_patch_config(path: str | Path, *, context=None) -> dict: + spec, digest = load_patch_spec(path, context=context) + if spec.export is None: + raise WeightPatchError("schema", "the spec has no export block (export.output_dir)") + ckpt, binding, _, plan = plan_against_checkpoint(spec, digest) + manifest = export_checkpoint(spec, digest, plan, ckpt, binding) + return { + "mode": "export", + "written": True, + "output_dir": spec.export.output_dir, + "patch_digest": manifest["patch_digest"], + "totals": manifest["totals"], + "manifest": manifest, + } diff --git a/docs/MECH_INTERP_CELLS.md b/docs/MECH_INTERP_CELLS.md index 9bfdf19ec..373178685 100644 --- a/docs/MECH_INTERP_CELLS.md +++ b/docs/MECH_INTERP_CELLS.md @@ -16,6 +16,8 @@ recipe. There are four verbs: | `mechinterp probe-fit` | fit a linear readout from extracted activations and freeze a direction JSON | | `mechinterp steer` | run the six-block declarative intervention cell (smoke-gated) | | `mechinterp score-gates` | evaluate a declarative `gates.yaml` against a per-row output JSONL | +| `mechinterp weights-inspect` | (experimental) read-only report on a LOCAL safetensors checkpoint, with bounded numeric projections | +| `mechinterp weights-patch` | (experimental) validate or create-only export a declarative base-weight patch | Example recipes ship under `MechInterp/configs/templates/`. List them with `python tuner.py mechinterp list-configs`. @@ -108,7 +110,16 @@ python tuner.py mechinterp score-gates \ ``` `extract` and `steer` load a model and use a GPU, so they refuse to run without -`--i-know-this-runs-on-gpu`. `probe-fit` and `score-gates` are CPU-only. +`--i-know-this-runs-on-gpu`. `probe-fit`, `score-gates`, `weights-inspect` and +`weights-patch` are CPU-only (`weights-*` need torch only to validate/apply a patch +or to compute projections, never a GPU). + +`mechinterp run` stage commands are compiled as `python -m tuner mechinterp ...` +(the installed-wheel form; there is no `tuner.py` in a wheel). Stages run in the +project workdir, and a source checkout's engine root is put on `PYTHONPATH` so the +module resolves; a host project must not contain its own top-level `tuner/` +package. `dose-calibrate` honors `--model-revision` (stage or pipeline +`model_revision`) exactly like `steer` and `extract`. ## Gates @@ -180,3 +191,197 @@ both before launching a cell, especially on a fresh or retried remote container. The steer cell's own smoke-first gate and `expected_config_sha` guard cover a third failure mode (running an edited or unverified cell), so a full launch is gated on a recorded smoke pass for the exact config. + +## Experimental: weight patches, module-site capture, weight inspection + +These are explicitly experimental MechInterp CLI capabilities, not part of the +stable public API. They are generic: every tensor name, shape, value, index and +restriction comes from a spec/recipe, never from engine code. + +### `mechinterp-weight-patch/v1` + +```yaml +schema_version: mechinterp-weight-patch/v1 +base: + model_id: org/name # informational + revision: <40-hex commit id> # required; the run's --model-revision must equal it + checkpoint: path/to/local_dir_or_file.safetensors # needed by weights-patch only + index_sha256: # of model.safetensors.index.json (or the single file) + files_sha256: {shard.safetensors: } # optional, whole-file pins + allow_symlinked_files: false # true for HF cache snapshot dirs (links to regular files only) + runtime_prefix_rules: [] # [{checkpoint_prefix, runtime_prefix}] if loaded names differ + tensors: # EVERY targeted tensor, pinned to exact stored bytes + : {dtype: bfloat16, shape: [out, in], sha256: } +budget: # all required except the last two + allowed_tensors: [""] + max_modified_tensors: 4 + max_modified_entries: 100000 # entries whose STORED value actually changes + max_relative_frobenius: 0.05 # per tensor, ||W'-W||_F / ||W||_F on the realized delta + max_payload_bytes: 268435456 + max_index_count: 1000000 +payload: {path: patch.safetensors, sha256: } # all numeric arrays live here +operations: + - {id: a, tensor: , op: add_rank_one, scale: 1.0, cols: [3, 9], + arrays: {u: a.u, v: a.v}} # W[R][:, C] += scale * outer(u, v) + - {id: b, tensor: , op: project, axis: output, normalize: false, + arrays: {direction: b.d}} # W[:, C] -= scale * d (d^T W[:, C]) (axis: input -> rows) + - {id: c, tensor: , op: replace_rows, rows: [2, 5], arrays: {values: c.v}} + - {id: d, tensor: , op: replace_cols, arrays: {values: d.v, cols: d.idx}} +export: {output_dir: path/new_checkpoint_dir, sidecar_files: ["*.json"]} # weights-patch --export +``` + +Rules enforced before anything is applied or written: schema (unknown fields, +NaN/Inf, bool-as-number, duplicate YAML keys all refuse); every operation tensor +pinned and matched by `allowed_tensors`; indices distinct and in range (inline, or +integer payload arrays via `arrays.rows`/`arrays.cols`, never both); payload sha256 +and exact array inventory (extra arrays refuse); finite payloads; base tensor +dtype/shape/byte hash; finite budgets on the realized result. `project` needs a +unit direction unless `normalize: true`. A zero-valued (or sub-ulp) patch changes no +byte: only entries whose value differs numerically are rewritten, so it is a true +no-op (`noop: true` in the receipt) and unchanged entries (even `-0.0`) keep their +exact bytes. bfloat16 is hashed and written as bf16 bytes; arithmetic is float32 +(float64 for float64 tensors) then cast. + +**Source binding.** Checkpoint files must be local regular files (no symlinks +unless `allow_symlinked_files`), index shard names plain, every shard header +strictly valid, and the index and headers must agree exactly. A bare revision +string cannot be authenticated from file bytes, so binding has two legs: exact +content pins (`index_sha256`/`files_sha256`, plus the per-tensor byte hashes), +and local revision evidence when present (an HF `snapshots/` directory name or +`.cache/huggingface/download/*.metadata`). Contradicting evidence refuses; with no +evidence the content pins are required. `model.config` names are never used. + +**CLI** + +```bash +python tuner.py mechinterp weights-inspect --weights-config inspect.yaml [--json] +python tuner.py mechinterp weights-patch --weights-config patch.yaml --validate [--json] +python tuner.py mechinterp weights-patch --weights-config patch.yaml --export [--json] +``` + +Exactly one of `--validate` / `--export`. `--validate` writes nothing. `--export` +stages a sibling directory, copies every shard and overwrites only the modified +tensors' byte ranges (headers, metadata and untouched tensors stay byte-identical, +verified by re-hashing), copies the index and `sidecar_files`, writes +`mechinterp-weight-export.manifest.json` (spec/payload/base-file digests, per-tensor +before/after hashes, realized deltas, output file hashes, `patch_digest`), then +renames into place. An existing destination is refused, never overwritten. +On filesystems that reject exclusive directory rename (including some external +drive mounts), export exclusively creates the destination, copies and re-hashes +the verified files, then writes the completion manifest last. The manifest +records `publication.method: exclusive_directory_manifest_last`. This fallback +does not publish the directory atomically. Require a valid completion manifest +before loading it. A killed export may leave an incomplete directory; preserve +it as failed evidence and choose a fresh destination for a retry. +Refusals exit 1 with `WEIGHTS_` (`SCHEMA PATH INDEX BINDING BASE_HASH_MISMATCH +PAYLOAD NONFINITE BUDGET OUTPUT_EXISTS APPLY`). + +### `weight_patch` in `steer` / `dose-calibrate` / `extract` + +Steer and dose generation records retain `generated_token_ids` (through the first +EOS, inclusive). Use these for exact token parity; decoded-text equality alone +does not establish token equality. Pool metadata cannot override this field. + +```yaml +surface: # extract: top-level `weight_patch:` + weight_patch: {path: patches/edit.yaml, sha256: } +``` + +Applied in memory to the freshly loaded BASE model (before any adapter, generation +or capture); no checkpoint is exported per candidate. Before the model loads the +spec bytes and payload are verified and `--model-revision` must equal +`base.revision`. After load, the targeted tensors of the loaded module are checked +against the pinned byte hashes (a wrong base refuses whatever its config says), +a resolved `config._commit_hash` must agree, and the patch is committed +all-or-nothing (rolled back and re-verified on any failure). Internal implementation +(not a public API): `MechInterp.weights.runtime.prepare_patch`, `apply_patch(...)` +(returns an `AppliedPatch`; `.revert()` or `with patched(model, prepared)`). + +Steer/dose lineage: an absent patch leaves behavior and `compute_config_sha` unchanged. With a +patch, the pinned sha is part of the config sha; per-row records carry +`weight_patch_digest`; the smoke state records it (a smoke taken without or under +another patch is not reusable); manifests carry the receipt; and +`.weight_patch.json` binds the output rows to the patch (the digest covers +spec, payload, revision and exact before/after tensor bytes). A resume over rows from +another or no patch is refused. Exit codes: `6` stale lineage, `7` patch refused +(before any row is written). + +Limits: a Hub-id load is bound by the revision it was loaded at plus the targeted +tensor hashes (only targeted tensors are verified, not the whole model); the +default loader is bfloat16 so patches over non-bf16 checkpoints refuse by hash; +quantized params are refused; an adapter is attached after the patch. + +### `capture_sites`, `use_cache`, `forward_only` (extract) + +```yaml +capture_sites: + - {layer: 20, module: mlp.down_proj, tensor: input} # or output +use_cache: false # teacher-forced capture forward; true for hybrid/KV-sharing models +forward_only: false # true: no generation; families must be [anchor]; content_end_fn unused +resume: true # append/fsync per completed row; verify identity and files before skipping +``` + +`layer` is the decoder BLOCK index from `get_decoder_layer` (the `law.layer` +convention), not the `hidden_states` index used by residual `layers` (index k there +is block k-1's output). `module` is a dotted path inside the block; `input` is the +first positional argument. Only the selected family positions are indexed inside the +hook (no sequence cache); each is written float32 to +`__.sites.safetensors` (a separate file, so probe-fit never sees it) +as `L..` with file metadata, and per-row/manifest metadata +records site, layer, convention, shape, source dtype and positions. Hooks exist only +for the capture forward and are removed on any error. Residual tensor values are +unchanged when these options are absent (`use_cache` defaults to false). For an +anchor-only read use `forward_only: true` (or `max_new_tokens: 1` with a +`content_end_fn`). + +Extraction output directories must be empty unless `resume: true` opens their +matching `capture.runlog.jsonl`. The resume fingerprint binds rendered prompts, +row keys, capture settings, the patch receipt, file-backed render/content-end +callables, and model sources (pinned Hub revision or complete local file hashes). +Hub adapters cannot resume without a local, hashable snapshot. Every row's tensor +files are fsynced and hashed before its journal append is fsynced. Resume verifies +all committed files and skips those rows; interrupted uncommitted rows are retried. +Use one writer per directory. `manifest.json` is published atomically on completion. +Probe fitting reads only that manifest's captured rows and verifies their hashes; +it refuses incomplete captures and ignores stray files. New manifests are +`mechinterp-capture/v2`; unpatched historical manifests can still be read. + +Simple portable row keys keep their filenames. Other keys use `row-`. +Missing keys, duplicates, case-insensitive filename collisions, and encoded-name +collisions are refused before generation. Per-row `capture_files` and +`site_captures` map original keys to the actual filenames and hashes. + +### `weights-inspect` projections (bounded numeric reads) + +```yaml +schema_version: mechinterp-weights-inspect/v1 +checkpoint: path/to/local_checkpoint +tensors: [""] # list matching tensors (capped by max_listed_tensors) +hash_tensors: true # adds sha256 + a paste-ready base.tensors snippet +max_output_values: 16384 # total numbers all projections may emit (<= 1_000_000) +max_tensor_bytes: 2147483648 # largest tensor a projection may read +projections: + - id: col_dots + tensor: <2-D float tensor> + axis: cols # cols -> W[:, j]; rows -> W[i, :] + indices: [12, 40] # omit for every line (still capped) + other_indices: [0, 1, 2] # optional: restrict positions along each line + kind: dot # dot | cosine | slice + include_norms: true # dot/cosine: also |line| + vector: # exactly one source + safetensors: {path: v.safetensors, key: axis, sha256: } + # direction_json: {path: direction.json, sha256: } # mechinterp-direction/v1 + # inline: [0.1, 0.2] # <= 65536 numbers +``` + +Reads one tensor at a time, converts only the selected lines to float64, and +refuses (`BUDGET`) before reading when the emitted value count would exceed +`max_output_values`. `dot`/`cosine` emit one number per selected line (`cosine` is +`null` for a zero line); `slice` emits raw `[lines, positions]` values. Each result +carries the tensor sha256, shape/dtype and vector provenance. No model is loaded. + +Readback measures before and after projections in the same float32 direction +with float64 accumulation, including when the model writes bf16 tensors. Using +a bf16-rounded direction for only the after projection fabricates off-target +movement on unchanged rows. The inactive-row no-op regression requires exact +zero movement; the smoke tolerance and intervention arithmetic are unchanged. diff --git a/docs/batch-inference.md b/docs/batch-inference.md index 7b84eeb2c..3344213e2 100644 --- a/docs/batch-inference.md +++ b/docs/batch-inference.md @@ -260,3 +260,17 @@ python tuner.py batch-capture \ > Local lane on a slow disk (e.g. a 9P-mounted drive): point `--out-dir` at fast > local scratch (ext4 `~/` or `/tmp`) and use `--sync-cmd` to move artifacts to > the slow drive once, rather than writing tensors there per row. +# HF structured-decoding fallback + +`batch-generate --engine hf-batched --json-schema schema.json +--structured-output-backend xgrammar` uses the optional XGrammar Transformers +logits processor. A fresh matcher is created per independent generation batch; +the runtime records its XGrammar/Transformers/Torch versions. Unconstrained HF +generation requires no grammar package. Conditional generation models registered +with Transformers can serve text-only prompts through their registered auto +class. Weight-loading errors are not caught and retried through another loader. + +HF batch size one removes batch-composition changes but still requires actual +model repeat/permutation and hard-kill/resume checks on the consuming study's +hardware. It does not inherit vLLM's batch-invariance guarantee. A change of +backend is prospective and must be registered before scientific generation. diff --git a/docs/experimental/weight-editor-codex-account-adapter.md b/docs/experimental/weight-editor-codex-account-adapter.md new file mode 100644 index 000000000..1da73c45e --- /dev/null +++ b/docs/experimental/weight-editor-codex-account-adapter.md @@ -0,0 +1,223 @@ +# Weight editor: Codex account adapter (experimental, unqualified) + +`synaptic_tuner.experimental.weight_editor.adapters.codex_account.CodexAccountAdapter` +is a `ModelAdapter` that drives the locally installed Codex CLI through the +operator's existing ChatGPT login. It is not a Tuner API v1 promise. Synthetic +fake-executable tests pass. **It has not been run against a real model and is +not qualified for any study.** + +## Transport + +Each broker turn launches one subprocess, using argv lists and never a shell: + +- If the turn has no session, the adapter runs + `codex exec --json --ignore-user-config --ignore-rules --strict-config --skip-git-repo-check --output-schema /response-schema.json -m -c ... -`. + This also covers a core bootstrap after a handoff. +- If the turn has a session, it runs + `codex exec resume -`. + +The prompt is passed on stdin as canonical JSON of the shape +`{"schema":"codex_account_turn/v1","turn_id","turn_index","messages":[...]}`. + +`resume` does not accept `--sandbox` or `--cd`. For that reason both forms set +`sandbox_mode="read-only"` with `-c`, and the process `cwd` is the private +`work_dir`. Both forms use identical flags, and a test asserts this. + +### Config overrides (`-c`) + +- `model_provider="openai"`, `forced_login_method="chatgpt"`, + `approval_policy="never"`, `sandbox_mode="read-only"`, + `web_search="disabled"`. +- `model_instructions_file=/instructions.md`. These are neutral + protocol instructions, replaceable through `instructions_text`, and their + bytes are bound into the identity. +- `project_doc_max_bytes=0` and `project_doc_fallback_filenames=[]`. +- `include_{permissions,apps,collaboration_mode}_instructions=false` and + `include_environment_context[_time]=false`. +- `show_raw_agent_reasoning=false`, `hide_agent_reasoning=false`, + `notify=[]`, `mcp_servers={}`. +- `cloud.skills.enabled=false`, `skills.include_instructions=false`, + `tools.update_plan.enabled=false`, + `tools.experimental_request_user_input.enabled=false`. +- `features.=false` for each name in `DISABLED_FEATURES`. That list is the + union of: + - the source paper's `harness/codex_config.toml`, and + - the override list codex-cli 0.166.0 applies to its own internal tool-free + "temporary structured thread". That list was recovered from the binary's + strings and was not confirmed by running the binary. +- Requested settings: only `reasoning_effort`, `reasoning_summary` and + `verbosity`, mapped to `model_*` keys. Any other setting key is refused + rather than dropped. + +### Environment + +Only these names are passed from `base_env` (default `os.environ`): `PATH`, +`HOME`, `USER`, `LOGNAME`, `LANG`, `LC_*`, `TZ`, `SSL_CERT_*` and `CODEX_HOME`. +`NO_COLOR=1` is added. + +If any API-key or billing variable is present, construction is refused. This +covers `OPENAI_*`, `CODEX_*` and `AZURE_OPENAI_*` names ending in `KEY`, +`TOKEN`, `BASE_URL` and similar. + +When `verify_login=True`, `codex login status` must report ChatGPT. Only a +boolean is retained from that check. + +`HOME` and `CODEX_HOME` are never repurposed. The adapter checks for the +existence of `$CODEX_HOME/AGENTS.md`, `AGENTS.override.md`, `skills/` and +`plugins/`, `~/.agents` and `/etc/codex/*` but never reads them. Those +existence observations are bound into the effective config. + +## Identity + +`identity()` returns the following: + +- `provider`, `model` and `settings`, exactly as in the config. + `provider` must be `openai-codex-chatgpt-account`. +- The client's version and sha256. Both are pinned by the operator, the + sha256 is re-checked before every turn, and drift raises `client_drift`. +- The effective config: argv templates, cwd, env names, instruction and + schema sha256, and environment observations. Its digest is + `effective_config_sha256`. +- Auth mode, `returned_identity: {"source":"client_reported_only","synthesized":false}`, + the qualification mode and its blockers, and the capabilities. + +The core hashes the adapter source. Any change to these values is identity +drift, and the broker refuses to resume. + +## Capture + +The adapter yields three kinds of event, in this order: + +1. `client_input` before the process starts: the launch record (argv, cwd, + env names, stdin sha256/size, pins, resume thread id), then the exact stdin + bytes. +2. `provider`: every stdout JSONL line, byte-exact with its trailing newline. + A partial final line is yielded as-is and then raises `truncated_stream`. +3. `client_stderr`: stderr chunks, byte-exact as they arrive. + +Both pipes are multiplexed with `selectors`, so neither pipe can deadlock. The +stdout line buffer is the only accumulation. It is bounded by +`max_line_bytes` (default 64 MiB), which raises `line_too_long`. There is no +token or cost cap. + +## Normalization (`parse_event`) + +The mapping is stateless and runs again in `run_turn`, so the adapter and the +broker see the same normalized events. + +| Codex event | Broker kind | +|---|---| +| `thread.started` | `session` with `session_id`. `model` is included only if the client reported one. | +| `turn.started` | `session` | +| `turn.completed` | `finish` with `status: "completed"` and `usage` | +| `turn.failed` / `error` | `finish` with status `failed` or `error`. The adapter then raises `provider_error`. | +| `item.*` of type `reasoning` | `reasoning_summary` (`source: client_exposed_summary`). Hidden reasoning is never claimed. | +| `item.completed` of type `agent_message` whose text starts with `{` | Must be the exact envelope `{action, operation, arguments_json, choice, proposal, rationale}`. It becomes `request` (`operation`, `arguments` from strict-parsed `arguments_json`, `rationale`) or `final_choice` (`choice`, `rationale`, `proposal` if any). A malformed envelope raises, and the broker records it as `unknown`. | +| Any other `agent_message` text | `message`. Prose never becomes a request. | +| `command_execution`, `file_change`, `mcp_tool_call`, `web_search`, `todo_list`, `collab_tool_call` | `unknown` with `native_tool_item` | +| Any other type | `unknown` | + +The original agent text is preserved by the broker's raw reference. It is not +copied into the request payload, because admission accepts only +`operation`, `arguments`, `rationale` and `label`. + +## Fail-closed checks + +In every failure case below, the bytes are yielded first and `AdapterFailure` +is raised afterwards. The adapter never retries. Where possible, the process +group is killed immediately so that a native tool or a client-internal +reconnect cannot continue. + +- `native_tool_event`, `unknown_provider_event`, `malformed_provider_event` + and `provider_error`. +- `missing_thread_start` and `session_drift`. On resume, the reported thread + id must equal the journaled session. +- `multiple_turns`, `unbalanced_turn`, `output_after_completion` and + `missing_turn_completion`. +- `multiple_actions` and `no_structured_action`. The last agent message must + be the one structured action. +- `truncated_stream`, `line_too_long` and `nonzero_exit`. +- `work_dir_dirty`: the private cwd must be empty before and after every turn. +- `client_drift` and `control_drift`. +- `returned_model_unobserved`: no normalized event on a clean turn carried a + client-reported model. Nothing is synthesized from the requested model. +- These are refused before spawning: + - `resume_after_interruption`: `TurnInput.resumed` together with a session. + - `session_invalid`. + - `missing_bootstrap`. +- `AdapterTimeout`, raised only when the optional `turn_timeout_s` is set. +- `AdapterCancelled`, raised by `cancel()` from any thread. Closing the + generator also cleans up. In both cases the process group is sent SIGTERM, + then SIGKILL after `kill_grace_s`. + +## Modes and qualification + +`mode` has no default. + +- `probe` runs the adapter and reports `qualified: false` along with its + blockers. +- `qualified` requires a `qualification_record` JSON with: + - `schema: codex_account_qualification/v1`; + - `client_sha256`, `effective_config_sha256` and `model`, matching the + adapter; + - `verified.{native_tool_catalogue_empty, model_visible_instructions, returned_model_reported, no_client_internal_retry}` + all true; + - `evidence_sha256`. + +The record's sha256 is bound into the identity. The adapter checks only that +the record is consistent. It cannot verify the evidence itself. + +## Composition + +```python +from synaptic_tuner.experimental.weight_editor.adapters.codex_account import build_codex_account_ports +ports = build_codex_account_ports(ctx, executor=my_real_executor, + codex_path=..., expected_sha256=..., expected_version="codex-cli 0.166.0", + work_dir=empty_private_dir, control_dir=adapter_control_dir, mode="probe", + acknowledged_markers=(...)) +``` + +`ctx.model` is the only source of model identity. The caller must supply a +real `Executor`. There is no executor default and no fake. + +`work_dir` ancestors that contain `.git`, `AGENTS.md`, `AGENTS.override.md`, +`.codex` or `.agents` are refused unless they are listed exactly in +`acknowledged_markers`. User-level `CODEX_HOME` and `~/.agents` are recorded +as environment observations instead. Use a `work_dir` outside any repository +for real runs. + +## Unresolved gaps (block qualification) + +1. **The model-visible tool catalogue is not observable.** `codex exec --json` + does not export the tool list sent to the provider. `codex debug + prompt-input` renders input items, not tools, and has no + `--ignore-user-config`. Disabled flags are configuration intent, not a + measured catalogue. +2. **The model-visible instruction set is not observable.** It is unknown + whether `$CODEX_HOME/AGENTS.md` (present on this machine) and user skills + are injected under `--ignore-user-config`. They are probably still loaded. + Checking this means rendering the prompt with the owner's real + `CODEX_HOME`, which exposes private instructions. That is the parent's + decision. +3. **The returned model is not reported.** Codex 0.166.0 exec JSONL has no + model field. Under the new core contract every clean turn needs observed + returned identity, so **every real turn currently fails closed with + `returned_model_unobserved`**. The adapter forwards a `model` field if a + future client emits one. Other possible evidence sources (rollout files, + response headers) are not exported by exec. Reading the session store + would touch the owner's other sessions. +4. **Client-internal retries cannot be disabled or fully observed.** + Stream and request retries happen inside the built-in `openai` provider. + Only retries that surface as `error` events are detected, and the process + is killed when one appears. +5. **`--strict-config` may not cover `-c` overrides.** Help text documents it + for `config.toml`. A misspelled override might be ignored silently. + `agents.enabled=false` from the paper is omitted because the key was not + found in the 0.166.0 binary. +6. **Silent compaction is undetectable** unless it surfaces as an unknown + item, which raises. +7. **Provider threads persist in the owner's `$CODEX_HOME/sessions`.** + `--ephemeral` would break `resume`. +8. **The exec JSONL item shapes come from the binary's strings and documented + behaviour, not from a live capture.** The first real probe should be + checked for unknown events, which raise. diff --git a/docs/experimental/weight-editor.md b/docs/experimental/weight-editor.md new file mode 100644 index 000000000..e67d7c08f --- /dev/null +++ b/docs/experimental/weight-editor.md @@ -0,0 +1,264 @@ +# Weight-editor broker and recorder (experimental) + +`synaptic_tuner.experimental.weight_editor` is a model-independent, CPU-only +broker and append-only recorder for agent-led weight-editing research. It is +**experimental and not a Tuner API v1 promise**: nothing here is listed in the +v1 support matrix, and the stable API is unchanged. The core has no dataset +fields, no model names and no provider code. Optional adapters live separately +under `adapters/`; the Codex account adapter is implemented but unqualified (see +`weight-editor-codex-account-adapter.md`). A study (for example the EHR +research) owns its scientific policy and composes the real model adapter and +executor outside this package. + +The state machine is `registered -> discovery -> final_patch_frozen -> +independent_evaluation -> closed`. The editor can only move through the first +three; the last two are host actions (`advance`). There is no transition back +to discovery, and the core implements no scientific verdict. + +## What it guarantees, and what it does not + +Enforced by the host broker, independent of model compliance: + +- Requests are admitted only for operations in the config, with arguments that + match the declared schema. Objects are opaque ids resolved against a + hash-frozen capsule of development objects. Paths, URLs, commands, imports, + policy, budget and split fields in a request are denied before any + reservation or executor call. +- Unknown, withheld (held-out) and wrong-kind ids are denied. The model sees one + generic message for unknown and withheld ids; the audit trail records which. +- Writes go only to `artifacts//` through a create-only writer. + A model cannot name a capsule object as a write target. The output root must + not overlap the capsule or any `read_only_roots`. +- Every dispatch is written ahead (`dispatch_intent`, fsynced) before the + executor runs. After a crash the broker asks the executor to reconcile by + dispatch id: `complete` (receipt recovered), `unstarted` (executor attests + with the dispatch id and a basis; the broker redispatches once), or `unknown` + (run halts `reconciliation_needed`; the reservation stays charged). Nothing is + re-executed implicitly, and an executor exception after dispatch is treated + as unknown. +- Resource limits are optional and owned by the caller. Reservations, + commitments and denied attempts are folded from the journal, so a resume + never resets a charge. Charge on completion is `max(reserved, reported)`. + Negative, NaN and infinite amounts are rejected. + Limits without a configured operation-cost meter or built-in counter are + refused. Provider usage is recorded as evidence; it is not an implicit billing + meter. `dispatch_attempts` is checked before initial dispatch and redispatch. +- The run identity binds config bytes, capsule manifest and object bytes, the + requested model block, adapter and executor identity (class, source hash, + declared identity and Python package sources), the broker package sources, + and a caller-supplied binding. External binaries, dependencies and non-Python + resources must be pinned by the port identity or caller binding. A resume under any change + is refused, without calling the adapter or executor, and the refusal is + journaled. + Plain-module and uninspectable/dynamic ports are refused. Package import + initializers and the top-level version module are included; the source scope + is recorded rather than silently accepting an empty or one-file binding. +- A single writer holds an `flock` on the run for the process lifetime; the + kernel releases it on SIGKILL. +- `provider/events.jsonl` keeps every raw provider event byte-for-byte + (base64) in a hash chain. `journal/events.jsonl` is the normalized hash-linked + journal; unknown or unparseable events are kept and mark capture incomplete. + Every record is fsynced before the next effect. + `TransportEvent` additionally retains exact `client_input` and `client_stderr` + bytes on named streams. These streams cannot issue requests or choices. + Independent pipes are ordered as observed, without claiming a physical total + order. Diagnostics containing invalid UTF-8 remain available as base64. +- Success needs a validated `final_choice`; final assistant text is never + success. A run that stops early is `incomplete` and has no terminal manifest. + Each clean turn needs returned-model evidence; model fields on any normalized + event are checked. Failed, interrupted, unknown and truncated turns have their + requests and choices denied before dispatch. An explicit resume may continue + the conversation, but capture remains unqualified for the lifetime of that run. + Patch selection requires its validated receipt to have been delivered in an + earlier clean model turn. Receipt delivery in a failed turn is retried with + its recorded bootstrap and tool replies. No-session retries and handoffs resend the instructions + and catalog in the journaled model input. + +Not guaranteed: + +- **No OS isolation.** The writer is a cooperative API. An adapter or executor + that touches the filesystem or network itself is outside the guarantee, and + `declared_isolation` is only what the port says about itself. A normal + subagent or CLI session is not an isolated environment. +- **Hidden reasoning is neither captured nor claimed.** Only provider-exposed + events and summaries are retained. +- An internally chained directory detects inconsistent edits, not a malicious + writer who rewrites the chain and sidecars together. Boundary truncation of an + incomplete run is also undetectable without an independent anchor. `verify` + explicitly reports its integrity scope. It does not reparse raw provider bytes + using a dynamically loaded adapter. At freeze, use `anchor` to retain the final + selection, terminal, binding and chain hashes outside the run output tree. + The host must place that hash-only anchor under independent custody (for + example, a Git commitment) before evaluation. A second mutable file owned by + the same process provides no protection against an attacker rewriting both. + `advance` requires the external anchor and verifies all receipts and artifacts. +- Transcript replay reconstructs what was observed. It never re-asks a model. + +## Quick start + +```bash +# deterministic synthetic smoke with fake ports (no model, no GPU, no network) +python -m synaptic_tuner.experimental.weight_editor smoke --workdir scratch/editor-smoke + +python -m synaptic_tuner.experimental.weight_editor validate --config C --ports MOD:FACTORY [--ports-arg K=V ...] +python -m synaptic_tuner.experimental.weight_editor run --config C --run-id ID --ports ... [--binding-file B.json] +python -m synaptic_tuner.experimental.weight_editor resume --config C --run-id ID --ports ... [--recover-partial-tail] +python -m synaptic_tuner.experimental.weight_editor verify --run-dir DIR # alias: status +python -m synaptic_tuner.experimental.weight_editor anchor --run-dir DIR --output EXTERNAL_FREEZE.json +python -m synaptic_tuner.experimental.weight_editor verify --run-dir DIR --anchor-file EXTERNAL_FREEZE.json +python -m synaptic_tuner.experimental.weight_editor replay --run-dir DIR [--output F] [--force] +python -m synaptic_tuner.experimental.weight_editor advance --run-dir DIR --to independent_evaluation|closed --reference TEXT --anchor-file EXTERNAL_FREEZE.json +``` + +Exit codes: `0` ok/complete, `1` refused or invalid input, `3` incomplete with +reconciliation needed, `4` incomplete for another reason (adapter failure, +budget exhausted, model drift, no final choice, capsule drift), `5` +verification or integrity failure, `6` editor completed with unqualified capture. +`capture_qualification.qualified` is distinct from the editor completion status; +evaluation admission and synthetic smoke require qualified capture. + +`validate` creates no run and makes no executor or model call. `run` registers a +new run and never overwrites an existing one. `--ports module:factory` is +chosen by the operator on the command line; it is never read from the config or +from a model request. The factory receives `PortContext(args, model)` and +returns `PortSet(adapter, executor)`. + +## Config (`weight_editor_config/v1`, strict JSON) + +Unknown keys, duplicate keys and `NaN`/`Infinity` are errors. + +```json +{ + "schema": "weight_editor_config/v1", + "model": {"provider": "…", "model": "…", "settings": {"…": "…"}, "allowed_returned": []}, + "capsule": {"manifest": "capsule/manifest.json"}, + "instructions": [{"role": "system", "object": "instr-main"}, {"role": "user", "text": "…"}], + "operations": { + "query_development": { + "description": "…", "selectable": false, "required": ["items"], + "arguments": {"items": {"type": "ref_list", "kind": "dev_item", "max_items": 4}}, + "cost": {"gpu_units": {"len_of": "items", "per_item": 0.5}} + } + }, + "output_root": "runs", + "read_only_roots": [], + "resources": {"limits": {"gpu_units": 2}}, + "final_choice": {"allow_no_edit": true, "max_rationale_chars": 20000}, + "withheld_id_digests": [""] +} +``` + +- `model` is required, with no default or fallback. The adapter's requested + identity must equal it exactly. `allowed_returned` lists provider aliases + accepted as the returned model; any other returned model halts the run as + `model_drift`. +- Argument types: `ref`, `ref_list` (capsule object ids of one `kind`), `int`, + `number` (finite, bounded), `enum`, `text` (bounded payload such as a patch; + never an authority), `artifact_name` (a fresh bare name). Argument names that + denote host authority (`path`, `command`, `import`, `url`, `policy`, + `budget`, `target`, …) are rejected at config load. +- `cost` values are constants, `{"from_arg": name}` or + `{"len_of": name, "per_item": n}`. Each admitted request also reserves one + `dispatches`. `resources.limits` is optional; **no default money, token or + time cap is invented**. Built-in meters `requests`, `model_turns` and + `dispatches` and `dispatch_attempts` can be limited too; every request attempt, including denied or malformed + requests, is counted. +- `selectable: true` marks operations whose `ok` receipts may be chosen by + `final_choice`. + +## Capsule (`weight_editor_capsule/v1`) + +```json +{"schema": "weight_editor_capsule/v1", "capsule_id": "…", + "objects": [{"id": "w.layer0", "kind": "tensor", "path": "tensors/w.layer0.json", + "sha256": "…", "split": "development"}]} +``` + +Every object must have `split: "development"`; anything else is rejected at +load. Paths must be relative, free of `..`, and resolve (including through +symlinks) inside the manifest's directory. Object bytes are re-verified at +registration, resume, and before every dispatch. + +## Ports + +`ModelAdapter`: `identity()` (requested `provider`/`model`/`settings`, optional +`client_version`, `capabilities.raw_events` must be `true`, +`captures_hidden_reasoning` must not be), +`run_turn(TurnInput) -> Iterator[bytes | TransportEvent]` +(exact raw events), `parse_event(bytes) -> {"kind": …}` with kinds `message`, +`reasoning_summary`, `request`, `final_choice`, `session`, `usage`, `finish`, +`handoff`, `truncation`, `unknown`. Anything else, or any parse error, is stored +as `unknown` with its raw bytes. Adapter exceptions are recorded as +`cancelled`, `timeout` or `provider_error` and halt the run; a later explicit +`resume` starts a fresh turn marked `resumed`. +Only a clean turn can authorize requests or choices. A provider that reports +model identity in usage or finish packets must include that actual `model` in +the normalized event. An adapter must not copy the requested name and call it +returned evidence. Missing identity prevents dispatch. Unknown/truncated traffic +halts before dispatch; raw bytes remain available and capture is unqualified. + +`Executor`: `identity()`, `supported_operations()` (a configured operation +outside it is rejected as `unsupported_capability` at validation, as is the case +for `analyze` in the fake executor), side-effect-free `validate()`, +`execute(Dispatch, BoundedWriter) -> Receipt`, and `reconcile(Dispatch) -> +ReconcileResult`. `reconcile` must never cause an effect. Raise +`ExecutorRejection` from `execute` only when no effect began. +`Dispatch.bound` carries resolved capsule paths for the executor only; they are +not journaled or shown to the model. + +The shipped `fakes` module provides `ScriptedAdapter`, `FakeEffectExecutor` +(an external fsynced effect ledger with crash-injection hooks) and +`write_fixture()`. All content is synthetic. + +## Run directory + +```text +// + manifest.json immutable binding (create-only) + config.json exact config bytes; capsule/manifest.json exact capsule bytes + lock flock single-writer + provider/events.jsonl raw provider events (base64, hash chain) + journal/events.jsonl normalized hash-chained journal + requests//receipt.json + artifacts//… artifacts/manifest.json (at completion) + final_selection.json hashes proposal, evidence, artifacts, budget and journal/raw heads + terminal_manifest.json binds the frozen record, selection, artifacts and capture status + transcript.md derived Markdown view + quarantine/ incomplete tail lines moved aside by audited recovery +``` + +Journal record types include `run_registered`, `turn_start` (exact model-visible +messages), `provider_event`, `request_received`, `request_denied`, +`request_admitted` (reservation), `dispatch_intent`, `dispatch_result`, +`dispatch_error`, `reconcile_attempt`, `reconcile_result`, `handoff`, +`adapter_error`, `turn_end`, `final_choice_received`, `final_choice_denied`, +`final_patch_frozen`, `run_halted`, `resume_started`, `resume_refused`, +`tail_recovery`, `editor_terminal` and `phase_advanced`. Each record carries +`run_id`, `seq`, `prev`, `digest`, linked request/dispatch/raw ids and its time. + +`verify` fails closed on any altered, reordered, missing or non-canonical line, +a broken raw reference, a partial final line, or a changed artifact, receipt, +selection or terminal manifest. A partial final line is only repaired by +`resume --recover-partial-tail`, which moves it to `quarantine/` (hash recorded) +and appends a `tail_recovery` record; corruption elsewhere is never repaired. + +## Tests + +```bash +python -m pytest tests/experimental/weight_editor -q +``` + +The tests drive the public CLI in subprocesses with the fake ports, including +real SIGKILL at the dispatch boundary. They write only under +`scratch/test-weight-editor/`. + +## Known gaps before a live run + +- No real subscription adapter or real executor exists here; the parent composes + and qualifies them. Whether a given adapter exports every required field and + restricts tools is unproven until measured. +- `analyze` (CPU Python) is intentionally unsupported by the shipped executor. +- An unresolved `unknown` dispatch has no operator override yet; the run stays + `reconciliation_needed` until the executor can resolve it. +- Turns are request/response batches. A streaming provider that expects tool + results mid-turn must be wrapped to that shape. diff --git a/shared/utilities/text_model.py b/shared/utilities/text_model.py new file mode 100644 index 000000000..90e0ddca2 --- /dev/null +++ b/shared/utilities/text_model.py @@ -0,0 +1,26 @@ +"""Load a text-generating Transformers auto model without naming architectures.""" +from __future__ import annotations + + +def load_text_generation_model(model_name, **kwargs): + from transformers import AutoConfig, AutoModelForCausalLM + + config = kwargs.pop("config", None) + if config is None: + config = AutoConfig.from_pretrained(model_name, **{ + key: kwargs[key] for key in ("revision", "token", "trust_remote_code", "cache_dir", "local_files_only", "subfolder") + if key in kwargs + }) + loader = AutoModelForCausalLM + if type(config) not in loader._model_mapping: + # Text-only calls can also use registered conditional-generation models. + # Other unsupported/custom configs retain AutoModelForCausalLM's normal + # dispatch and refusal behavior; weight-loading errors are never retried. + try: + from transformers import AutoModelForImageTextToText + except ImportError: + pass + else: + if type(config) in AutoModelForImageTextToText._model_mapping: + loader = AutoModelForImageTextToText + return loader.from_pretrained(model_name, config=config, **kwargs) diff --git a/synaptic_tuner/experimental/__init__.py b/synaptic_tuner/experimental/__init__.py new file mode 100644 index 000000000..963b81f08 --- /dev/null +++ b/synaptic_tuner/experimental/__init__.py @@ -0,0 +1 @@ +"""Experimental, unqualified capabilities. Nothing here is a Tuner API v1 promise.""" diff --git a/synaptic_tuner/experimental/weight_editor/__init__.py b/synaptic_tuner/experimental/weight_editor/__init__.py new file mode 100644 index 000000000..d823fe707 --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/__init__.py @@ -0,0 +1,10 @@ +"""Experimental, model-independent weight-editor broker and recorder. + +Not a Tuner API v1 promise. The core owns admission, budgets, write-ahead +dispatch, reconciliation and a hash-chained transcript; callers supply the +trusted ``ModelAdapter`` and ``Executor`` ports. See +``docs/experimental/weight-editor.md``. +""" + +__version__ = "0.2.0-experimental" +EXPERIMENTAL = True diff --git a/synaptic_tuner/experimental/weight_editor/__main__.py b/synaptic_tuner/experimental/weight_editor/__main__.py new file mode 100644 index 000000000..eb53e2f31 --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +raise SystemExit(main()) diff --git a/synaptic_tuner/experimental/weight_editor/adapters/__init__.py b/synaptic_tuner/experimental/weight_editor/adapters/__init__.py new file mode 100644 index 000000000..7e669831f --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/adapters/__init__.py @@ -0,0 +1,6 @@ +"""Experimental, unqualified ``ModelAdapter`` implementations for the weight editor. + +Nothing here is a Tuner API v1 promise. Adapters are trusted operator +composition: the caller supplies the ``Executor`` separately and the broker +still owns admission, budgets, write-ahead dispatch and the journal. +""" diff --git a/synaptic_tuner/experimental/weight_editor/adapters/codex_account.py b/synaptic_tuner/experimental/weight_editor/adapters/codex_account.py new file mode 100644 index 000000000..5824d11f5 --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/adapters/codex_account.py @@ -0,0 +1,750 @@ +"""Account-authenticated Codex CLI ``ModelAdapter`` (experimental, unqualified by default). + +Transport: one ``codex exec`` (first turn of a provider thread) or +``codex exec resume `` (later turns) subprocess per broker turn, using +the operator's existing ChatGPT login. No API key, no new billing path, no +model fallback, no retry. + +What this adapter guarantees (and tests with a fake executable): + +* argv is a list (no shell); every built-in tool switch this client version + exposes is overridden off; user config/rules, project docs and environment + context are excluded; the response is constrained by a JSON Schema envelope. +* exact stdout bytes are yielded line by line (newline included) on the + ``provider`` channel; stderr chunks on ``client_stderr``; the launch record + and the exact stdin prompt bytes on ``client_input`` *before* the process + starts. Nothing is synthesized on the provider channel. +* any native tool item, unknown packet, error/failed turn, malformed or + multiple final actions, truncated stream, missing ``turn.completed``, + nonzero exit, thread-id drift, client-binary drift, a dirtied work dir, or a + clean turn without client-reported returned model identity raises + ``AdapterFailure`` after the bytes were yielded (so the broker retains them). + The adapter never retries. + +What it does NOT establish (see ``docs/experimental/weight-editor-codex-account-adapter.md``): +the model-visible tool catalogue, the model-visible instruction set, the +server-returned model, and the absence of client-internal transport retries +are not observable from ``codex exec --json``. ``mode="probe"`` runs and lists +these as blockers; ``mode="qualified"`` refuses to start without an operator +qualification record bound to the exact client bytes and effective config. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import selectors +import signal +import subprocess +import threading +import time +from pathlib import Path +from typing import Any, Iterator, Mapping + +from ..canon import canonical_bytes, digest_of, sha256_hex, strict_loads +from ..errors import AdapterCancelled, AdapterFailure, AdapterTimeout, PortError, UnsupportedCapability +from ..ports import Executor, ModelAdapter, PortContext, PortSet, TransportEvent, TurnInput + +ADAPTER_NAME = "codex_account" +ADAPTER_VERSION = "0.1.0-experimental" +PROVIDER = "openai-codex-chatgpt-account" +LAUNCH_SCHEMA = "codex_account_launch/v1" +TURN_SCHEMA = "codex_account_turn/v1" +QUALIFICATION_SCHEMA = "codex_account_qualification/v1" + +# requested setting name -> codex config key. Anything else is refused (no silent drop). +SETTINGS_MAP = { + "reasoning_effort": "model_reasoning_effort", + "reasoning_summary": "model_reasoning_summary", + "verbosity": "model_verbosity", +} +_TOKEN_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$") +_THREAD_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$") + +# Union of (a) the source paper's harness config and (b) the override list codex 0.166.0 +# itself applies to its internal tool-free "temporary structured thread". +DISABLED_FEATURES = ( + "apps", "browser_use", "browser_use_external", "browser_use_full_cdp_access", "code_mode", + "code_mode_host", "code_mode_only", "collaboration_modes", "computer_use", "context_management", + "current_time_reminder", "deferred_executor", "enable_fanout", "goals", "hooks", "image_generation", + "in_app_browser", "memories", "multi_agent", "multi_agent_v2", "plugins", "remote_plugin", + "request_permissions_tool", "shell_snapshot", "shell_tool", "skill_mcp_dependency_install", + "skill_search", "sleep_tool", "standalone_web_search", "token_budget", "tool_call_mcp_elicitation", + "tool_suggest", "unified_exec", "unified_exec_tty", "view_image", "workspace_dependencies", "worktrees", +) + +FIXED_OVERRIDES = ( + ("model_provider", '"openai"'), + ("forced_login_method", '"chatgpt"'), + ("approval_policy", '"never"'), + ("sandbox_mode", '"read-only"'), + ("web_search", '"disabled"'), + ("project_doc_max_bytes", "0"), + ("project_doc_fallback_filenames", "[]"), + ("include_permissions_instructions", "false"), + ("include_apps_instructions", "false"), + ("include_collaboration_mode_instructions", "false"), + ("include_environment_context", "false"), + ("include_environment_context_time", "false"), + ("hide_agent_reasoning", "false"), + ("show_raw_agent_reasoning", "false"), + ("notify", "[]"), + ("mcp_servers", "{}"), + ("cloud.skills.enabled", "false"), + ("skills.include_instructions", "false"), + ("tools.update_plan.enabled", "false"), + ("tools.experimental_request_user_input.enabled", "false"), +) + +ENV_PASS = ("PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "LC_CTYPE", "TZ", + "SSL_CERT_FILE", "SSL_CERT_DIR", "CODEX_HOME") +ENV_FIXED = {"NO_COLOR": "1"} +_FORBIDDEN_ENV = re.compile(r"^(OPENAI|CODEX|AZURE_OPENAI|CHATGPT)_[A-Z0-9_]*(KEY|TOKEN|BASE_URL|API_BASE|ORG_ID|ORGANIZATION|PROJECT)$") + +ANCESTOR_MARKERS = (".git", "AGENTS.md", "AGENTS.override.md", ".codex", ".agents") +MANAGED_PATHS = ("/etc/codex/managed_config.toml", "/etc/codex/config.toml", "/etc/codex/requirements.toml") + +FORBIDDEN_ITEMS = frozenset({"command_execution", "file_change", "mcp_tool_call", "web_search", + "todo_list", "collab_tool_call"}) +ENVELOPE_KEYS = ("action", "operation", "arguments_json", "choice", "proposal", "rationale") + +RESPONSE_SCHEMA = { + "type": "object", + "additionalProperties": False, + "required": list(ENVELOPE_KEYS), + "properties": { + "action": {"type": "string", "enum": ["request", "final_choice"]}, + "operation": {"type": ["string", "null"]}, + "arguments_json": {"type": ["string", "null"]}, + "choice": {"type": ["string", "null"], "enum": ["patch", "no_edit", None]}, + "proposal": {"type": ["string", "null"]}, + "rationale": {"type": "string"}, + }, +} + +NEUTRAL_INSTRUCTIONS = ( + "You are the editor model in a brokered research session. Each user message is a JSON envelope " + "of messages from the broker. You have no native tools. Act only through your final reply, which " + "must be one JSON object matching the response schema: use action \"request\" with operation and " + "arguments_json (a JSON object encoded as a string) to ask the broker for one operation, or action " + "\"final_choice\" with choice and proposal to end discovery. Put your visible justification in " + "rationale. Unused fields are null.\n" +) + + +# ------------------------------------------------------------------ helpers + + +def _sha256_file(path: Path) -> str: + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def _fail(code: str, message: str) -> AdapterFailure: + return AdapterFailure(message, code=code) + + +def parse_envelope(text: str) -> dict: + """Map the agent's final structured message to one broker event. Raise ValueError if malformed.""" + doc = strict_loads(text) + if not isinstance(doc, dict) or tuple(sorted(doc)) != tuple(sorted(ENVELOPE_KEYS)): + raise ValueError("final message is not the exact action envelope") + rationale = doc["rationale"] + if not isinstance(rationale, str): + raise ValueError("rationale must be a string") + if doc["action"] == "request": + op, args_json = doc["operation"], doc["arguments_json"] + if not isinstance(op, str) or not op or doc["choice"] is not None or doc["proposal"] is not None: + raise ValueError("request envelope needs operation and null choice/proposal") + if not isinstance(args_json, str): + raise ValueError("request envelope needs arguments_json") + args = strict_loads(args_json) + if not isinstance(args, dict): + raise ValueError("arguments_json must encode a JSON object") + return {"kind": "request", "operation": op, "arguments": args, "rationale": rationale} + if doc["action"] == "final_choice": + if doc["operation"] is not None or doc["arguments_json"] is not None: + raise ValueError("final_choice envelope needs null operation/arguments_json") + choice, proposal = doc["choice"], doc["proposal"] + if choice not in ("patch", "no_edit") or not (proposal is None or isinstance(proposal, str)): + raise ValueError("final_choice envelope needs choice patch|no_edit") + out = {"kind": "final_choice", "choice": choice, "rationale": rationale} + if proposal is not None: + out["proposal"] = proposal + return out + raise ValueError("unknown action") + + +def _returned_model(ev: Mapping[str, Any]) -> str | None: + """Only a model string the client itself put in the event; never the requested value.""" + for holder in (ev, ev.get("item") if isinstance(ev.get("item"), dict) else {}): + m = holder.get("model") + if isinstance(m, str) and m: + return m + return None + + +def normalize(raw: bytes) -> dict: + """Stateless mapping of one exact stdout JSONL line (newline included) to a broker event.""" + ev = strict_loads(raw) + if not isinstance(ev, dict) or not isinstance(ev.get("type"), str): + raise ValueError("provider line is not a typed JSON object") + t = ev["type"] + model = _returned_model(ev) + extra = {"model": model} if model else {} + if t == "thread.started": + tid = ev.get("thread_id") + if not isinstance(tid, str) or not _THREAD_RE.match(tid): + raise ValueError("thread.started without a valid thread_id") + return {"kind": "session", "event": t, "session_id": tid, **extra} + if t == "turn.started": + return {"kind": "session", "event": t, **extra} + if t == "turn.completed": + usage = ev.get("usage") + return {"kind": "finish", "status": "completed", "usage": usage if isinstance(usage, dict) else None, + **extra} + if t == "turn.failed": + return {"kind": "finish", "status": "failed", "error": ev.get("error"), **extra} + if t == "error": + return {"kind": "finish", "status": "error", "message": ev.get("message"), **extra} + if t in ("item.started", "item.updated", "item.completed"): + item = ev.get("item") + if not isinstance(item, dict) or not isinstance(item.get("type"), str): + raise ValueError("item event without a typed item") + it, iid = item["type"], item.get("id") + if it == "agent_message": + text = item.get("text") + if not isinstance(text, str): + raise ValueError("agent_message without text") + if t != "item.completed": + return {"kind": "message", "event": t, "item_id": iid, "text": text, "partial": True, **extra} + if text.lstrip().startswith("{"): + # raises on malformed structured output; payload keys are exactly what admission + # accepts, so a client-reported model on this line is not merged here (the original + # text is preserved by the broker's raw reference) + return parse_envelope(text) + return {"kind": "message", "event": t, "item_id": iid, "text": text, **extra} + if it == "reasoning": + return {"kind": "reasoning_summary", "event": t, "item_id": iid, "text": item.get("text"), + "source": "client_exposed_summary", **extra} + if it in FORBIDDEN_ITEMS: + return {"kind": "unknown", "native_tool_item": it, "event": t, "item_id": iid} + return {"kind": "unknown", "unsupported_item": it, "event": t} + return {"kind": "unknown", "unsupported_type": t} + + +# ------------------------------------------------------------------ adapter + + +class CodexAccountAdapter(ModelAdapter): + """Trusted operator port. Construct directly or via :func:`build_codex_account_ports`. + + Parameters are all explicit; nothing is chosen by a model request. + + ``codex_path``/``expected_sha256``/``expected_version`` pin the client. + ``work_dir`` is an empty private cwd that must stay empty; ``control_dir`` + holds the adapter-owned instructions and response schema (create-only, or + byte-identical if present). ``mode`` is ``"probe"`` (runs, never claims + qualification) or ``"qualified"`` (requires ``qualification_record``). + ``turn_timeout_s`` is an optional operator wall-clock bound (no default). + ``base_env`` defaults to ``os.environ``; only allowlisted names are passed. + ``acknowledged_markers`` lists exact ancestor marker paths the operator accepts. + """ + + def __init__(self, *, model: Mapping[str, Any], codex_path: str | os.PathLike, expected_sha256: str, + expected_version: str, work_dir: str | os.PathLike, control_dir: str | os.PathLike, + mode: str, qualification_record: str | os.PathLike | None = None, + instructions_text: str = NEUTRAL_INSTRUCTIONS, turn_timeout_s: float | None = None, + base_env: Mapping[str, str] | None = None, acknowledged_markers: tuple[str, ...] = (), + max_line_bytes: int = 64 << 20, kill_grace_s: float = 2.0, verify_login: bool = True): + if mode not in ("probe", "qualified"): + raise PortError("mode must be 'probe' or 'qualified'; there is no default") + self._requested = self._check_model(model) + self.mode = mode + self._timeout = turn_timeout_s + if turn_timeout_s is not None and not (isinstance(turn_timeout_s, (int, float)) and turn_timeout_s > 0): + raise PortError("turn_timeout_s must be positive or None") + self._max_line = int(max_line_bytes) + self._grace = float(kill_grace_s) + + self._codex = Path(codex_path).resolve(strict=True) + actual = _sha256_file(self._codex) + if actual != expected_sha256: + raise PortError("codex client bytes do not match the pinned sha256", code="client_drift") + self._client_sha = actual + + env_in = dict(os.environ if base_env is None else base_env) + bad = sorted(k for k, v in env_in.items() if v and _FORBIDDEN_ENV.match(k)) + if bad: + raise PortError(f"API-key/billing environment present ({', '.join(bad)}); account login only", + code="api_key_environment") + self._env = {k: env_in[k] for k in ENV_PASS if k in env_in} + self._env.update(ENV_FIXED) + home = self._env.get("HOME") + if not home: + raise PortError("HOME is required for the operator's existing codex login") + self._codex_home = Path(self._env.get("CODEX_HOME") or Path(home) / ".codex") + + self._work = Path(work_dir).resolve(strict=True) + self._control = Path(control_dir).resolve(strict=True) + if self._work == self._control or self._control.is_relative_to(self._work): + raise PortError("control_dir must be outside work_dir") + if any(self._work.iterdir()): + raise PortError("work_dir must be empty") + self._markers = self._ancestor_markers(Path(home)) + unack = sorted(set(self._markers) - set(acknowledged_markers)) + if unack: + raise PortError(f"work_dir ancestors contain instruction/config markers {unack}; " + "acknowledge exact paths explicitly or choose another work_dir", + code="work_dir_markers") + + self._instructions = instructions_text.encode("utf-8") + self._schema = canonical_bytes(RESPONSE_SCHEMA) + b"\n" + self._instr_path = self._control / "instructions.md" + self._schema_path = self._control / "response-schema.json" + for path, data in ((self._instr_path, self._instructions), (self._schema_path, self._schema)): + self._install(path, data) + + self._observed = self._observe_environment(Path(home)) + self._version = self._run_probe(["--version"]) + if self._version != expected_version: + raise PortError("codex client version does not match the pinned version", code="client_drift") + if verify_login: + status = self._run_probe(["login", "status"]) + # only a boolean is retained; the status text is not stored or logged + if "chatgpt" not in status.lower() or "api key" in status.lower(): + raise PortError("codex is not logged in with a ChatGPT account", code="login_mode") + self._login_verified = bool(verify_login) + + self._effective = self._effective_config() + self._effective_sha = digest_of(self._effective) + self._record_sha = None + if mode == "qualified": + self._record_sha = self._check_record(qualification_record) + elif qualification_record is not None: + raise PortError("qualification_record is only meaningful in qualified mode") + + self._proc: subprocess.Popen | None = None + self._cancel = threading.Event() + self._lock = threading.Lock() + + # ---------------------------------------------------------- construction + + @staticmethod + def _check_model(model: Mapping[str, Any]) -> dict: + try: + provider, name, settings = model["provider"], model["model"], model["settings"] + except (KeyError, TypeError) as exc: + raise PortError("model block needs provider, model, settings") from exc + if provider != PROVIDER: + raise UnsupportedCapability(f"provider must be {PROVIDER!r}; no other route is implemented") + if not isinstance(name, str) or not _TOKEN_RE.match(name): + raise PortError("model must be an explicit model id") + if not isinstance(settings, dict): + raise PortError("settings must be an object") + unknown = sorted(set(settings) - set(SETTINGS_MAP)) + if unknown: + raise UnsupportedCapability(f"unsupported settings {unknown}; refusing to drop them silently") + for k, v in settings.items(): + if not isinstance(v, str) or not _TOKEN_RE.match(v): + raise PortError(f"setting {k} must be a plain token string") + return {"provider": provider, "model": name, "settings": dict(settings)} + + def _ancestor_markers(self, home: Path) -> list[str]: + user_roots = {self._codex_home.resolve() if self._codex_home.exists() else self._codex_home, + (home / ".agents")} + found = [] + for d in (self._work, *self._work.parents): + for name in ANCESTOR_MARKERS: + p = d / name + if (p.exists() or p.is_symlink()) and p not in user_roots and p.resolve() not in user_roots: + found.append(str(p)) + return found + + def _observe_environment(self, home: Path) -> dict: + """Existence only; no file under CODEX_HOME is read.""" + ch = self._codex_home + return { + "codex_home_agents_md": (ch / "AGENTS.md").exists(), + "codex_home_agents_override_md": (ch / "AGENTS.override.md").exists(), + "codex_home_skills_dir": (ch / "skills").is_dir(), + "codex_home_plugins_dir": (ch / "plugins").is_dir(), + "home_agents_dir": (home / ".agents").is_dir(), + "managed_config": sorted(p for p in MANAGED_PATHS if Path(p).exists()), + "acknowledged_ancestor_markers": sorted(self._markers), + } + + @staticmethod + def _install(path: Path, data: bytes) -> None: + try: + fd = os.open(str(path), os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + except FileExistsError: + if path.is_symlink() or path.read_bytes() != data: + raise PortError(f"{path.name} in control_dir differs from the adapter's bytes", code="control_drift") + return + try: + os.write(fd, data) + os.fsync(fd) + finally: + os.close(fd) + + def _run_probe(self, args: list[str]) -> str: + try: + cp = subprocess.run([str(self._codex), *args], cwd=self._work, env=self._env, capture_output=True, + timeout=60, stdin=subprocess.DEVNULL, check=False) + except (OSError, subprocess.TimeoutExpired) as exc: + raise PortError(f"codex {' '.join(args)} failed: {type(exc).__name__}") from exc + if cp.returncode != 0: + raise PortError(f"codex {' '.join(args)} exited {cp.returncode}") + return (cp.stdout + cp.stderr).decode("utf-8", errors="replace").strip() + + def _overrides(self) -> list[tuple[str, str]]: + ov = list(FIXED_OVERRIDES) + ov.insert(5, ("model_instructions_file", json.dumps(str(self._instr_path)))) + ov += [(f"features.{f}", "false") for f in DISABLED_FEATURES] + ov += [(SETTINGS_MAP[k], json.dumps(v)) for k, v in sorted(self._requested["settings"].items())] + return ov + + def _common_args(self) -> list[str]: + out = ["--json", "--ignore-user-config", "--ignore-rules", "--strict-config", "--skip-git-repo-check", + "--output-schema", str(self._schema_path), "-m", self._requested["model"]] + for k, v in self._overrides(): + out += ["-c", f"{k}={v}"] + return out + + def argv_for(self, session_id: str | None) -> list[str]: + if session_id is None: + return [str(self._codex), "exec", *self._common_args(), "-"] + return [str(self._codex), "exec", "resume", *self._common_args(), session_id, "-"] + + def _effective_config(self) -> dict: + return { + "argv_new": self.argv_for(None), + "argv_resume": self.argv_for(""), + "cwd": str(self._work), + "env_names": sorted(self._env), + "env_fixed": dict(ENV_FIXED), + "instructions_sha256": sha256_hex(self._instructions), + "schema_sha256": sha256_hex(self._schema), + "client_sha256": self._client_sha, + "client_version": self._version, + "environment_observed": self._observed, + } + + def _check_record(self, path) -> str: + if path is None: + raise PortError("qualified mode requires a qualification_record", code="adapter_unqualified") + blob = Path(path).read_bytes() + rec = strict_loads(blob) + need = { + "schema": QUALIFICATION_SCHEMA, "client_sha256": self._client_sha, + "effective_config_sha256": self._effective_sha, "model": self._requested, + } + for k, v in need.items(): + if not isinstance(rec, dict) or rec.get(k) != v: + raise PortError(f"qualification record field {k} does not match this adapter", + code="adapter_unqualified") + ver = rec.get("verified", {}) + for k in ("native_tool_catalogue_empty", "model_visible_instructions", "returned_model_reported", + "no_client_internal_retry"): + if not isinstance(ver, dict) or ver.get(k) is not True: + raise PortError(f"qualification record does not verify {k}", code="adapter_unqualified") + if not isinstance(rec.get("evidence_sha256"), str): + raise PortError("qualification record lacks evidence_sha256", code="adapter_unqualified") + return sha256_hex(blob) + + def blockers(self) -> list[str]: + if self.mode == "qualified": + return [] + out = [ + "native_tool_catalogue_unobserved: codex exec --json does not expose the model-visible tool list", + "model_visible_instructions_unobserved: final prompt assembly (incl. CODEX_HOME AGENTS.md/skills) " + "is not exported by codex exec", + "returned_model_unreported: codex exec JSONL carries no server-returned model; turns fail closed", + "client_internal_retry_unobservable: codex stream/request retries are client-internal; only " + "surfaced error events are detected", + "strict_config_override_validation_unverified: --strict-config is documented for config.toml, " + "not -c overrides", + ] + obs = self._observed + if obs["codex_home_agents_md"] or obs["codex_home_agents_override_md"]: + out.append("codex_home_agents_md_present: global instructions may be injected despite " + "--ignore-user-config") + if obs["managed_config"]: + out.append("managed_config_present: " + ",".join(obs["managed_config"])) + return out + + # ---------------------------------------------------------- port API + + def identity(self) -> dict: + qualified = self.mode == "qualified" + return { + **self._requested, + "client_version": self._version, + "client_sha256": self._client_sha, + "adapter": {"name": ADAPTER_NAME, "version": ADAPTER_VERSION}, + "effective_config_sha256": self._effective_sha, + "effective_config": self._effective, + "auth": {"mode": "chatgpt_account", "forced_login_method": "chatgpt", + "login_status_checked": self._login_verified, "api_key_environment": "rejected"}, + "returned_identity": {"source": "client_reported_only", "synthesized": False}, + "qualification": {"mode": self.mode, "qualified": qualified, "record_sha256": self._record_sha, + "blockers": self.blockers()}, + "capabilities": {"raw_events": True, "reasoning_summaries": True, "captures_hidden_reasoning": False, + "tool_isolation": "config_disabled_qualified_by_record" if qualified + else "config_disabled_unqualified"}, + } + + def parse_event(self, raw: bytes) -> dict: + return normalize(raw) + + def cancel(self) -> None: + """Thread-safe: stop the current turn and kill its process group.""" + self._cancel.set() + with self._lock: + proc = self._proc + if proc is not None: + self._kill_group(proc) + + def close(self) -> None: + self.cancel() + + def _kill_group(self, proc: subprocess.Popen) -> None: + try: + os.killpg(proc.pid, signal.SIGTERM) + except (ProcessLookupError, PermissionError): + pass + try: + proc.wait(timeout=self._grace) + except subprocess.TimeoutExpired: + pass + try: + os.killpg(proc.pid, signal.SIGKILL) # children that ignored TERM; group is owned by this turn + except (ProcessLookupError, PermissionError): + pass + try: + proc.wait(timeout=self._grace) + except subprocess.TimeoutExpired: + pass + + def _preflight(self, turn: TurnInput) -> str | None: + if _sha256_file(self._codex) != self._client_sha: + raise _fail("client_drift", "codex client bytes changed since identity was bound") + for path, data in ((self._instr_path, self._instructions), (self._schema_path, self._schema)): + if path.is_symlink() or path.read_bytes() != data: + raise _fail("control_drift", f"{path.name} changed since identity was bound") + if any(self._work.iterdir()): + raise _fail("work_dir_dirty", "work_dir is not empty") + sid = turn.session_id + if sid is not None and (not isinstance(sid, str) or not _THREAD_RE.match(sid)): + raise _fail("session_invalid", "session id is not a codex thread id") + if turn.resumed and sid is not None: + raise _fail("resume_after_interruption", + "provider thread may hold an interrupted turn; explicit operator handling required") + if sid is None and not turn.messages: + raise _fail("missing_bootstrap", "new provider thread without bootstrap messages") + return sid + + def run_turn(self, turn: TurnInput) -> Iterator[bytes | TransportEvent]: + self._cancel.clear() + sid = self._preflight(turn) + argv = self.argv_for(sid) + stdin = canonical_bytes({"schema": TURN_SCHEMA, "turn_id": turn.turn_id, "turn_index": turn.turn_index, + "messages": [dict(m) for m in turn.messages]}) + b"\n" + launch = canonical_bytes({ + "schema": LAUNCH_SCHEMA, "turn_id": turn.turn_id, "argv": argv, "cwd": str(self._work), + "env_names": sorted(self._env), "stdin_sha256": sha256_hex(stdin), "stdin_size": len(stdin), + "client_sha256": self._client_sha, "effective_config_sha256": self._effective_sha, + "resume_thread_id": sid, + }) + b"\n" + yield TransportEvent(launch, "client_input") # durable before the process exists + yield TransportEvent(stdin, "client_input") + + check = _TurnCheck(expected_thread=sid) + try: + proc = subprocess.Popen(argv, cwd=self._work, env=self._env, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, + close_fds=True, shell=False) + except OSError as exc: + raise _fail("spawn_failed", f"cannot start codex: {type(exc).__name__}") from exc + with self._lock: + self._proc = proc + writer = threading.Thread(target=_feed, args=(proc.stdin, stdin), daemon=True) + writer.start() + deadline = None if self._timeout is None else time.monotonic() + self._timeout + killed_for: AdapterFailure | None = None + sel = selectors.DefaultSelector() + try: + for f, ch in ((proc.stdout, "provider"), (proc.stderr, "client_stderr")): + os.set_blocking(f.fileno(), False) + sel.register(f, selectors.EVENT_READ, ch) + buf = bytearray() + open_streams = 2 + while open_streams: + if self._cancel.is_set() and killed_for is None: + killed_for = AdapterCancelled("turn cancelled by operator") + self._kill_group(proc) + if deadline is not None and killed_for is None and time.monotonic() > deadline: + killed_for = AdapterTimeout("operator turn_timeout_s exceeded") + self._kill_group(proc) + for key, _ in sel.select(timeout=0.1): + try: + chunk = os.read(key.fileobj.fileno(), 65536) + except BlockingIOError: + continue + if not chunk: + sel.unregister(key.fileobj) + open_streams -= 1 + continue + if key.data == "client_stderr": + yield TransportEvent(chunk, "client_stderr") + continue + buf += chunk + while True: + nl = buf.find(b"\n") + if nl < 0: + break + line = bytes(buf[: nl + 1]) + del buf[: nl + 1] + yield TransportEvent(line, "provider") + problem = check.feed(line) + if problem is not None and killed_for is None: + killed_for = problem + self._kill_group(proc) # stop before a native tool or client retry proceeds + if len(buf) > self._max_line and killed_for is None: + yield TransportEvent(bytes(buf), "provider") + buf.clear() + killed_for = _fail("line_too_long", "provider line exceeded max_line_bytes") + self._kill_group(proc) + if buf: + yield TransportEvent(bytes(buf), "provider") # exact partial bytes, then fail + if killed_for is None: + killed_for = _fail("truncated_stream", "provider stream ended mid-line") + rc = proc.wait() + if self._cancel.is_set() and killed_for is None: # killed by cancel() from another thread + killed_for = AdapterCancelled("turn cancelled by operator") + finally: + sel.close() + if proc.poll() is None: + self._kill_group(proc) + else: + try: + os.killpg(proc.pid, signal.SIGKILL) # stray children of a finished client + except (ProcessLookupError, PermissionError): + pass + for f in (proc.stdout, proc.stderr): + try: + f.close() + except OSError: + pass + with self._lock: + self._proc = None + if killed_for is not None: + raise killed_for + if rc != 0: + raise _fail("nonzero_exit", f"codex exited {rc}") + final = check.finish() + if final is not None: + raise final + if any(self._work.iterdir()): + raise _fail("work_dir_dirty", "work_dir changed during the turn") + + +def _feed(pipe, data: bytes) -> None: + try: + pipe.write(data) + pipe.flush() + except (BrokenPipeError, OSError): + pass + finally: + try: + pipe.close() + except OSError: + pass + + +class _TurnCheck: + """Per-turn protocol state over the same normalization the broker sees.""" + + def __init__(self, expected_thread: str | None): + self.expected = expected_thread + self.lines = 0 + self.thread: str | None = None + self.turn_started = 0 + self.completed = False + self.actions = 0 + self.last_agent_was_action = False + self.models: set[str] = set() + + def feed(self, line: bytes) -> AdapterFailure | None: + self.lines += 1 + if self.completed: + return _fail("output_after_completion", "provider output after turn.completed") + try: + ev = normalize(line) + except Exception as exc: # malformed JSON or malformed structured action + return _fail("malformed_provider_event", f"unparseable provider line: {type(exc).__name__}") + if isinstance(ev.get("model"), str): # only what the broker will also see normalized + self.models.add(ev["model"]) + kind = ev["kind"] + if kind == "unknown": + if "native_tool_item" in ev: + return _fail("native_tool_event", f"client emitted native tool item {ev['native_tool_item']}") + return _fail("unknown_provider_event", "unsupported provider packet") + if self.lines == 1 and ev.get("event") != "thread.started": + return _fail("missing_thread_start", "first provider event is not thread.started") + if ev.get("event") == "thread.started": + if self.thread is not None: + return _fail("session_drift", "second thread.started in one turn") + self.thread = ev["session_id"] + if self.expected is not None and self.thread != self.expected: + return _fail("session_drift", "resumed thread id differs from the journaled session") + elif ev.get("event") == "turn.started": + self.turn_started += 1 + if self.turn_started > 1: + return _fail("multiple_turns", "more than one turn.started") + elif kind == "finish": + if ev["status"] != "completed": + return _fail("provider_error", f"client reported {ev['status']}") + if self.turn_started != 1: + return _fail("unbalanced_turn", "turn.completed without turn.started") + self.completed = True + elif kind in ("request", "final_choice"): + self.actions += 1 + self.last_agent_was_action = True + if self.actions > 1: + return _fail("multiple_actions", "more than one structured action in one turn") + elif kind == "message" and not ev.get("partial"): + self.last_agent_was_action = False + return None + + def finish(self) -> AdapterFailure | None: + if not self.completed: + return _fail("missing_turn_completion", "stream ended without turn.completed") + if self.actions != 1 or not self.last_agent_was_action: + return _fail("no_structured_action", "turn did not end with exactly one structured action") + if not self.models: + return _fail("returned_model_unobserved", + "the client reported no returned model on this turn; nothing is synthesized") + return None + + +# ------------------------------------------------------------------ composition + + +def build_codex_account_ports(ctx: PortContext, executor: Executor, **adapter_kwargs: Any) -> PortSet: + """Compose the adapter with a caller-supplied real ``Executor``. + + Model identity comes only from the config's model block; ``adapter_kwargs`` + are operator settings (paths, pins, mode). No executor is invented here. + """ + if not isinstance(executor, Executor): + raise PortError("an Executor instance must be supplied by the caller") + if "model" in adapter_kwargs: + raise PortError("model comes from the config's model block only") + return PortSet(CodexAccountAdapter(model=ctx.model, **adapter_kwargs), executor) diff --git a/synaptic_tuner/experimental/weight_editor/admission.py b/synaptic_tuner/experimental/weight_editor/admission.py new file mode 100644 index 000000000..4e0fc8b9e --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/admission.py @@ -0,0 +1,182 @@ +"""Pure host-side admission of one model request. + +Runs before any reservation or executor involvement. A model request can name +an admitted operation and fill its declared arguments; it cannot carry paths, +commands, imports, policy, budget or split overrides. +""" + +from __future__ import annotations + +import math +import re +from dataclasses import dataclass +from typing import Any, Mapping + +from .canon import sha256_hex +from .config import AUTHORITY_NAMES, ID_RE, EditorConfig +from .ledger import Ledger + +REQUEST_KEYS = frozenset({"operation", "arguments", "rationale", "label"}) +_PATHLIKE = re.compile(r"(^[~$%])|(\.\.)|[/\\\x00]|(^[A-Za-z][A-Za-z0-9+.-]*:)") + +PUBLIC = { + "failed_turn": "provider turn did not complete; submit a new request", + "interrupted_turn": "provider turn was interrupted; submit a new request", + "capture_incomplete": "provider capture is incomplete; this turn cannot authorize an operation", + "model_drift": "returned model identity did not match; this turn cannot authorize an operation", + "model_identity_unverified": "returned model identity was not observed; this turn cannot authorize an operation", + "phase_closed": "no further operations are accepted in the current phase", + "malformed_request": "request is malformed", + "forbidden_field": "request carries fields that grant no authority", + "unadmitted_operation": "operation is not admitted", + "unknown_argument": "request has an undeclared argument", + "missing_argument": "request is missing a required argument", + "invalid_argument": "argument value is invalid", + "path_authority": "paths, URLs and commands are not artifact references", + "unknown_object": "unknown or unadmitted object", + "withheld_id": "unknown or unadmitted object", + "source_or_base_write": "target is not a writable artifact name", + "artifact_exists": "artifact name already used in this run", + "budget_exceeded": "resource policy does not permit this request", + "executor_validation": "operation rejected by executor validation", +} + + +@dataclass(frozen=True) +class Denied: + reason: str + detail: str + + @property + def public(self) -> str: + return PUBLIC.get(self.reason, "request denied") + + +@dataclass(frozen=True) +class Admitted: + operation: str + arguments: Mapping[str, Any] + bound: Mapping[str, Any] + cost: Mapping[str, float] + + +def _id_value(value: Any, where: str) -> Denied | str: + if not isinstance(value, str): + return Denied("invalid_argument", f"{where} must be an id string") + if _PATHLIKE.search(value): + return Denied("path_authority", f"{where} looks like a path/URL/command") + if not ID_RE.match(value): + return Denied("invalid_argument", f"{where} is not a well-formed id") + return value + + +def admit( + payload: Any, + config: EditorConfig, + ledger: Ledger, + used_artifact_names: set[str], + phase: str, +) -> Admitted | Denied: + if phase != "discovery": + return Denied("phase_closed", f"phase is {phase}") + if not isinstance(payload, dict): + return Denied("malformed_request", "request is not an object") + extra = set(payload) - REQUEST_KEYS + if extra: + return Denied("forbidden_field", f"top-level fields {sorted(extra)}") + op_name = payload.get("operation") + if not isinstance(op_name, str): + return Denied("malformed_request", "operation missing") + spec = config.operations.get(op_name) + if spec is None: + return Denied("unadmitted_operation", f"operation {op_name!r}") + args = payload.get("arguments", {}) + if not isinstance(args, dict): + return Denied("malformed_request", "arguments is not an object") + for key in args: + if key not in spec.args: + reason = "forbidden_field" if key in AUTHORITY_NAMES else "unknown_argument" + return Denied(reason, f"argument {key!r}") + for name, aspec in spec.args.items(): + if aspec.required and name not in args: + return Denied("missing_argument", f"argument {name!r}") + + bound: dict[str, Any] = {} + clean: dict[str, Any] = {} + for name, value in args.items(): + aspec = spec.args[name] + where = f"argument {name!r}" + t, p = aspec.type, aspec.params + if t in ("ref", "ref_list"): + if t == "ref": + values = [value] + else: + if not isinstance(value, list) or not value: + return Denied("invalid_argument", f"{where} must be a non-empty list") + if len(value) > p["max_items"]: + return Denied("invalid_argument", f"{where} exceeds max_items") + if len(set(map(str, value))) != len(value): + return Denied("invalid_argument", f"{where} has duplicates") + values = value + resolved = [] + for v in values: + r = _id_value(v, where) + if isinstance(r, Denied): + return r + if sha256_hex(r.encode()) in config.withheld_digests: + return Denied("withheld_id", f"{where} id is registered as withheld") + obj = config.capsule.objects.get(r) + if obj is None or obj.kind != p["kind"]: + return Denied("unknown_object", f"{where} id {r!r} not an admitted {p['kind']}") + resolved.append({"id": obj.id, "kind": obj.kind, "sha256": obj.sha256, "path": str(obj.abs_path)}) + bound[name] = resolved[0] if t == "ref" else resolved + clean[name] = value + elif t == "int": + if isinstance(value, bool) or not isinstance(value, int) or not p["min"] <= value <= p["max"]: + return Denied("invalid_argument", f"{where} not an int in [{p['min']},{p['max']}]") + clean[name] = value + elif t == "number": + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(value) + or not p["min"] <= value <= p["max"] + ): + return Denied("invalid_argument", f"{where} not a finite number in range") + clean[name] = value + elif t == "enum": + if value not in p["values"]: + return Denied("invalid_argument", f"{where} not in enum") + clean[name] = value + elif t == "text": + if not isinstance(value, str) or len(value) > p["max_length"]: + return Denied("invalid_argument", f"{where} must be text up to {p['max_length']} chars") + clean[name] = value + elif t == "artifact_name": + r = _id_value(value, where) + if isinstance(r, Denied): + return r + if r in config.capsule.objects: + return Denied("source_or_base_write", f"{where} names a capsule source/base object") + if r in used_artifact_names: + return Denied("artifact_exists", f"{where} {r!r}") + clean[name] = r + + cost = _cost(spec.cost, clean) + cost["dispatches"] = cost.get("dispatches", 0) + 1 + over = ledger.exceeded_by(cost) + if over: + return Denied("budget_exceeded", f"exceeds limit: {over}") + return Admitted(op_name, clean, bound, cost) + + +def _cost(spec: Mapping[str, Any], args: Mapping[str, Any]) -> dict[str, float]: + out: dict[str, float] = {} + for res, c in spec.items(): + if isinstance(c, dict) and "from_arg" in c: + out[res] = float(args[c["from_arg"]]) if c["from_arg"] in args else 0.0 + elif isinstance(c, dict): + out[res] = float(len(args.get(c["len_of"], []))) * c["per_item"] + else: + out[res] = c + return out diff --git a/synaptic_tuner/experimental/weight_editor/broker.py b/synaptic_tuner/experimental/weight_editor/broker.py new file mode 100644 index 000000000..29075b1c9 --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/broker.py @@ -0,0 +1,923 @@ +"""Host-owned experiment broker and recorder. + +The broker owns admission, reservation, write-ahead dispatch, reconciliation, +the journals and the terminal boundary. The model adapter and executor are +trusted ports that never receive authority from a model request. +""" + +from __future__ import annotations + +import base64 +import fcntl +import os +import time +from pathlib import Path +from typing import Any, Callable, Mapping + +from . import __version__ +from .admission import PUBLIC, Denied, admit +from .canon import ( + canonical_bytes, check_json, create_only, digest_of, load_strict_file, sha256_file, sha256_hex, +) +from .config import RUN_ID_RE, EditorConfig +from .errors import ( + AdapterCancelled, AdapterFailure, AdapterTimeout, EditorError, ExecutorRejection, IdentityDrift, + JournalCorrupt, LockHeld, PartialTail, PhaseError, PortError, RunExists, RunNotFound, UnsupportedCapability, + WriteBoundaryViolation, +) +from .journal import HashChainLog, genesis_prev, quarantine_partial_tail +from .ledger import clean_amount +from .ports import ( + EVENT_KINDS, BoundedWriter, Dispatch, PortSet, Receipt, ReconcileResult, TransportEvent, + TurnInput, describe_port, source_package, +) +from .state import PHASES, RunState, chain_context + +MANIFEST_SCHEMA = "weight_editor_run/v1" +PROTOCOL = ( + "You are the editor. Only the operations and objects in this catalog exist. A request is an object " + "with 'operation' and 'arguments' only; paths, URLs, commands, imports, policy and budget fields " + "carry no authority and are denied. Give a visible justification with every proposal. " + "Finish with exactly one final_choice (a selectable proposal or no_edit). After a final choice " + "no further operations are accepted." +) + + +class _Halt(Exception): + def __init__(self, code: str, detail: str, **extra): + super().__init__(detail) + self.code, self.detail, self.extra = code, detail, extra + + +# ------------------------------------------------------------ identity + + +def validate_ports(config: EditorConfig, ports: PortSet) -> dict: + """Explicit port validators. No fallback model, no unsupported capability.""" + ident = ports.adapter.identity() + if not isinstance(ident, dict): + raise PortError("adapter identity must be an object") + req = {k: ident.get(k) for k in ("provider", "model", "settings")} + if req != config.model.requested(): + raise PortError( + "adapter requested model identity does not equal the configured model; no fallback is permitted", + code="model_mismatch", + configured=config.model.requested(), + adapter=req, + ) + caps = ident.get("capabilities", {}) + if not isinstance(caps, dict) or caps.get("raw_events") is not True: + raise PortError("adapter must declare raw_events=true (complete emitted-traffic retention)", code="adapter_unqualified") + if caps.get("captures_hidden_reasoning"): + raise PortError("hidden reasoning capture is not a supported claim", code="adapter_unqualified") + supported = ports.executor.supported_operations() + missing = sorted(set(config.operations) - set(supported)) + if missing: + raise UnsupportedCapability( + f"executor does not support configured operations {missing}", unsupported=missing + ) + return { + "adapter": describe_port(ports.adapter), + "executor": describe_port(ports.executor), + "declared_isolation": caps.get("tool_isolation", "unspecified"), + "isolation_note": "declared by the port; not verified or enforced by the broker", + } + + +def compute_binding(config: EditorConfig, ports: PortSet, supplied: Mapping[str, Any]) -> dict: + check_json(dict(supplied)) + return { + "broker_sources": source_package(__file__), + "config_sha256": config.sha256, + "capsule_manifest_sha256": config.capsule.manifest_sha256, + "capsule_objects": {oid: o.sha256 for oid, o in sorted(config.capsule.objects.items())}, + "model": config.model.requested(), + "adapter": describe_port(ports.adapter), + "executor": describe_port(ports.executor), + "supplied": dict(supplied), + } + + +def _diff(old: Mapping, new: Mapping) -> list[str]: + return sorted(k for k in set(old) | set(new) if old.get(k) != new.get(k)) + + +# ---------------------------------------------------------------- run + + +class EditorRun: + def __init__(self, config, ports, run_dir, manifest, lock_fd, journal, raw, clock): + self.config: EditorConfig = config + self.ports: PortSet = ports + self.run_dir: Path = run_dir + self.manifest: dict = manifest + self.run_id: str = manifest["run_id"] + self._lock_fd = lock_fd + self.journal: HashChainLog = journal + self.raw: HashChainLog = raw + self.clock = clock + self._drift: dict | None = None + self.state = RunState(config.limits) + for rec in journal.records: + self.state.apply(rec) + + # ------------------------------------------------------- lifecycle + @staticmethod + def _run_dir_for(config: EditorConfig, run_id: str) -> Path: + if not isinstance(run_id, str) or not RUN_ID_RE.match(run_id) or ".." in run_id: + raise EditorError("run id must match [a-z0-9][a-z0-9._-]{0,63}", code="bad_run_id") + return config.output_root / run_id + + @staticmethod + def _lock(path: Path) -> int: + fd = os.open(str(path), os.O_CREAT | os.O_RDWR, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError as exc: + os.close(fd) + raise LockHeld("another writer holds this run's lock") from exc + return fd + + @classmethod + def create(cls, config: EditorConfig, ports: PortSet, run_id: str, + supplied: Mapping[str, Any] | None = None, clock: Callable[[], float] = time.time): + validate_ports(config, ports) + run_dir = cls._run_dir_for(config, run_id) + config.output_root.mkdir(parents=True, exist_ok=True) + if run_dir.parent.resolve() != config.output_root: + raise EditorError("run directory escapes output root", code="output_root_escape") + try: + os.mkdir(run_dir, 0o700) + except FileExistsError as exc: + raise RunExists(f"run {run_id} already exists; runs are never overwritten") from exc + lock_fd = cls._lock(run_dir / "lock") + try: + for sub in ("capsule", "provider", "journal", "requests", "artifacts"): + (run_dir / sub).mkdir() + binding = compute_binding(config, ports, supplied or {}) + bad = config.capsule.verify_objects() + if bad: + raise EditorError(f"capsule objects changed during registration: {bad}", code="capsule_drift") + create_only(run_dir / "config.json", config.raw_bytes) + create_only(run_dir / "capsule" / "manifest.json", config.capsule.manifest_bytes) + manifest = { + "schema": MANIFEST_SCHEMA, "run_id": run_id, "created_at": round(clock(), 6), + "writer": f"weight_editor {__version__}", "binding": binding, + "binding_digest": digest_of(binding), + "state_machine": list(PHASES), + "notes": ["hidden reasoning is not captured or claimed", + "adapter isolation is declared by the port, not enforced by the broker"], + } + create_only(run_dir / "manifest.json", canonical_bytes(manifest) + b"\n") + journal = HashChainLog(run_dir / "journal" / "events.jsonl", run_id, + genesis_prev(manifest["binding_digest"], "journal"), clock) + raw = HashChainLog(run_dir / "provider" / "events.jsonl", run_id, + genesis_prev(manifest["binding_digest"], "provider"), clock) + except BaseException: + os.close(lock_fd) + raise + run = cls(config, ports, run_dir, manifest, lock_fd, journal, raw, clock) + run._emit("run_registered", { + "binding_digest": manifest["binding_digest"], "config_sha256": config.sha256, + "capsule_manifest_sha256": config.capsule.manifest_sha256, "model_requested": config.model.requested(), + "adapter": binding["adapter"], "executor": binding["executor"], "supplied": binding["supplied"], + }) + run._emit("state_transition", {"from": "registered", "to": "discovery", "reason": "registered"}) + return run + + @classmethod + def open(cls, config: EditorConfig, ports: PortSet, run_id: str, + supplied: Mapping[str, Any] | None = None, recover_tail: bool = False, + clock: Callable[[], float] = time.time): + run_dir = cls._run_dir_for(config, run_id) + if not (run_dir / "manifest.json").is_file(): + raise RunNotFound(f"no registered run {run_id} under output root") + lock_fd = cls._lock(run_dir / "lock") + try: + manifest = read_manifest(run_dir) + journal, raw, recovered = _open_logs(run_dir, manifest, recover_tail, clock) + except BaseException: + os.close(lock_fd) + raise + run = cls(config, ports, run_dir, manifest, lock_fd, journal, raw, clock) + try: + for r in recovered: + run._emit("tail_recovery", r) + cross_check(run_dir, journal.records, raw.records) + try: + validate_ports(config, ports) + current = compute_binding(config, ports, supplied or {}) + except EditorError as exc: + run._refuse("port_validation", {"code": exc.code, "message": str(exc)}) + raise + drift = _diff(manifest["binding"], current) + if drift: + run._refuse("identity_drift", {"components": drift}) + raise IdentityDrift( + f"run binding changed ({', '.join(drift)}); the run cannot resume under changed bytes", + components=drift, + ) + if run.state.phase in ("independent_evaluation", "closed"): + run._refuse("phase_closed", {"phase": run.state.phase}) + raise PhaseError(f"run is in {run.state.phase}; the editor has no transition back to discovery") + if run.state.phase == "registered": # crashed between registration records + run._emit("state_transition", {"from": "registered", "to": "discovery", "reason": "resume"}) + if run.state.status != "complete": + run._emit("resume_started", {"prior_status": run.state.status, "prior_halt": run.state.halt, + "open_turn": run.state.open_turn}) + except BaseException: + run.close() + raise + return run + + def close(self) -> None: + for log in (self.journal, self.raw): + log.close() + for port in (self.ports.adapter, self.ports.executor): + try: + port.close() + except Exception: + pass + if self._lock_fd is not None: + os.close(self._lock_fd) + self._lock_fd = None + + # ---------------------------------------------------------- emit + def _emit(self, rtype: str, data: dict, linked: dict | None = None, ledger: list | None = None) -> dict: + if ledger: + for e in ledger: + clean_amount(e["amount"], "ledger amount") + data = {**data, "ledger": ledger} + rec = self.journal.append(rtype, data, linked) + self.state.apply(rec) + return rec + + def _refuse(self, reason: str, detail: dict) -> None: + self._emit("resume_refused", {"reason": reason, **detail}) + + def _halt(self, code: str, detail: str, **extra) -> None: + self._emit("run_halted", {"code": code, "detail": detail, "incomplete": True, **extra}) + + # ---------------------------------------------------------- drive + def run(self) -> dict: + st = self.state + if st.phase not in ("discovery", "final_patch_frozen") or st.status == "complete": + return self.summary() + try: + if st.open_turn is not None: + self._recover_open_turn() + if st.phase == "final_patch_frozen": + self._finalize() + return self.summary() + while st.phase == "discovery" and st.status == "running": + bad = self.config.capsule.verify_objects() + if bad: + raise _Halt("capsule_drift", f"capsule objects changed: {bad}", objects=bad) + self._process_pending() + if st.phase != "discovery" or st.status != "running": + break + self._run_turn() + self._process_pending() + if st.phase == "final_patch_frozen" and st.status == "running": + self._finalize() + except _Halt as h: + self._halt(h.code, h.detail, **h.extra) + return self.summary() + + # ----------------------------------------------------------- turn + def _initial_messages(self) -> list[dict]: + msgs = [] + for ins in self.config.instructions: + if "text" in ins: + text = ins["text"] + else: + text = self.config.capsule.objects[ins["object"]].abs_path.read_text(encoding="utf-8") + msgs.append({"role": ins["role"], "content": text}) + catalog = { + "protocol": PROTOCOL, + "capsule": self.config.capsule.listing(), + "operations": { + n: {"description": o.description, "selectable": o.selectable, + "arguments": {a.name: {"type": a.type, "required": a.required, **a.params} + for a in o.args.values()}} + for n, o in sorted(self.config.operations.items()) + }, + } + msgs.append({"role": "system", "content": "BROKER CATALOG\n" + canonical_bytes(catalog).decode()}) + return msgs + + def _run_turn(self) -> None: + st = self.state + self._drift = None # mismatches belong to the turn that produced their evidence + req_limit = st.ledger.limits.get("requests") + if st.ledger.exhausted("model_turns") or (req_limit is not None and st.ledger.charged("requests") >= req_limit): + raise _Halt("budget_exhausted", "model_turns/requests limit reached; configured limits are not raised on resume") + idx = st.turn_count + 1 + turn_id = f"turn-{idx:04d}" + bootstrap = idx == 1 or st.session_id is None or st.needs_bootstrap + messages = (self._initial_messages() if bootstrap else []) + list(st.outbox) + ctx = chain_context(st.context_digest, messages) + resumed = not st.last_turn_clean + self._emit("turn_start", { + "turn_id": turn_id, "turn_index": idx, "session_id": st.session_id, "messages": messages, + "context_digest": ctx, "resumed": resumed, + }, {"turn_id": turn_id}, ledger=[{"op": "commit", "ref": turn_id, "resource": "model_turns", "amount": 1}]) + ti = TurnInput(self.run_id, turn_id, idx, st.session_id, + tuple(dict(m) for m in messages), ctx, resumed) + try: + for raw in self.ports.adapter.run_turn(ti): + self._ingest_raw(turn_id, raw) + except Exception as exc: # provider failure, cancellation, timeout, adapter bug + cls = ("cancelled" if isinstance(exc, AdapterCancelled) else + "timeout" if isinstance(exc, (AdapterTimeout, TimeoutError)) else "provider_error") + self._emit("adapter_error", {"turn_id": turn_id, "classification": cls, + "category": type(exc).__name__, + "message_sha256": sha256_hex(str(exc).encode())}, {"turn_id": turn_id}) + self._discard_turn_items(turn_id, "failed_turn") + self._emit("turn_end", {"turn_id": turn_id, "status": "failed", "reason": cls}, {"turn_id": turn_id}) + raise _Halt("adapter_failure", f"adapter {cls}: {type(exc).__name__}; the turn is not retried implicitly") + if self._drift is not None: + drift, self._drift = self._drift, None + self._discard_turn_items(turn_id, "model_drift") + self._emit("turn_end", {"turn_id": turn_id, "status": "failed", "reason": "model_drift"}, {"turn_id": turn_id}) + raise _Halt("model_drift", f"provider returned model {drift['returned']!r}, not the configured model " + "or an allowed alias", **drift) + if turn_id in st.unqualified_turns: + self._discard_turn_items(turn_id, "capture_incomplete") + self._emit("turn_end", {"turn_id": turn_id, "status": "failed", "reason": "capture_incomplete"}, + {"turn_id": turn_id}) + raise _Halt("capture_incomplete", "unknown or truncated stream: turn items discarded, raw bytes retained") + if turn_id not in st.model_verified_turns: + self._discard_turn_items(turn_id, "model_identity_unverified") + self._emit("turn_end", {"turn_id": turn_id, "status": "failed", + "reason": "model_identity_unverified"}, {"turn_id": turn_id}) + raise _Halt("model_identity_unverified", "no returned model identity was observed in this turn") + self._emit("turn_end", {"turn_id": turn_id, "status": "complete"}, {"turn_id": turn_id}) + if st.pending() is None and st.phase == "discovery": + raise _Halt("model_ended_without_choice", + "the turn produced no request or final choice; final text is not success") + + def _ingest_raw(self, turn_id: str, raw: Any) -> None: + channel = "provider" + if isinstance(raw, TransportEvent): + channel, raw = raw.channel, raw.data + if channel not in ("provider", "client_input", "client_stderr"): + raise AdapterFailure("adapter yielded an unsupported transport channel") + if isinstance(raw, str): + raw = raw.encode("utf-8") + if not isinstance(raw, (bytes, bytearray)): + raise AdapterFailure("adapter yielded a non-bytes event") + raw = bytes(raw) + rec = self.raw.append("provider_raw", { + "turn_id": turn_id, "raw_b64": base64.b64encode(raw).decode(), "raw_sha256": sha256_hex(raw), + "size": len(raw), + "channel": channel, + }) + self._normalize(turn_id, rec, recovered=False) + + def _normalize(self, turn_id: str, rawrec: dict, recovered: bool) -> None: + raw = base64.b64decode(rawrec["data"]["raw_b64"]) + ref = {"seq": rawrec["seq"], "sha256": rawrec["data"]["raw_sha256"], "digest": rawrec["digest"]} + error = None + try: + channel = rawrec["data"].get("channel", "provider") + ev = (self.ports.adapter.parse_event(raw) if channel == "provider" else + {"kind": "message", "channel": channel, "content": raw.decode("utf-8", errors="replace")}) + check_json(ev) + if not isinstance(ev, dict) or ev.get("kind") not in EVENT_KINDS: + raise ValueError("unrecognized event kind") + except Exception as exc: + error = type(exc).__name__ + ev = {"kind": "unknown"} + kind = ev["kind"] + payload = {k: v for k, v in ev.items() if k != "kind"} + complete = kind != "unknown" + self._emit("provider_event", { + "kind": kind, "payload": payload, "raw": ref, "turn_id": turn_id, + "capture": {"complete": complete, **({"note": "unsupported/unparsed event retained raw", + "parse_error": error} if not complete else {})}, + "recovered_from_raw": recovered, + }, {"turn_id": turn_id, "raw_seq": ref["seq"]}) + st = self.state + self._check_returned_model(turn_id, payload) + if kind in ("handoff", "truncation"): + cap = payload.get("capsule", payload) + to_session = payload.get("new_session_id") or payload.get("to_session") + self._emit("handoff", { + "kind": kind, "from_session": st.session_id, "to_session": to_session, "capsule": cap, + "capsule_sha256": digest_of(cap), "raw": ref, "turn_id": turn_id, + "message": {"role": "system", "content": f"{kind.upper()} CAPSULE\n" + canonical_bytes(cap).decode()}, + }, {"turn_id": turn_id, "raw_seq": ref["seq"]}) + elif kind == "request": + rid = st.next_request_id() + self._emit("request_received", { + "request_id": rid, "turn_id": turn_id, "payload": payload, "raw": ref, + }, {"request_id": rid, "turn_id": turn_id, "raw_seq": ref["seq"]}, + ledger=[{"op": "commit", "ref": rid, "resource": "requests", "amount": 1}]) + elif kind == "final_choice": + fid = st.next_final_id() + self._emit("final_choice_received", { + "item_id": fid, "turn_id": turn_id, "payload": payload, "raw": ref, + }, {"item_id": fid, "turn_id": turn_id, "raw_seq": ref["seq"]}) + + def _check_returned_model(self, turn_id: str, payload: dict) -> None: + returned = payload.get("model") + if returned is None: + return + ok = {self.config.model.model, *self.config.model.allowed_returned} + if (not isinstance(returned, str) or returned not in ok) and self._drift is None: + # Keep consuming and retaining the turn's traffic; discard its requests afterwards. + self._drift = {"requested": self.config.model.model, "returned": returned} + elif isinstance(returned, str) and returned in ok: + self._emit("model_identity_verified", {"turn_id": turn_id, "model": returned}, {"turn_id": turn_id}) + + def _discard_turn_items(self, turn_id: str, reason: str) -> None: + for kind, iid in list(self.state.order): + if kind == "request" and self.state.requests[iid]["turn_id"] == turn_id and \ + self.state.requests[iid]["status"] == "received": + self._deny(iid, Denied(reason, reason), override_reason=reason) + elif kind == "final" and self.state.finals[iid]["turn_id"] == turn_id and \ + self.state.finals[iid]["status"] == "received": + self._deny_final(iid, reason, "turn discarded") + + def _recover_open_turn(self) -> None: + """A crash left a turn open: normalize raw events never referenced, then close it.""" + st = self.state + turn_id = st.open_turn + try: + for rawrec in list(self.raw.records): + if rawrec["seq"] > st.raw_referenced: + self._normalize(rawrec["data"]["turn_id"], rawrec, recovered=True) + finally: + self._discard_turn_items(turn_id, "interrupted_turn") + self._emit("turn_end", {"turn_id": turn_id, "status": "interrupted", "reason": "process_crash_or_kill", + **({"model_drift": self._drift} if self._drift else {})}, + {"turn_id": turn_id}) + self._drift = None + + # ------------------------------------------------------- requests + def _process_pending(self) -> None: + st = self.state + while True: + item = st.pending() + if item is None or st.status != "running": + return + kind, obj = item + if kind == "request": + self._process_request(obj["id"]) + else: + self._process_final(obj["id"]) + + def _tool_message(self, request_id: str, status: str, **body) -> dict: + return {"role": "tool", "content": canonical_bytes({"request_id": request_id, "status": status, **body}).decode()} + + def _deny(self, rid: str, denial: Denied, override_reason: str | None = None) -> None: + reason = override_reason or denial.reason + public = PUBLIC.get(denial.reason, "request denied") + public_reason = "unknown_object" if reason in ("withheld_id", "unknown_object") else reason + self._emit("request_denied", { + "request_id": rid, "reason": reason, "detail": denial.detail, + "message": self._tool_message(rid, "denied", reason=public_reason, + detail=public), + }, {"request_id": rid}) + + def _process_request(self, rid: str) -> None: + st = self.state + req = st.requests[rid] + if req["status"] == "received": + req_limit = st.ledger.limits.get("requests") + if req_limit is not None and int(rid.split("-")[1]) > req_limit: + return self._deny(rid, Denied("budget_exceeded", f"requests limit {req_limit} exceeded")) + adm = admit(req["payload"], self.config, st.ledger, st.artifact_names, st.phase) + if isinstance(adm, Denied): + return self._deny(rid, adm) + bad = self.config.capsule.verify_objects( + {b["id"] for v in adm.bound.values() for b in (v if isinstance(v, list) else [v])}) + if bad: + raise _Halt("capsule_drift", f"capsule objects changed before dispatch: {bad}", objects=bad) + try: + self.ports.executor.validate(adm.operation, adm.arguments, adm.bound) + except ExecutorRejection as exc: + return self._deny(rid, Denied("executor_validation", str(exc))) + dispatch_id = "dsp-" + digest_of({"run": self.run_id, "req": rid, "op": adm.operation, + "args": adm.arguments})[:24] + cost = dict(adm.cost) + self._emit("request_admitted", { + "request_id": rid, "operation": adm.operation, "arguments": dict(adm.arguments), + "bound": _public_bound(adm.bound), "dispatch_id": dispatch_id, "cost": cost, + "artifact_names": [v for n, v in adm.arguments.items() + if self.config.operations[adm.operation].args[n].type == "artifact_name"], + }, {"request_id": rid, "dispatch_id": dispatch_id}, + ledger=[{"op": "reserve", "ref": dispatch_id, "resource": r, "amount": a} + for r, a in cost.items() if a > 0]) + req = st.requests[rid] + if req["status"] == "admitted": + self._dispatch(req, attempt=1, basis="initial") + elif req["status"] in ("intent", "unknown"): + self._reconcile(req) + + def _make_dispatch(self, req: dict, attempt: int) -> Dispatch: + bound = self._resolve_bound(req["operation"], req["arguments"]) + return Dispatch(req["dispatch_id"], self.run_id, req["id"], req["operation"], + dict(req["arguments"]), bound, attempt) + + def _resolve_bound(self, op: str, args: Mapping[str, Any]) -> dict: + spec = self.config.operations[op] + out: dict[str, Any] = {} + for name, value in args.items(): + if spec.args[name].type in ("ref", "ref_list"): + ids = [value] if spec.args[name].type == "ref" else value + objs = [self.config.capsule.objects[i] for i in ids] + rs = [{"id": o.id, "kind": o.kind, "sha256": o.sha256, "path": str(o.abs_path)} for o in objs] + out[name] = rs[0] if spec.args[name].type == "ref" else rs + return out + + def _artifact_dir(self, dispatch_id: str) -> Path: + return self.run_dir / "artifacts" / dispatch_id + + def _dispatch(self, req: dict, attempt: int, basis: str) -> None: + if self.state.ledger.exhausted("dispatch_attempts"): + raise _Halt("budget_exhausted", "dispatch_attempts limit reached before executor effect") + bad = self.config.capsule.verify_objects() + if bad: + raise _Halt("capsule_drift", f"capsule objects changed before dispatch: {bad}", objects=bad) + dispatch = self._make_dispatch(req, attempt) + # Write-ahead: the intent is durable before the executor can cause any effect. + self._emit("dispatch_intent", { + "dispatch_id": dispatch.dispatch_id, "request_id": req["id"], "attempt": attempt, "basis": basis, + "operation": req["operation"], + }, {"request_id": req["id"], "dispatch_id": dispatch.dispatch_id}, + ledger=[{"op": "commit", "ref": dispatch.dispatch_id, "resource": "dispatch_attempts", "amount": 1}]) + writer = BoundedWriter(self._artifact_dir(dispatch.dispatch_id), self.config.read_only_roots) + try: + receipt = self.ports.executor.execute(dispatch, writer) + except ExecutorRejection as exc: + self._reject_dispatch(req, exc) + return + except BaseException as exc: # ambiguous: the effect may or may not have happened + self._emit("dispatch_error", { + "dispatch_id": dispatch.dispatch_id, "request_id": req["id"], "outcome": "unknown", + "category": type(exc).__name__, "message_sha256": sha256_hex(str(exc).encode()), + "boundary_violation": isinstance(exc, WriteBoundaryViolation), + }, {"request_id": req["id"], "dispatch_id": dispatch.dispatch_id}) + if isinstance(exc, (KeyboardInterrupt, SystemExit)): + raise + raise _Halt("reconciliation_needed", + f"dispatch {dispatch.dispatch_id} outcome unknown ({type(exc).__name__}); " + "no implicit retry; reconcile by dispatch id", dispatch_id=dispatch.dispatch_id) + self._complete(req, receipt, via="execute") + + def _reject_dispatch(self, req: dict, exc: Exception) -> None: + did = req["dispatch_id"] + released = [{"op": "release", "ref": did, "resource": r, "amount": a} + for r, a in self.state.ledger.reserved.get(did, {}).items() if a > 0] + self._emit("dispatch_error", { + "dispatch_id": did, "request_id": req["id"], "outcome": "not_started", + "category": type(exc).__name__, "message_sha256": sha256_hex(str(exc).encode()), + "message": self._tool_message(req["id"], "rejected", detail="operation rejected by executor"), + }, {"request_id": req["id"], "dispatch_id": did}, ledger=released) + + def _complete(self, req: dict, receipt: Any, via: str) -> None: + did, rid = req["dispatch_id"], req["id"] + anomalies: list[str] = [] + if not isinstance(receipt, Receipt) or not isinstance(receipt.status, str) or not isinstance(receipt.output, str): + anomalies.append("receipt_malformed") + receipt = Receipt("malformed_receipt", "", {}, {}) + try: + check_json(dict(receipt.detail)) + except ValueError: + anomalies.append("detail_not_json") + receipt = Receipt(receipt.status, receipt.output, {}, receipt.usage) + usage: dict[str, float] = {} + try: + for res, amt in dict(receipt.usage).items(): + usage[str(res)] = clean_amount(amt, f"usage {res}") + except (ValueError, TypeError): + anomalies.append("usage_invalid_charged_reservation_only") + usage = {} + reserved = dict(self.state.ledger.reserved.get(did, {})) + charge = {r: max(reserved.get(r, 0), usage.get(r, 0)) for r in set(reserved) | set(usage)} + artifacts = self._scan_artifacts(did) + body = {"status": receipt.status, "output": receipt.output, "detail": dict(receipt.detail), "usage": usage} + receipt_doc = {"dispatch_id": did, "request_id": rid, "receipt": body, "artifacts": artifacts} + rdir = self.run_dir / "requests" / rid + rdir.mkdir(exist_ok=True) + blob = canonical_bytes(receipt_doc) + b"\n" + rfile = rdir / "receipt.json" + if rfile.exists(): + if rfile.read_bytes() != blob: + raise _Halt("receipt_conflict", f"receipt file for {rid} exists with different content") + else: + create_only(rfile, blob) + ledger = [{"op": "release", "ref": did, "resource": r, "amount": a} for r, a in reserved.items() if a > 0] + ledger += [{"op": "commit", "ref": did, "resource": r, "amount": a} for r, a in charge.items() if a > 0] + msg = self._tool_message(rid, receipt.status, dispatch_id=did, output=receipt.output, + artifacts=[{"name": a["name"], "sha256": a["sha256"]} for a in artifacts]) + self._emit("dispatch_result", { + "dispatch_id": did, "request_id": rid, "via": via, "receipt": body, + "receipt_sha256": sha256_hex(canonical_bytes(receipt_doc)), "artifacts": artifacts, + "charge": charge, "anomalies": anomalies, "message": msg, + }, {"request_id": rid, "dispatch_id": did}, ledger=ledger) + + def _scan_artifacts(self, dispatch_id: str) -> list[dict]: + d = self._artifact_dir(dispatch_id) + if not d.is_dir(): + return [] + out = [] + for f in sorted(d.iterdir()): + if f.is_file() and not f.is_symlink(): + out.append({"name": f.name, "relpath": f"artifacts/{dispatch_id}/{f.name}", + "sha256": sha256_file(f), "size": f.stat().st_size}) + return out + + def _reconcile(self, req: dict) -> None: + did = req["dispatch_id"] + dispatch = self._make_dispatch(req, req["attempts"]) + self._emit("reconcile_attempt", {"dispatch_id": did, "request_id": req["id"], "attempt": req["attempts"]}, + {"request_id": req["id"], "dispatch_id": did}) + try: + res = self.ports.executor.reconcile(dispatch) + if not isinstance(res, ReconcileResult) or res.status not in ("complete", "unstarted", "unknown"): + raise ValueError("malformed reconcile result") + except Exception as exc: + res = ReconcileResult("unknown", note=f"reconcile failed: {type(exc).__name__}") + status = res.status + authority = dict(res.authority) if res.authority else None + if status == "unstarted": + if not (authority and authority.get("dispatch_id") == did + and isinstance(authority.get("basis"), str) and authority["basis"].strip()): + status = "unknown" + if status == "complete" and not isinstance(res.receipt, Receipt): + status = "unknown" + self._emit("reconcile_result", { + "dispatch_id": did, "request_id": req["id"], "status": status, "reported_status": res.status, + "authority": authority if status == "unstarted" else None, "note": res.note[:500], + }, {"request_id": req["id"], "dispatch_id": did}) + if status == "complete": + self._complete(req, res.receipt, via="reconciliation") + elif status == "unstarted": + self._dispatch(req, attempt=req["attempts"] + 1, basis="proven_unstarted_reconciliation") + else: + raise _Halt("reconciliation_needed", + f"dispatch {did} outcome is unknown; refusing to re-execute", dispatch_id=did) + + # ------------------------------------------------------- final choice + def _deny_final(self, fid: str, reason: str, detail: str) -> None: + msg = {"role": "tool", "content": canonical_bytes( + {"item_id": fid, "status": "denied", "reason": reason, "detail": detail}).decode()} + self._emit("final_choice_denied", {"item_id": fid, "reason": reason, "detail": detail, "message": msg}, + {"item_id": fid}) + + def _process_final(self, fid: str) -> None: + st = self.state + item = st.finals[fid] + payload = item["payload"] + if st.phase != "discovery": + return self._deny_final(fid, "phase_closed", f"phase is {st.phase}") + if not isinstance(payload, dict) or set(payload) - {"choice", "proposal", "rationale"}: + return self._deny_final(fid, "malformed", "final choice has unknown fields") + rationale = payload.get("rationale") + if not isinstance(rationale, str) or not rationale.strip() or len(rationale) > self.config.max_text_chars: + return self._deny_final(fid, "rationale_required", "a visible justification is required") + choice = payload.get("choice") + proposal = payload.get("proposal") + prop_info: dict = {} + if choice == "no_edit": + if proposal is not None or not self.config.allow_no_edit: + return self._deny_final(fid, "not_allowed", "no_edit with a proposal, or no_edit not enabled") + elif choice == "patch": + req = st.requests.get(proposal) if isinstance(proposal, str) else None + if req is None or req["status"] != "done" or \ + not self.config.operations[req["operation"]].selectable or req["receipt"]["status"] != "ok": + return self._deny_final(fid, "not_selectable", + "proposal must be a completed selectable request with an ok receipt") + if req["id"] not in st.delivered_receipts: + return self._deny_final(fid, "receipt_not_seen", "select a proposal after receiving its validated receipt") + prop_info = { + "proposal_request_id": req["id"], "proposal_dispatch_id": req["dispatch_id"], + "proposal_receipt_sha256": req["receipt_sha256"], "proposal_artifacts": req["artifacts"], + "proposal_arguments_sha256": digest_of(req["arguments"]), + } + prop_info["proposal_sha256"] = digest_of(prop_info) + else: + return self._deny_final(fid, "malformed", "choice must be 'patch' or 'no_edit'") + sel = { + "schema": "weight_editor_final_selection/v1", "run_id": self.run_id, + "binding_digest": self.manifest["binding_digest"], "item_id": fid, "choice": choice, + "rationale": rationale, **prop_info, + "evidence_digest": digest_of(st.results), + "artifacts_digest": digest_of(st.artifacts), + "budget_digest": digest_of(st.ledger.snapshot()), + "journal_head": self.journal.head, + "raw_head": self.raw.head, + } + path = self.run_dir / "final_selection.json" + if path.exists(): + old, _ = load_strict_file(path, what="final_selection.json") + stable = lambda d: {k: v for k, v in d.items() if k not in ("journal_head",)} + if stable(old) != stable(sel): + raise _Halt("final_selection_conflict", "existing final_selection.json disagrees with the journal") + sel = old + blob = path.read_bytes() + else: + blob = canonical_bytes(sel) + b"\n" + create_only(path, blob) + self._emit("final_patch_frozen", { + "item_id": fid, "choice": choice, "proposal_request_id": prop_info.get("proposal_request_id"), + "final_selection_sha256": sha256_hex(blob), "journal_head": sel["journal_head"], + "raw_head": sel["raw_head"], "evidence_digest": sel["evidence_digest"], + "artifacts_digest": sel["artifacts_digest"], "budget_digest": sel["budget_digest"], + }, {"item_id": fid}) + + def _finalize(self) -> None: + st = self.state + if st.terminal is not None: + return + arts = self.run_dir / "artifacts" / "manifest.json" + a_blob = canonical_bytes({"run_id": self.run_id, "artifacts": st.artifacts}) + b"\n" + if not arts.exists(): + create_only(arts, a_blob) + elif arts.read_bytes() != a_blob: + raise _Halt("artifacts_manifest_conflict", "artifacts/manifest.json disagrees with the journal") + terminal = { + "schema": "weight_editor_terminal/v1", "run_id": self.run_id, "status": "complete", + "binding_digest": self.manifest["binding_digest"], + "frozen_record_digest": st.frozen_record_digest, + "final_selection_sha256": st.frozen["final_selection_sha256"], + "raw_head_at_freeze": st.frozen["raw_head"], + "artifacts_manifest_sha256": sha256_hex(a_blob), + "budget_digest": st.frozen["budget_digest"], + "capture_incomplete": st.capture_incomplete, "unknown_events": st.unknown_events, + "capture_qualification": self._capture_qualification(), + "hidden_reasoning_captured": False, + } + t_blob = canonical_bytes(terminal) + b"\n" + tpath = self.run_dir / "terminal_manifest.json" + if tpath.exists(): + if tpath.read_bytes() != t_blob: + raise _Halt("terminal_conflict", "terminal manifest disagrees with the journal") + else: + create_only(tpath, t_blob) + self._emit("editor_terminal", {"terminal_manifest_sha256": sha256_hex(t_blob), "status": "complete"}) + from .replay import render_markdown # derived view, written once + + tfile = self.run_dir / "transcript.md" + if not tfile.exists(): + create_only(tfile, render_markdown(self.run_dir, self.journal.records, self.raw.records).encode()) + + # ------------------------------------------------------- summaries + def _capture_qualification(self) -> dict: + st = self.state + missing = sorted(st.completed_turns - st.model_verified_turns) + return {"qualified": not st.capture_incomplete and not missing, + "capture_incomplete": st.capture_incomplete, "missing_model_turns": missing, + "basis": "retained emitted streams and per-turn returned model identity"} + + def summary(self) -> dict: + st = self.state + return { + "run_id": self.run_id, "run_dir": str(self.run_dir), + "status": "complete" if st.status == "complete" else "incomplete", + "phase": st.phase, "halt": st.halt, "turns": st.turn_count, "resumes": st.resume_count, + "journal_records": len(self.journal.records), "raw_records": len(self.raw.records), + "journal_head": self.journal.head, "raw_head": self.raw.head, + "capture_incomplete": st.capture_incomplete, "unknown_events": st.unknown_events, + "capture_qualification": self._capture_qualification(), + "budget": st.ledger.snapshot(), + "dispatches": {r["dispatch_id"]: r["status"] for r in st.requests.values() if "dispatch_id" in r}, + "final_selection_sha256": st.frozen["final_selection_sha256"] if st.frozen else None, + "hidden_reasoning_captured": False, + } + + +def _public_bound(bound: Mapping[str, Any]) -> dict: + strip = lambda b: {k: v for k, v in b.items() if k != "path"} + return {k: ([strip(x) for x in v] if isinstance(v, list) else strip(v)) for k, v in bound.items()} + + +# ---------------------------------------------------- integrity helpers + + +def read_manifest(run_dir: Path) -> dict: + manifest, _ = load_strict_file(run_dir / "manifest.json", what="run manifest") + if manifest.get("schema") != MANIFEST_SCHEMA or digest_of(manifest["binding"]) != manifest.get("binding_digest"): + raise JournalCorrupt("run manifest binding digest does not match its binding", code="manifest_tampered") + return manifest + + +def _open_logs(run_dir: Path, manifest: dict, recover_tail: bool, clock): + bd, rid = manifest["binding_digest"], manifest["run_id"] + recovered: list[dict] = [] + logs = [] + for name, sub in (("journal", "journal"), ("provider", "provider")): + path = run_dir / sub / "events.jsonl" + genesis = genesis_prev(bd, name) + try: + logs.append(HashChainLog(path, rid, genesis, clock)) + except PartialTail: + if not recover_tail: + raise + info = quarantine_partial_tail(path, run_dir / "quarantine", rid, genesis) + recovered.append(info) + logs.append(HashChainLog(path, rid, genesis, clock)) + return logs[0], logs[1], recovered + + +def cross_check(run_dir: Path, journal: list[dict], raw: list[dict]) -> None: + by_seq = {r["seq"]: r for r in raw} + for rec in journal: + ref = rec["data"].get("raw") if isinstance(rec["data"], dict) else None + if ref: + target = by_seq.get(ref["seq"]) + if target is None or target["digest"] != ref["digest"] or target["data"]["raw_sha256"] != ref["sha256"]: + raise JournalCorrupt(f"journal seq {rec['seq']} references missing/altered raw event {ref['seq']}", + code="raw_reference_broken") + + +def _writer_session(run_dir: Path, clock=time.time): + """Lock + verify + fold a run without any ports (host-side maintenance actions).""" + if not (run_dir / "manifest.json").is_file(): + raise RunNotFound(f"no registered run at {run_dir}") + lock_fd = EditorRun._lock(run_dir / "lock") + try: + manifest = read_manifest(run_dir) + journal, raw, _ = _open_logs(run_dir, manifest, False, clock) + cross_check(run_dir, journal.records, raw.records) + except BaseException: + os.close(lock_fd) + raise + state = RunState({}) + for rec in journal.records: + state.apply(rec) + return lock_fd, journal, raw, state + + +def freeze_anchor(run_dir: Path) -> dict: + """Hash-only observation to keep under independent custody before evaluation.""" + from .replay import verify_run + + report = verify_run(run_dir) + if not report["ok"] or report["status"] != "complete" or not report["capture_qualification"]["qualified"]: + raise EditorError("anchor requires a verified, capture-qualified completed run", code="run_unqualified") + manifest = read_manifest(run_dir) + return {"schema": "weight_editor_freeze_anchor/v1", "run_id": manifest["run_id"], + "binding_digest": manifest["binding_digest"], + "final_selection_sha256": sha256_file(run_dir / "final_selection.json"), + "terminal_manifest_sha256": sha256_file(run_dir / "terminal_manifest.json"), + "journal_head": report["journal_head"], "raw_head": report["raw_head"]} + + +def write_anchor(run_dir: Path, output: Path) -> dict: + run_dir, output = Path(run_dir).resolve(), Path(output).resolve() + if output.is_relative_to(run_dir.parent): + raise EditorError("anchor must be outside the run output tree", code="anchor_location") + lock_fd, journal, raw, _ = _writer_session(run_dir) + try: + doc = freeze_anchor(run_dir) + try: + create_only(output, canonical_bytes(doc) + b"\n") + except FileExistsError as exc: + raise EditorError("freeze anchor already exists; it is never overwritten", code="anchor_exists") from exc + return {"ok": True, "anchor_sha256": sha256_file(output), "anchor": doc} + finally: + journal.close() + raw.close() + os.close(lock_fd) + + +def advance_phase(run_dir: Path, to: str, reference: str, clock=time.time, *, anchor_file: Path | None = None) -> dict: + """Host action: freeze -> independent_evaluation -> closed. Never reopens discovery.""" + nxt = {"independent_evaluation": "final_patch_frozen", "closed": "independent_evaluation"} + lock_fd, journal, raw, state = _writer_session(Path(run_dir), clock) + try: + if to not in nxt or state.phase != nxt[to] or state.status != "complete": + raise EditorError(f"cannot advance from {state.phase}/{state.status} to {to}", code="bad_transition") + from .replay import verify_run + + if anchor_file is None or Path(anchor_file).resolve().is_relative_to(Path(run_dir).resolve().parent): + raise EditorError("evaluation requires an external freeze anchor", code="anchor_required") + report = verify_run(Path(run_dir), anchor_file=Path(anchor_file)) + if not report["ok"] or not report["capture_qualification"]["qualified"]: + raise EditorError("run evidence or external anchor failed verification", code="run_unqualified") + rec = journal.append("phase_advanced", {"from": state.phase, "to": to, "reference": reference, + "anchor_sha256": sha256_file(Path(anchor_file))}) + return {"run_id": journal.run_id, "phase": to, "journal_head": rec["digest"]} + finally: + journal.close() + raw.close() + os.close(lock_fd) + + +def record_refusal(run_dir: Path, reason: str, detail: dict, clock=time.time) -> bool: + """Best-effort audit of a resume refused before ports were opened. Never raises.""" + try: + lock_fd, journal, raw, _ = _writer_session(Path(run_dir), clock) + except Exception: + return False + try: + journal.append("resume_refused", {"reason": reason, **detail}) + return True + finally: + journal.close() + raw.close() + os.close(lock_fd) diff --git a/synaptic_tuner/experimental/weight_editor/canon.py b/synaptic_tuner/experimental/weight_editor/canon.py new file mode 100644 index 000000000..26157aabd --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/canon.py @@ -0,0 +1,121 @@ +"""Canonical JSON, hashing and durable file primitives (stdlib only).""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +from pathlib import Path +from typing import Any + +from .errors import ConfigError + + +def check_json(value: Any, where: str = "$") -> None: + """Reject anything that is not strictly JSON-representable and finite.""" + if value is None or isinstance(value, (bool, str)): + return + if isinstance(value, int): + return + if isinstance(value, float): + if not math.isfinite(value): + raise ValueError(f"non-finite number at {where}") + return + if isinstance(value, list): + for i, item in enumerate(value): + check_json(item, f"{where}[{i}]") + return + if isinstance(value, dict): + for key, item in value.items(): + if not isinstance(key, str): + raise ValueError(f"non-string key at {where}") + check_json(item, f"{where}.{key}") + return + raise ValueError(f"unsupported JSON type {type(value).__name__} at {where}") + + +def canonical_bytes(value: Any) -> bytes: + check_json(value) + return json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False + ).encode("utf-8") + + +def sha256_hex(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def digest_of(value: Any) -> str: + return sha256_hex(canonical_bytes(value)) + + +def _no_constant(name: str): + raise ValueError(f"non-finite constant {name} is not allowed") + + +def _no_duplicates(pairs): + out = {} + for key, val in pairs: + if key in out: + raise ValueError(f"duplicate key {key!r}") + out[key] = val + return out + + +def strict_loads(data: bytes | str) -> Any: + """Parse JSON rejecting duplicate keys and NaN/Infinity.""" + text = data.decode("utf-8") if isinstance(data, (bytes, bytearray)) else data + return json.loads(text, parse_constant=_no_constant, object_pairs_hook=_no_duplicates) + + +def load_strict_file(path: Path, *, what: str) -> tuple[Any, bytes]: + try: + raw = Path(path).read_bytes() + except OSError as exc: + raise ConfigError(f"cannot read {what} {path}: {exc.strerror}", code="unreadable") from exc + try: + return strict_loads(raw), raw + except (ValueError, UnicodeDecodeError) as exc: + raise ConfigError(f"{what} {path} is not strict JSON: {exc}") from exc + + +def fsync_dir(path: Path) -> None: + fd = os.open(str(path), os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def create_only(path: Path, data: bytes) -> None: + """Create a new file (never overwrite), fsync it and its directory.""" + fd = os.open(str(path), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + try: + view = memoryview(data) + while view: + n = os.write(fd, view) + if n <= 0: + raise OSError("file write made no progress") + view = view[n:] + os.fsync(fd) + finally: + os.close(fd) + fsync_dir(path.parent) + + +def sha256_file(path: Path) -> str: + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def is_finite_nonneg(value: Any) -> bool: + return ( + isinstance(value, (int, float)) + and not isinstance(value, bool) + and math.isfinite(value) + and value >= 0 + ) diff --git a/synaptic_tuner/experimental/weight_editor/cli.py b/synaptic_tuner/experimental/weight_editor/cli.py new file mode 100644 index 000000000..fb129cd62 --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/cli.py @@ -0,0 +1,240 @@ +"""CLI: ``python -m synaptic_tuner.experimental.weight_editor ``. + +Exit codes: 0 ok/complete, 1 refused or invalid input, 3 incomplete and +reconciliation needed, 4 incomplete for another reason, 5 verification failed. +``--ports`` names an operator-trusted ``module:factory``; it is never read from +the config or from a model request. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +from . import broker, replay +from .canon import create_only, strict_loads +from .config import load_config +from .errors import EditorError, PartialTail +from .fakes import write_fixture +from .ports import PortContext, load_ports + + +def _kv(items: list[str]) -> dict[str, str]: + out = {} + for item in items or []: + if "=" not in item: + raise EditorError(f"--ports-arg expects key=value, got {item!r}", code="usage") + k, v = item.split("=", 1) + out[k] = v + return out + + +def _binding(path: str | None) -> dict: + if not path: + return {} + try: + data = strict_loads(Path(path).read_bytes()) + except (OSError, ValueError) as exc: + raise EditorError(f"cannot read binding file: {exc}", code="usage") from exc + if not isinstance(data, dict): + raise EditorError("binding file must be a JSON object", code="usage") + return data + + +def _ports(args, config): + if not args.ports: + raise EditorError("--ports module:factory is required", code="usage") + return load_ports(args.ports, PortContext(_kv(args.ports_arg), config.model.requested())) + + +def _emit(obj: dict) -> None: + print(json.dumps(obj, indent=2, sort_keys=True)) + + +def _exit_for(summary: dict) -> int: + if summary["status"] == "complete": + return 0 if summary["capture_qualification"]["qualified"] else 6 + halt = summary.get("halt") or {} + return 3 if halt.get("code") == "reconciliation_needed" else 4 + + +def cmd_validate(args) -> int: + config = load_config(Path(args.config)) + ports = _ports(args, config) + report = broker.validate_ports(config, ports) + ports.executor.close() + _emit({ + "ok": True, "config_sha256": config.sha256, "capsule_manifest_sha256": config.capsule.manifest_sha256, + "capsule_objects": len(config.capsule.objects), "operations": sorted(config.operations), + "output_root": str(config.output_root), "limits": dict(config.limits) or "none configured (caller-owned)", + "ports": report, "effects": "none: validate performs no executor or model call", + }) + return 0 + + +def cmd_run(args) -> int: + config = load_config(Path(args.config)) + ports = _ports(args, config) + run = broker.EditorRun.create(config, ports, args.run_id, _binding(args.binding_file)) + try: + summary = run.run() + finally: + run.close() + _emit(summary) + return _exit_for(summary) + + +def cmd_resume(args) -> int: + try: + config = load_config(Path(args.config)) + except EditorError as exc: + _audit_pre_open_refusal(args, exc) + raise + ports = _ports(args, config) + run = broker.EditorRun.open(config, ports, args.run_id, _binding(args.binding_file), + recover_tail=args.recover_partial_tail) + try: + summary = run.run() + finally: + run.close() + _emit(summary) + return _exit_for(summary) + + +def _audit_pre_open_refusal(args, exc: EditorError) -> None: + """Config/capsule drift is refused before any port exists; still leave audit evidence.""" + try: + data = strict_loads(Path(args.config).read_bytes()) + out = (Path(args.config).resolve().parent / data["output_root"]).resolve() + except Exception: + return + run_dir = out / args.run_id + if (run_dir / "manifest.json").is_file(): + broker.record_refusal(run_dir, "config_or_capsule_invalid", {"code": exc.code, "message": str(exc)}) + + +def cmd_verify(args) -> int: + report = replay.verify_run(Path(args.run_dir), anchor_file=Path(args.anchor_file) if args.anchor_file else None) + _emit(report) + return (5 if not report["ok"] else 6 if report["status"] == "complete" + and not report["capture_qualification"]["qualified"] else 0) + + +def cmd_status(args) -> int: + return cmd_verify(args) + + +def cmd_replay(args) -> int: + run_dir = Path(args.run_dir) + manifest, journal, raw = replay.load_verified(run_dir) + text = replay.render_markdown(run_dir, journal, raw) + out = Path(args.output) if args.output else run_dir / "transcript.md" + if out.exists() and out.read_bytes() != text.encode() and not args.force: + raise EditorError(f"{out} exists with different content; pass --force to replace the derived view", + code="output_exists") + if args.force and out.exists(): + out.write_text(text) + elif not out.exists(): + create_only(out, text.encode()) + _emit({"ok": True, "transcript": str(out), "journal_records": len(journal), "raw_records": len(raw)}) + return 0 + + +def cmd_advance(args) -> int: + _emit(broker.advance_phase(Path(args.run_dir), args.to, args.reference, + anchor_file=Path(args.anchor_file) if args.anchor_file else None)) + return 0 + + +def cmd_anchor(args) -> int: + _emit(broker.write_anchor(Path(args.run_dir), Path(args.output))) + return 0 + + +def cmd_smoke(args) -> int: + workdir = Path(args.workdir) + if workdir.exists(): + raise EditorError(f"{workdir} exists; smoke never overwrites", code="run_exists") + fx = write_fixture(workdir) + config = load_config(fx["config"]) + ports = load_ports("synaptic_tuner.experimental.weight_editor.fakes:build_ports", + PortContext({"script": str(fx["script"]), "effects_dir": str(fx["effects"])}, + config.model.requested())) + run = broker.EditorRun.create(config, ports, args.run_id, {"smoke": "synthetic"}) + try: + summary = run.run() + finally: + run.close() + report = replay.verify_run(Path(summary["run_dir"])) + effects = [json.loads(x) for x in (fx["effects"] / "effects.log").read_text().splitlines()] + ok = summary["status"] == "complete" and report["ok"] and summary["capture_qualification"]["qualified"] + _emit({"ok": ok, "summary": summary, "verify": report, + "effect_count": len(effects), "unique_dispatches": len({e["dispatch_id"] for e in effects}), + "transcript": str(Path(summary["run_dir"]) / "transcript.md")}) + return 0 if ok else 6 if report["ok"] else 5 + + +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser(prog="weight_editor", description=__doc__.split("\n\n")[0]) + sub = p.add_subparsers(dest="cmd", required=True) + + def ports_args(sp): + sp.add_argument("--config", required=True) + sp.add_argument("--ports", help="operator-trusted module:factory returning PortSet") + sp.add_argument("--ports-arg", action="append", default=[], metavar="KEY=VALUE") + sp.add_argument("--binding-file", help="JSON object of source/runtime identifiers bound into the run") + + sp = sub.add_parser("validate", help="validate config, capsule and ports; no run, no effects") + ports_args(sp) + sp.set_defaults(fn=cmd_validate) + sp = sub.add_parser("run", help="register a NEW run and drive it") + ports_args(sp) + sp.add_argument("--run-id", required=True) + sp.set_defaults(fn=cmd_run) + sp = sub.add_parser("resume", help="resume a run under identical bytes; reconciles in-flight dispatches") + ports_args(sp) + sp.add_argument("--run-id", required=True) + sp.add_argument("--recover-partial-tail", action="store_true", + help="quarantine (never delete) an incomplete final log line and record an audit entry") + sp.set_defaults(fn=cmd_resume) + for name, fn in (("verify", cmd_verify), ("status", cmd_status)): + sp = sub.add_parser(name, help="verify hash chains, raw references, receipts and artifacts") + sp.add_argument("--run-dir", required=True) + sp.add_argument("--anchor-file") + sp.set_defaults(fn=fn) + sp = sub.add_parser("replay", help="export a readable Markdown transcript from the retained run") + sp.add_argument("--run-dir", required=True) + sp.add_argument("--output") + sp.add_argument("--force", action="store_true") + sp.set_defaults(fn=cmd_replay) + sp = sub.add_parser("advance", help="host action: final_patch_frozen -> independent_evaluation -> closed") + sp.add_argument("--run-dir", required=True) + sp.add_argument("--to", required=True, choices=["independent_evaluation", "closed"]) + sp.add_argument("--reference", required=True) + sp.add_argument("--anchor-file", help="externally retained freeze anchor; required before evaluation") + sp.set_defaults(fn=cmd_advance) + sp = sub.add_parser("anchor", help="write hash-only freeze anchor outside the run output tree") + sp.add_argument("--run-dir", required=True) + sp.add_argument("--output", required=True) + sp.set_defaults(fn=cmd_anchor) + sp = sub.add_parser("smoke", help="deterministic synthetic smoke with fake ports (no model call)") + sp.add_argument("--workdir", required=True) + sp.add_argument("--run-id", default="smoke-1") + sp.set_defaults(fn=cmd_smoke) + return p + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + try: + return args.fn(args) + except EditorError as exc: + _emit({"ok": False, "error": {"code": exc.code, "message": str(exc), **{k: v for k, v in exc.details.items()}}}) + return 1 if not isinstance(exc, PartialTail) and exc.code not in ( + "journal_corrupt", "hash_mismatch", "manifest_tampered", "raw_reference_broken") else 5 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/synaptic_tuner/experimental/weight_editor/config.py b/synaptic_tuner/experimental/weight_editor/config.py new file mode 100644 index 000000000..b9f63437a --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/config.py @@ -0,0 +1,424 @@ +"""Config-first run policy and hash-frozen input capsule. + +Everything scientific or model-specific lives in the host-owned config JSON. +The core never branches on a model name. Unknown keys are errors so that a +config cannot silently carry authority the validator does not understand. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Mapping + +from .canon import is_finite_nonneg, load_strict_file, sha256_file, sha256_hex +from .errors import CapsuleError, ConfigError + +CONFIG_SCHEMA = "weight_editor_config/v1" +CAPSULE_SCHEMA = "weight_editor_capsule/v1" + +ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$") +RUN_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$") +OP_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") +RESOURCE_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") +SHA_RE = re.compile(r"^[0-9a-f]{64}$") + +# Names that denote host authority. Neither a model request nor an operation declaration may use them +# as an argument name: a model cannot be handed a path/command/policy knob. +AUTHORITY_NAMES = frozenset( + { + "path", "paths", "file", "files", "command", "cmd", "shell", "exec", "import", "module", + "url", "uri", "policy", "budget", "limits", "output_root", "env", "cwd", "executor", + "adapter", "model", "split", "heldout", "held_out", "write", "target", "capsule", + } +) +BUILTIN_METERS = ("requests", "model_turns", "dispatches") +ARG_TYPES = ("ref", "ref_list", "int", "number", "enum", "text", "artifact_name") + + +def _strict(obj: Any, required: set[str], optional: set[str], where: str) -> dict: + if not isinstance(obj, dict): + raise ConfigError(f"{where} must be an object") + missing = required - obj.keys() + if missing: + raise ConfigError(f"{where} missing keys: {sorted(missing)}") + extra = obj.keys() - required - optional + if extra: + raise ConfigError(f"{where} has unknown keys: {sorted(extra)}") + return obj + + +@dataclass(frozen=True) +class ModelSpec: + provider: str + model: str + settings: Mapping[str, Any] + allowed_returned: tuple[str, ...] + + def requested(self) -> dict: + return {"provider": self.provider, "model": self.model, "settings": dict(self.settings)} + + +@dataclass(frozen=True) +class ArgSpec: + name: str + type: str + required: bool + params: Mapping[str, Any] + + +@dataclass(frozen=True) +class OperationSpec: + name: str + description: str + args: Mapping[str, ArgSpec] + cost: Mapping[str, Any] + selectable: bool + + +@dataclass(frozen=True) +class CapsuleObject: + id: str + kind: str + rel_path: str + sha256: str + size: int + abs_path: Path + + +@dataclass(frozen=True) +class Capsule: + root: Path + manifest_bytes: bytes + manifest_sha256: str + capsule_id: str + objects: Mapping[str, CapsuleObject] + + def listing(self) -> list[dict]: + """Opaque model-visible view: no paths.""" + return [ + {"id": o.id, "kind": o.kind, "sha256": o.sha256, "size": o.size} + for o in sorted(self.objects.values(), key=lambda o: o.id) + ] + + def verify_objects(self, ids=None) -> list[str]: + """Return ids whose on-disk bytes no longer match the frozen hash.""" + bad = [] + for oid in sorted(ids if ids is not None else self.objects): + obj = self.objects[oid] + try: + if ( + not obj.abs_path.is_file() + or obj.abs_path.resolve() != obj.abs_path + or sha256_file(obj.abs_path) != obj.sha256 + ): + bad.append(oid) + except OSError: + bad.append(oid) + return bad + + +@dataclass(frozen=True) +class EditorConfig: + path: Path + raw_bytes: bytes + sha256: str + model: ModelSpec + capsule: Capsule + instructions: tuple[Mapping[str, Any], ...] + operations: Mapping[str, OperationSpec] + output_root: Path + read_only_roots: tuple[Path, ...] + limits: Mapping[str, float] + allow_no_edit: bool + withheld_digests: frozenset[str] + max_text_chars: int + data: Mapping[str, Any] = field(repr=False, default_factory=dict) + + +# ---------------------------------------------------------------- capsule + + +def load_capsule(manifest_path: Path) -> Capsule: + manifest_path = Path(manifest_path) + data, raw = _load(manifest_path, "capsule manifest", CapsuleError) + _strict_c(data, {"schema", "capsule_id", "objects"}, set(), "capsule manifest") + if data["schema"] != CAPSULE_SCHEMA: + raise CapsuleError(f"capsule schema must be {CAPSULE_SCHEMA}") + if not isinstance(data["capsule_id"], str) or not ID_RE.match(data["capsule_id"]): + raise CapsuleError("capsule_id malformed") + root = manifest_path.resolve().parent + objects: dict[str, CapsuleObject] = {} + if not isinstance(data["objects"], list) or not data["objects"]: + raise CapsuleError("capsule objects must be a non-empty list") + for i, item in enumerate(data["objects"]): + where = f"capsule object[{i}]" + _strict_c(item, {"id", "kind", "path", "sha256", "split"}, set(), where) + oid, kind, rel = item["id"], item["kind"], item["path"] + if not isinstance(oid, str) or not ID_RE.match(oid): + raise CapsuleError(f"{where} id malformed") + if oid in objects: + raise CapsuleError(f"duplicate capsule object id {oid!r}") + if not isinstance(kind, str) or not RESOURCE_RE.match(kind): + raise CapsuleError(f"{where} kind malformed") + if item["split"] != "development": + raise CapsuleError( + f"{where} split must be 'development': capsule holds registered development objects only", + code="non_development_object", + ) + if not isinstance(item["sha256"], str) or not SHA_RE.match(item["sha256"]): + raise CapsuleError(f"{where} sha256 malformed") + abs_path = _contained_file(root, rel, where) + if sha256_file(abs_path) != item["sha256"]: + raise CapsuleError(f"{where} bytes do not match frozen sha256", code="capsule_hash_mismatch") + objects[oid] = CapsuleObject(oid, kind, rel, item["sha256"], abs_path.stat().st_size, abs_path) + return Capsule(root, raw, sha256_hex(raw), data["capsule_id"], objects) + + +def _strict_c(obj, required, optional, where): + try: + return _strict(obj, required, optional, where) + except ConfigError as exc: + raise CapsuleError(str(exc)) from exc + + +def _load(path: Path, what: str, exc_type): + try: + return load_strict_file(path, what=what) + except ConfigError as exc: + if exc_type is ConfigError: + raise + raise exc_type(str(exc), code=exc.code) from exc + + +def _contained_file(root: Path, rel: Any, where: str) -> Path: + if not isinstance(rel, str) or not rel: + raise CapsuleError(f"{where} path must be a non-empty string") + if rel.startswith(("/", "~")) or "\\" in rel or "\x00" in rel or re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", rel): + raise CapsuleError(f"{where} path must be a relative capsule path", code="path_not_relative") + if ".." in Path(rel).parts: + raise CapsuleError(f"{where} path traversal", code="path_traversal") + candidate = root / rel + try: + resolved = candidate.resolve(strict=True) + except OSError as exc: + raise CapsuleError(f"{where} path does not exist", code="path_missing") from exc + if not resolved.is_relative_to(root): + raise CapsuleError(f"{where} escapes capsule root (symlink or traversal)", code="path_escape") + if not resolved.is_file(): + raise CapsuleError(f"{where} is not a regular file", code="path_not_file") + return resolved + + +# ----------------------------------------------------------------- config + + +def load_config(path: Path) -> EditorConfig: + path = Path(path) + data, raw = load_strict_file(path, what="config") + _strict( + data, + {"schema", "model", "capsule", "operations", "output_root"}, + {"instructions", "read_only_roots", "resources", "final_choice", "withheld_id_digests"}, + "config", + ) + if data["schema"] != CONFIG_SCHEMA: + raise ConfigError(f"config schema must be {CONFIG_SCHEMA}") + base = path.resolve().parent + + m = _strict(data["model"], {"provider", "model", "settings"}, {"allowed_returned"}, "model") + for key in ("provider", "model"): + if not isinstance(m[key], str) or not m[key].strip(): + raise ConfigError(f"model.{key} must be a non-empty string; no default/fallback exists") + if not isinstance(m["settings"], dict): + raise ConfigError("model.settings must be an object") + allowed = m.get("allowed_returned", []) + if not isinstance(allowed, list) or not all(isinstance(x, str) and x for x in allowed): + raise ConfigError("model.allowed_returned must be a list of strings") + model = ModelSpec(m["provider"], m["model"], m["settings"], tuple(allowed)) + + cap = _strict(data["capsule"], {"manifest"}, set(), "capsule") + if not isinstance(cap["manifest"], str): + raise ConfigError("capsule.manifest must be a path string") + capsule = load_capsule(_host_path(base, cap["manifest"])) + + instructions = [] + for i, item in enumerate(data.get("instructions", [])): + where = f"instructions[{i}]" + if not isinstance(item, dict) or item.get("role") not in ("system", "user"): + raise ConfigError(f"{where} needs role system|user") + if set(item) == {"role", "text"} and isinstance(item["text"], str): + instructions.append({"role": item["role"], "text": item["text"]}) + elif set(item) == {"role", "object"} and isinstance(item["object"], str): + obj = capsule.objects.get(item["object"]) + if obj is None or obj.kind != "instructions": + raise ConfigError(f"{where} object must be a capsule object of kind 'instructions'") + instructions.append({"role": item["role"], "object": item["object"]}) + else: + raise ConfigError(f"{where} must be exactly role+text or role+object") + + operations = _parse_operations(data["operations"]) + + out_root = _host_path(base, data["output_root"]) if isinstance(data["output_root"], str) else None + if out_root is None: + raise ConfigError("output_root must be a path string") + out_root = out_root.resolve() + ro = [] + for item in data.get("read_only_roots", []): + if not isinstance(item, str): + raise ConfigError("read_only_roots entries must be path strings") + ro.append(_host_path(base, item).resolve()) + for guarded in (capsule.root, *ro): + if out_root.is_relative_to(guarded) or guarded.is_relative_to(out_root): + raise ConfigError( + f"output_root {out_root} overlaps source/base root {guarded}", code="output_root_overlap" + ) + + res = _strict(data.get("resources", {}), set(), {"limits"}, "resources") + limits: dict[str, float] = {} + lim = res.get("limits", {}) + if not isinstance(lim, dict): + raise ConfigError("resources.limits must be an object") + for name, val in lim.items(): + if not RESOURCE_RE.match(name) or not is_finite_nonneg(val): + raise ConfigError(f"resource limit {name!r} must be a finite non-negative number") + limits[name] = val + for op in operations.values(): + for rname in op.cost: + if not RESOURCE_RE.match(rname): + raise ConfigError(f"operation {op.name} cost resource {rname!r} malformed") + measured = {"requests", "model_turns", "dispatches", "dispatch_attempts"} + measured.update(r for op in operations.values() for r in op.cost) + unmeasured = set(limits) - measured + if unmeasured: + raise ConfigError(f"limits have no configured meter: {sorted(unmeasured)}", code="unmeasured_resource") + + fc = _strict(data.get("final_choice", {}), set(), {"allow_no_edit", "max_rationale_chars"}, "final_choice") + allow_no_edit = fc.get("allow_no_edit", True) + if not isinstance(allow_no_edit, bool): + raise ConfigError("final_choice.allow_no_edit must be boolean") + max_text = fc.get("max_rationale_chars", 20000) + if not isinstance(max_text, int) or isinstance(max_text, bool) or max_text <= 0: + raise ConfigError("final_choice.max_rationale_chars must be a positive integer") + + withheld = data.get("withheld_id_digests", []) + if not isinstance(withheld, list) or not all(isinstance(x, str) and SHA_RE.match(x) for x in withheld): + raise ConfigError("withheld_id_digests must be a list of sha256 hex digests") + + return EditorConfig( + path=path.resolve(), + raw_bytes=raw, + sha256=sha256_hex(raw), + model=model, + capsule=capsule, + instructions=tuple(instructions), + operations=operations, + output_root=out_root, + read_only_roots=tuple(ro), + limits=limits, + allow_no_edit=allow_no_edit, + withheld_digests=frozenset(withheld), + max_text_chars=max_text, + data=data, + ) + + +def _host_path(base: Path, value: str) -> Path: + p = Path(value) + return p if p.is_absolute() else base / p + + +def _parse_operations(ops: Any) -> dict[str, OperationSpec]: + if not isinstance(ops, dict) or not ops: + raise ConfigError("operations must be a non-empty object (no operation is admitted by default)") + out: dict[str, OperationSpec] = {} + for name, spec in ops.items(): + if not OP_RE.match(name): + raise ConfigError(f"operation name {name!r} malformed") + where = f"operations.{name}" + spec = _strict(spec, {"arguments"}, {"description", "cost", "selectable", "required"}, where) + args: dict[str, ArgSpec] = {} + required = spec.get("required", []) + if not isinstance(required, list) or not all(isinstance(x, str) for x in required): + raise ConfigError(f"{where}.required must be a list of argument names") + if not isinstance(spec["arguments"], dict): + raise ConfigError(f"{where}.arguments must be an object") + for an, aspec in spec["arguments"].items(): + if not ID_RE.match(an): + raise ConfigError(f"{where} argument name {an!r} malformed") + if an in AUTHORITY_NAMES: + raise ConfigError(f"{where} argument name {an!r} denotes host authority and cannot be model-settable", + code="authority_argument_name") + args[an] = _parse_arg(an, aspec, an in required, f"{where}.arguments.{an}") + for r in required: + if r not in args: + raise ConfigError(f"{where}.required names undeclared argument {r!r}") + cost = spec.get("cost", {}) + if not isinstance(cost, dict): + raise ConfigError(f"{where}.cost must be an object") + for rname, c in cost.items(): + _validate_cost(c, args, f"{where}.cost.{rname}") + sel = spec.get("selectable", False) + if not isinstance(sel, bool): + raise ConfigError(f"{where}.selectable must be boolean") + desc = spec.get("description", "") + if not isinstance(desc, str): + raise ConfigError(f"{where}.description must be a string") + out[name] = OperationSpec(name, desc, args, cost, sel) + return out + + +def _parse_arg(name: str, spec: Any, required: bool, where: str) -> ArgSpec: + if not isinstance(spec, dict) or spec.get("type") not in ARG_TYPES: + raise ConfigError(f"{where}.type must be one of {ARG_TYPES}") + t = spec["type"] + allowed = { + "ref": ({"type", "kind"}, {"kind"}), + "ref_list": ({"type", "kind", "max_items"}, {"kind", "max_items"}), + "int": ({"type", "min", "max"}, {"min", "max"}), + "number": ({"type", "min", "max"}, {"min", "max"}), + "enum": ({"type", "values"}, {"values"}), + "text": ({"type", "max_length"}, {"max_length"}), + "artifact_name": ({"type"}, set()), + }[t] + extra = spec.keys() - allowed[0] + missing = allowed[1] - spec.keys() + if extra or missing: + raise ConfigError(f"{where} bad keys (extra={sorted(extra)} missing={sorted(missing)})") + params = {k: v for k, v in spec.items() if k != "type"} + if "kind" in params and not (isinstance(params["kind"], str) and RESOURCE_RE.match(params["kind"])): + raise ConfigError(f"{where}.kind malformed") + for key in ("max_items", "max_length"): + if key in params and not (isinstance(params[key], int) and not isinstance(params[key], bool) and params[key] > 0): + raise ConfigError(f"{where}.{key} must be a positive integer") + for key in ("min", "max"): + if key in params: + v = params[key] + if isinstance(v, bool) or not isinstance(v, (int, float)) or v != v or abs(v) == float("inf"): + raise ConfigError(f"{where}.{key} must be finite") + if t == "int" and not isinstance(v, int): + raise ConfigError(f"{where}.{key} must be an integer") + if "min" in params and params["min"] > params["max"]: + raise ConfigError(f"{where} min > max") + if t == "enum" and not ( + isinstance(params["values"], list) and params["values"] and all(isinstance(x, str) for x in params["values"]) + ): + raise ConfigError(f"{where}.values must be a non-empty list of strings") + return ArgSpec(name, t, required, params) + + +def _validate_cost(c: Any, args: Mapping[str, ArgSpec], where: str) -> None: + if is_finite_nonneg(c): + return + if isinstance(c, dict) and set(c) == {"from_arg"}: + a = args.get(c["from_arg"]) + if a is None or a.type not in ("int", "number") or "min" not in a.params or a.params["min"] < 0: + raise ConfigError(f"{where}.from_arg must name a bounded non-negative numeric argument") + return + if isinstance(c, dict) and set(c) == {"len_of", "per_item"}: + a = args.get(c["len_of"]) + if a is None or a.type != "ref_list" or not is_finite_nonneg(c["per_item"]): + raise ConfigError(f"{where}.len_of must name a ref_list argument with finite per_item") + return + raise ConfigError(f"{where} must be a finite non-negative number, {{from_arg}} or {{len_of, per_item}}") diff --git a/synaptic_tuner/experimental/weight_editor/errors.py b/synaptic_tuner/experimental/weight_editor/errors.py new file mode 100644 index 000000000..4fc8090a1 --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/errors.py @@ -0,0 +1,81 @@ +"""Error types. Every error carries a stable machine-readable ``code``.""" + +from __future__ import annotations + + +class EditorError(Exception): + code = "editor_error" + + def __init__(self, message: str, *, code: str | None = None, **details): + super().__init__(message) + if code: + self.code = code + self.details = details + + +class ConfigError(EditorError): + code = "config_invalid" + + +class CapsuleError(EditorError): + code = "capsule_invalid" + + +class UnsupportedCapability(EditorError): + """A trusted port explicitly rejects a configured capability.""" + + code = "unsupported_capability" + + +class PortError(EditorError): + code = "port_invalid" + + +class RunExists(EditorError): + code = "run_exists" + + +class RunNotFound(EditorError): + code = "run_not_found" + + +class LockHeld(EditorError): + code = "lock_held" + + +class IdentityDrift(EditorError): + code = "identity_drift" + + +class JournalCorrupt(EditorError): + code = "journal_corrupt" + + +class PartialTail(JournalCorrupt): + code = "partial_tail" + + +class WriteBoundaryViolation(EditorError): + code = "write_boundary_violation" + + +class ExecutorRejection(EditorError): + """Executor refuses an operation with proof that no effect started.""" + + code = "executor_rejected" + + +class AdapterFailure(EditorError): + code = "adapter_failure" + + +class AdapterCancelled(AdapterFailure): + code = "adapter_cancelled" + + +class AdapterTimeout(AdapterFailure): + code = "adapter_timeout" + + +class PhaseError(EditorError): + code = "phase_closed" diff --git a/synaptic_tuner/experimental/weight_editor/fakes.py b/synaptic_tuner/experimental/weight_editor/fakes.py new file mode 100644 index 000000000..c38942d0c --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/fakes.py @@ -0,0 +1,339 @@ +"""Deterministic fake ports and a synthetic fixture generator (CPU, stdlib). + +These ports never contact a hosted model. ``FakeEffectExecutor`` keeps its own durable +effect ledger so tests can prove, from outside the broker, that an effect +happened once and only once. All content is synthetic. +""" + +from __future__ import annotations + +import json +import math +import os +import time +from pathlib import Path +from typing import Any, Iterator, Mapping + +from .canon import canonical_bytes, create_only, sha256_hex, strict_loads +from .errors import AdapterCancelled, AdapterTimeout, ExecutorRejection, PortError +from .ports import ( + BoundedWriter, Dispatch, Executor, ModelAdapter, PortContext, PortSet, Receipt, + ReconcileResult, TransportEvent, TurnInput, +) + +HELDOUT_ID = "heldout-007" # synthetic withheld id; only its digest appears in config + +# --------------------------------------------------------------- adapter + + +class ScriptedAdapter(ModelAdapter): + """Emits scripted raw events per turn index. Never calls any model.""" + + def __init__(self, script: Mapping[str, Any], model: Mapping[str, Any], script_sha256: str): + self._script = script + self._model = dict(model) + self._script_sha = script_sha256 + + def identity(self) -> dict: + return {**self._model, "client_version": "scripted-0", "script_sha256": self._script_sha, + "capabilities": {"raw_events": True, "reasoning_summaries": True, + "captures_hidden_reasoning": False, "tool_isolation": "none"}} + + def run_turn(self, turn: TurnInput) -> Iterator[bytes]: + turns = self._script.get("turns", []) + if turn.turn_index > len(turns): + return + spec = turns[turn.turn_index - 1] + for ev in spec.get("events", []): + if set(ev) == {"transport_channel", "raw_b64"}: + import base64 + yield TransportEvent(base64.b64decode(ev["raw_b64"]), ev["transport_channel"]) + continue + if ev == {"self_sigkill": True}: # real SIGKILL of this process mid-turn + import signal + os.kill(os.getpid(), signal.SIGKILL) + if "raw" in ev and len(ev) == 1: + yield ev["raw"].encode("utf-8") + elif "raw_b64" in ev and len(ev) == 1: + import base64 + yield base64.b64decode(ev["raw_b64"]) + else: + yield json.dumps(ev).encode("utf-8") + fail = spec.get("fail") + if fail == "cancelled": + raise AdapterCancelled("scripted cancellation") + if fail == "timeout": + raise AdapterTimeout("scripted timeout") + if fail == "provider_error": + raise RuntimeError("scripted provider failure") + if spec.get("model_identity", True): + # This is synthetic provider evidence, never used by the real adapter. + yield json.dumps({"type": "session_started", "model": self._model["model"]}).encode("utf-8") + + def parse_event(self, raw: bytes) -> dict: + ev = strict_loads(raw) + if not isinstance(ev, dict): + return {"kind": "unknown"} + t = ev.get("type") + rest = {k: v for k, v in ev.items() if k != "type"} + table = { + "assistant_message": "message", "reasoning_summary": "reasoning_summary", + "tool_request": "request", "final_choice": "final_choice", "session_started": "session", + "usage": "usage", "turn_finished": "finish", "handoff": "handoff", "truncation": "truncation", + } + kind = table.get(t) + return {"kind": kind, **rest} if kind else {"kind": "unknown"} + + +# -------------------------------------------------------------- executor + + +class FakeEffectExecutor(Executor): + """Synthetic executor with an external, fsynced effect ledger. + + Supported operations: inspect_weights, query_development, propose_patch. + ``analyze`` is deliberately unsupported to exercise capability rejection. + """ + + OPS = frozenset({"inspect_weights", "query_development", "propose_patch"}) + + def __init__(self, effects_dir: Path, pause_at: str | None = None, pause_op: str | None = None, + fault: str | None = None): + self.dir = Path(effects_dir) + (self.dir / "dispatches").mkdir(parents=True, exist_ok=True) + self.pause_at, self.pause_op, self.fault = pause_at, pause_op, fault + + def identity(self) -> dict: + return {"name": "fake-effect-executor", "version": 1, "operations": sorted(self.OPS)} + + def supported_operations(self) -> frozenset[str]: + return self.OPS + + # ---- validation (side-effect free) + def validate(self, operation: str, arguments: Mapping[str, Any], bound: Mapping[str, Any]) -> None: + if operation == "propose_patch": + for key in ("patch", "justification"): + if not str(arguments.get(key, "")).strip(): + raise ExecutorRejection(f"{key} must be non-empty") + + # ---- helpers + def _log_path(self) -> Path: + return self.dir / "effects.log" + + def _append_effect(self, dispatch: Dispatch) -> None: + line = json.dumps({"dispatch_id": dispatch.dispatch_id, "op": dispatch.operation}) + "\n" + fd = os.open(str(self._log_path()), os.O_CREAT | os.O_APPEND | os.O_WRONLY, 0o600) + try: + os.write(fd, line.encode()) + os.fsync(fd) + finally: + os.close(fd) + + def _pause(self, stage: str, op: str) -> None: + if self.pause_at == stage and self.pause_op in (None, op): + create_only(self.dir / f"paused-{stage}", b"1") + time.sleep(300) + + # ---- execution + def execute(self, dispatch: Dispatch, writer: BoundedWriter) -> Receipt: + if self.fault == "reject_execute": + raise ExecutorRejection("fault: executor refuses before any effect") + started = self.dir / "dispatches" / f"{dispatch.dispatch_id}.started" + self._pause("before_started", dispatch.operation) + create_only(started, b"1") # fsynced before the effect so reconcile can tell "maybe started" + self._pause("after_started", dispatch.operation) + if self.fault == "escape_write": + writer.write("../../escape.txt", b"x") + self._append_effect(dispatch) + receipt = self._compute(dispatch, writer) + self._pause("before_done", dispatch.operation) + if self.fault == "raise_after_effect": + raise RuntimeError("fault: executor died after the effect") + done = {"status": receipt.status, "output": receipt.output, "detail": dict(receipt.detail), + "usage": dict(receipt.usage)} + create_only(self.dir / "dispatches" / f"{dispatch.dispatch_id}.done.json", canonical_bytes(done)) + self._pause("after_effect", dispatch.operation) + if self.fault == "bad_usage": + return Receipt(receipt.status, receipt.output, receipt.detail, {"gpu_units": float("nan")}) + return receipt + + def _compute(self, dispatch: Dispatch, writer: BoundedWriter) -> Receipt: + op, args, bound = dispatch.operation, dispatch.arguments, dispatch.bound + if op == "inspect_weights": + values = json.loads(Path(bound["tensor"]["path"]).read_text())["values"] + out = {"tensor": bound["tensor"]["id"], "n": len(values), "sum": sum(values), + "min": min(values), "max": max(values)} + return Receipt("ok", json.dumps(out, sort_keys=True), out, {"cpu_units": 1}) + if op == "query_development": + rows = [] + for item in bound["items"]: + score = int(sha256_hex(item["sha256"].encode())[:6], 16) % 100 / 100 + rows.append({"item": item["id"], "score": score}) + return Receipt("ok", json.dumps(rows, sort_keys=True), {"rows": len(rows)}, + {"gpu_units": 0.5 * len(rows), "examples": len(rows)}) + if op == "propose_patch": + text = args["patch"] + reason = _patch_problem(text, bound["tensor"]["id"]) + writer.write(f"{args['name']}.patch.json", text.encode("utf-8")) + status = "invalid" if reason else "ok" + out = f"patch {args['name']} {status}" + (f": {reason}" if reason else "") + return Receipt(status, out, {"reason": reason, "valid": reason is None}, {"cpu_units": 1}) + raise PortError(f"unsupported operation {op}") # pragma: no cover + + # ---- reconciliation (never causes an effect) + def reconcile(self, dispatch: Dispatch) -> ReconcileResult: + done = self.dir / "dispatches" / f"{dispatch.dispatch_id}.done.json" + started = self.dir / "dispatches" / f"{dispatch.dispatch_id}.started" + if done.exists(): + d = json.loads(done.read_text()) + return ReconcileResult("complete", Receipt(d["status"], d["output"], d["detail"], d["usage"])) + if started.exists(): + return ReconcileResult("unknown", note="effect may have started; executor has no completion record") + return ReconcileResult( + "unstarted", + authority={"dispatch_id": dispatch.dispatch_id, + "basis": "executor ledger holds no started marker; marker is fsynced before any effect"}, + ) + + +def _patch_problem(text: str, tensor_id: str) -> str | None: + try: + doc = strict_loads(text) + except ValueError: + return "patch is not strict JSON" + if not isinstance(doc, dict) or doc.get("tensor") != tensor_id: + return "patch must target the bound tensor" + deltas = doc.get("deltas") + if not isinstance(deltas, list) or not deltas or not all( + isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x) for x in deltas + ): + return "deltas must be a non-empty list of finite numbers" + if max(abs(x) for x in deltas) > 0.5: + return "realized delta exceeds the 0.5 limit" + return None + + +# ----------------------------------------------------------------- build + + +def build_ports(ctx: PortContext) -> PortSet: + """Factory for ``--ports synaptic_tuner.experimental.weight_editor.fakes:build_ports``. + + ports-args: script (path), effects_dir (path); optional model/provider override + (simulates adapter drift), pause_at/pause_op (crash injection), fault. + """ + args = ctx.args + try: + script_path, effects = Path(args["script"]), Path(args["effects_dir"]) + except KeyError as exc: + raise PortError(f"fake ports need --ports-arg {exc.args[0]}=...") from exc + blob = script_path.read_bytes() + model = dict(ctx.model) + if "model" in args: + model["model"] = args["model"] + if "provider" in args: + model["provider"] = args["provider"] + return PortSet( + ScriptedAdapter(strict_loads(blob), model, sha256_hex(blob)), + FakeEffectExecutor(effects, args.get("pause_at"), args.get("pause_op"), args.get("fault")), + ) + + +# --------------------------------------------------------------- fixture + +TENSOR_FILES = {"w.layer0": [0.1, -0.2, 0.3], "w.layer1": [0.5, 0.4, -0.3]} +DEV_ITEMS = [f"dev-{i:03d}" for i in range(1, 5)] + + +def _j(obj: Any) -> bytes: + return (json.dumps(obj, indent=2, sort_keys=True) + "\n").encode() + + +def write_fixture(dest: Path, *, script: Mapping[str, Any] | None = None, limits: Mapping[str, float] | None = None, + model: Mapping[str, Any] | None = None, extra_ops: Mapping[str, Any] | None = None) -> dict: + """Create a synthetic capsule + config + script under ``dest`` (must not exist).""" + dest = Path(dest) + dest.mkdir(parents=True) + cap = dest / "capsule" + (cap / "tensors").mkdir(parents=True) + (cap / "dev").mkdir() + objects = [] + + def add(oid: str, kind: str, rel: str, data: bytes) -> None: + (cap / rel).write_bytes(data) + objects.append({"id": oid, "kind": kind, "path": rel, "sha256": sha256_hex(data), "split": "development"}) + + for tid, vals in TENSOR_FILES.items(): + add(tid, "tensor", f"tensors/{tid}.json", _j({"values": vals})) + for did in DEV_ITEMS: + add(did, "dev_item", f"dev/{did}.json", _j({"prompt": f"synthetic development prompt {did}"})) + add("instr-main", "instructions", "instructions.txt", b"Synthetic editor task: propose a small safe edit.\n") + (cap / "manifest.json").write_bytes(_j({"schema": "weight_editor_capsule/v1", "capsule_id": "synthetic-capsule", + "objects": objects})) + operations = { + "inspect_weights": {"description": "bounded numeric read of an admitted tensor", + "arguments": {"tensor": {"type": "ref", "kind": "tensor"}}, "required": ["tensor"], + "cost": {"cpu_units": 1}}, + "query_development": {"description": "run admitted development items", + "arguments": {"items": {"type": "ref_list", "kind": "dev_item", "max_items": 4}}, + "required": ["items"], + "cost": {"gpu_units": {"len_of": "items", "per_item": 0.5}, + "examples": {"len_of": "items", "per_item": 1}}}, + "propose_patch": {"description": "hash-bound patch plus visible justification", "selectable": True, + "arguments": {"name": {"type": "artifact_name"}, + "tensor": {"type": "ref", "kind": "tensor"}, + "patch": {"type": "text", "max_length": 2000}, + "justification": {"type": "text", "max_length": 2000}}, + "required": ["name", "tensor", "patch", "justification"], "cost": {"cpu_units": 1}}, + **(extra_ops or {}), + } + mdl = dict(model or {"provider": "fake", "model": "fake-editor-1", "settings": {"effort": "fixture"}}) + config = { + "schema": "weight_editor_config/v1", "model": mdl, + "capsule": {"manifest": "capsule/manifest.json"}, + "instructions": [{"role": "system", "object": "instr-main"}, + {"role": "user", "text": "Begin discovery."}], + "operations": operations, "output_root": "runs", "read_only_roots": [], + "final_choice": {"allow_no_edit": True}, + "withheld_id_digests": [sha256_hex(HELDOUT_ID.encode())], + } + if limits is not None: + config["resources"] = {"limits": dict(limits)} + (dest / "config.json").write_bytes(_j(config)) + (dest / "script.json").write_bytes(_j(script if script is not None else smoke_script())) + (dest / "effects").mkdir() + return {"root": dest, "config": dest / "config.json", "script": dest / "script.json", + "effects": dest / "effects", "capsule_manifest": cap / "manifest.json", "capsule": cap, + "runs": dest / "runs"} + + +def smoke_script() -> dict: + ok_patch = json.dumps({"tensor": "w.layer0", "deltas": [0.1, -0.1, 0.05]}) + bad_patch = json.dumps({"tensor": "w.layer0", "deltas": [0.1, 9.0, 0.05]}) + return {"turns": [ + {"events": [ + {"type": "session_started", "session_id": "sess-1", "model": "fake-editor-1"}, + {"type": "assistant_message", "text": "I will inspect then query."}, + {"type": "reasoning_summary", "text": "synthetic visible summary"}, + {"type": "tool_request", "operation": "inspect_weights", "arguments": {"tensor": "w.layer0"}}, + {"type": "tool_request", "operation": "query_development", + "arguments": {"items": ["dev-001", "dev-002"]}}, + {"type": "tool_request", "operation": "inspect_weights", "arguments": {"tensor": "../../etc/passwd"}, + "command": "cat /etc/passwd"}, + {"type": "turn_finished", "finish_reason": "tool_use"}, + ]}, + {"events": [ + {"type": "tool_request", "operation": "propose_patch", + "arguments": {"name": "edit-a", "tensor": "w.layer0", "patch": ok_patch, + "justification": "small bounded change"}}, + {"type": "tool_request", "operation": "propose_patch", + "arguments": {"name": "edit-b", "tensor": "w.layer0", "patch": bad_patch, + "justification": "oversized change, expected to be invalid"}}, + {"type": "handoff", "new_session_id": "sess-2", + "capsule": {"summary": "synthetic compaction summary", "continuation_offset": 7}}, + ]}, + {"events": [ + {"type": "final_choice", "choice": "patch", "proposal": "req-0004", + "rationale": "edit-a is the valid bounded proposal"}, + ]}, + ]} diff --git a/synaptic_tuner/experimental/weight_editor/journal.py b/synaptic_tuner/experimental/weight_editor/journal.py new file mode 100644 index 000000000..5a8788f76 --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/journal.py @@ -0,0 +1,156 @@ +"""Append-only, fsynced, hash-chained JSONL log. + +Each line is exactly ``canonical_json(record)``. A record carries ``run_id``, +``seq``, ``prev`` (digest of the previous record), ``type``, ``time``, ``data``, +``linked`` and its own ``digest`` over everything else. Verification fails +closed: a bad line, gap, altered byte or partial tail raises. The only repair +is an explicit audited quarantine of an incomplete final line. +""" + +from __future__ import annotations + +import os +import time +from pathlib import Path +from typing import Any, Callable + +from .canon import canonical_bytes, fsync_dir, sha256_hex, strict_loads +from .errors import JournalCorrupt, PartialTail + + +def genesis_prev(binding_digest: str, log_name: str) -> str: + return sha256_hex(f"{binding_digest}:{log_name}".encode()) + + +def _digest(record: dict) -> str: + body = {k: v for k, v in record.items() if k != "digest"} + return sha256_hex(canonical_bytes(body)) + + +def verify_file(path: Path, run_id: str, genesis: str) -> list[dict]: + """Return all records or raise ``JournalCorrupt`` / ``PartialTail``.""" + try: + blob = Path(path).read_bytes() + except FileNotFoundError: + return [] + if not blob: + return [] + lines = blob.split(b"\n") + partial = lines.pop() # '' if the file ends with a newline + records: list[dict] = [] + prev = genesis + for i, line in enumerate(lines): + where = f"{path.name} line {i + 1}" + try: + rec = strict_loads(line) + except (ValueError, UnicodeDecodeError) as exc: + raise JournalCorrupt(f"{where}: not valid JSON", line=i + 1) from exc + if not isinstance(rec, dict) or canonical_bytes(rec) != line: + raise JournalCorrupt(f"{where}: not canonical record bytes", line=i + 1) + if rec.get("run_id") != run_id: + raise JournalCorrupt(f"{where}: run_id mismatch", line=i + 1) + if rec.get("seq") != i + 1: + raise JournalCorrupt(f"{where}: sequence gap/reorder", line=i + 1) + if rec.get("prev") != prev: + raise JournalCorrupt(f"{where}: previous-digest link broken", line=i + 1) + if rec.get("digest") != _digest(rec): + raise JournalCorrupt(f"{where}: digest mismatch (record altered)", line=i + 1) + prev = rec["digest"] + records.append(rec) + if partial: + raise PartialTail( + f"{path.name}: incomplete final line ({len(partial)} bytes) after {len(records)} valid records", + valid_records=len(records), + valid_bytes=len(blob) - len(partial), + partial_bytes=len(partial), + ) + return records + + +class HashChainLog: + def __init__( + self, + path: Path, + run_id: str, + genesis: str, + clock: Callable[[], float] = time.time, + _allow_missing: bool = True, + ): + self.path = Path(path) + self.run_id = run_id + self.genesis = genesis + self._clock = clock + self.records: list[dict] = verify_file(self.path, run_id, genesis) + new = not self.path.exists() + self._fd = os.open(str(self.path), os.O_CREAT | os.O_APPEND | os.O_WRONLY, 0o600) + if new: + fsync_dir(self.path.parent) + + @property + def head(self) -> str: + return self.records[-1]["digest"] if self.records else self.genesis + + @property + def next_seq(self) -> int: + return len(self.records) + 1 + + def append(self, rtype: str, data: dict, linked: dict | None = None) -> dict: + rec: dict[str, Any] = { + "run_id": self.run_id, + "seq": self.next_seq, + "prev": self.head, + "type": rtype, + "time": round(self._clock(), 6), + "data": data, + "linked": linked or {}, + } + rec["digest"] = _digest(rec) + line = canonical_bytes(rec) + b"\n" + view = memoryview(line) + while view: + n = os.write(self._fd, view) + view = view[n:] + os.fsync(self._fd) + self.records.append(rec) + return rec + + def close(self) -> None: + if self._fd is not None: + os.close(self._fd) + self._fd = None + + +def quarantine_partial_tail(path: Path, quarantine_dir: Path, run_id: str, genesis: str) -> dict: + """Move an incomplete final line aside (never deleted) and return its audit facts. + + Preconditions are re-checked: every complete line must verify and the + remainder must lack a trailing newline. + """ + try: + verify_file(path, run_id, genesis) + raise JournalCorrupt(f"{path.name} has no partial tail to recover") + except PartialTail as exc: + keep = exc.details["valid_bytes"] + blob = path.read_bytes() + tail = blob[keep:] + quarantine_dir.mkdir(parents=True, exist_ok=True) + n = len(list(quarantine_dir.iterdir())) + 1 + qpath = quarantine_dir / f"{path.name}.{n:03d}.partial" + fd = os.open(str(qpath), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + try: + os.write(fd, tail) + os.fsync(fd) + finally: + os.close(fd) + fsync_dir(quarantine_dir) + with open(path, "r+b") as fh: + fh.truncate(keep) + fh.flush() + os.fsync(fh.fileno()) + return { + "log": path.name, + "quarantined_file": str(qpath.relative_to(quarantine_dir.parent)), + "quarantined_sha256": sha256_hex(tail), + "quarantined_bytes": len(tail), + "valid_prefix_bytes": keep, + } diff --git a/synaptic_tuner/experimental/weight_editor/ledger.py b/synaptic_tuner/experimental/weight_editor/ledger.py new file mode 100644 index 000000000..19e6b002d --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/ledger.py @@ -0,0 +1,70 @@ +"""Conservative resource ledger folded from journal entries (never reset).""" + +from __future__ import annotations + +from typing import Any, Mapping + +from .canon import is_finite_nonneg +from .errors import JournalCorrupt + + +def clean_amount(value: Any, what: str = "amount") -> float: + if not is_finite_nonneg(value): + raise ValueError(f"{what} must be a finite non-negative number, got {value!r}") + return value + + +class Ledger: + """reserved + committed is the charge. Release only on proven no-effect.""" + + def __init__(self, limits: Mapping[str, float] | None = None): + self.limits = dict(limits or {}) + self.committed: dict[str, float] = {} + self.reserved: dict[str, dict[str, float]] = {} # ref -> resource -> amount + + def apply(self, entry: Mapping[str, Any]) -> None: + op, ref, res = entry.get("op"), entry.get("ref"), entry.get("resource") + try: + amount = clean_amount(entry.get("amount")) + except ValueError as exc: + raise JournalCorrupt(f"ledger entry invalid: {exc}") from exc + if op == "reserve": + slot = self.reserved.setdefault(ref, {}) + slot[res] = slot.get(res, 0) + amount + elif op == "release": + slot = self.reserved.get(ref, {}) + slot[res] = max(0, slot.get(res, 0) - amount) + elif op == "commit": + self.committed[res] = self.committed.get(res, 0) + amount + else: + raise JournalCorrupt(f"unknown ledger op {op!r}") + + def outstanding(self, resource: str) -> float: + return sum(slot.get(resource, 0) for slot in self.reserved.values()) + + def charged(self, resource: str) -> float: + return self.committed.get(resource, 0) + self.outstanding(resource) + + def exceeded_by(self, cost: Mapping[str, float]) -> list[dict]: + out = [] + for res, amount in cost.items(): + limit = self.limits.get(res) + if limit is not None and self.charged(res) + amount > limit: + out.append({"resource": res, "limit": limit, "charged": self.charged(res), "requested": amount}) + return out + + def exhausted(self, resource: str, amount: float = 1) -> bool: + limit = self.limits.get(resource) + return limit is not None and self.charged(resource) + amount > limit + + def snapshot(self) -> dict: + names = sorted(set(self.committed) | {r for s in self.reserved.values() for r in s} | set(self.limits)) + return { + n: { + "limit": self.limits.get(n), + "committed": self.committed.get(n, 0), + "reserved_outstanding": self.outstanding(n), + "charged": self.charged(n), + } + for n in names + } diff --git a/synaptic_tuner/experimental/weight_editor/ports.py b/synaptic_tuner/experimental/weight_editor/ports.py new file mode 100644 index 000000000..7e5d05638 --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/ports.py @@ -0,0 +1,249 @@ +"""Trusted ports: ModelAdapter and Executor. + +Both are supplied by the host operator (CLI ``--ports module:factory`` or the +Python API). They are never selected by a model request or by the run config. +The broker, not the port, owns admission, budgets, write-ahead and the journal. +""" + +from __future__ import annotations + +import importlib +import inspect +import os +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Iterator, Mapping + +from .canon import sha256_hex +from .errors import PortError, WriteBoundaryViolation +from .config import ID_RE + +# --------------------------------------------------------------- data types + + +@dataclass(frozen=True) +class TransportEvent: + """Exact bytes on a named client stream; never a synthetic provider event. + + ``provider`` is parsed by the adapter. Client input and diagnostics are + retained for audit without granting them request or final-choice authority. + """ + + data: bytes + channel: str = "provider" + + +@dataclass(frozen=True) +class TurnInput: + run_id: str + turn_id: str + turn_index: int + session_id: str | None + messages: tuple[Mapping[str, str], ...] # exact model-visible messages for this turn + context_digest: str # chain over every message ever delivered + resumed: bool # True when the previous turn was interrupted/failed + + +EVENT_KINDS = ( + "message", + "reasoning_summary", + "request", + "final_choice", + "session", + "usage", + "finish", + "handoff", + "truncation", + "unknown", +) + + +@dataclass(frozen=True) +class Receipt: + status: str # "ok" is a valid, selectable outcome; anything else is recorded but not selectable + output: str # text shown to the model verbatim + detail: Mapping[str, Any] = field(default_factory=dict) + usage: Mapping[str, Any] = field(default_factory=dict) # actual resource use, caller-defined names + + +@dataclass(frozen=True) +class Dispatch: + dispatch_id: str + run_id: str + request_id: str + operation: str + arguments: Mapping[str, Any] # validated model values + bound: Mapping[str, Any] # arg name -> {"id","kind","sha256","path"} resolved by the broker + attempt: int + + +@dataclass(frozen=True) +class ReconcileResult: + status: str # "complete" | "unstarted" | "unknown" + receipt: Receipt | None = None + authority: Mapping[str, Any] | None = None # for "unstarted": {"dispatch_id","basis"} + note: str = "" + + +# -------------------------------------------------------------------- ports + + +class ModelAdapter(ABC): + @abstractmethod + def identity(self) -> dict: + """Requested model identity and declared capabilities. + + Must contain ``provider``, ``model``, ``settings`` equal to the config's + model block. May contain ``client_version`` and ``capabilities`` + (``raw_events`` must be true; ``captures_hidden_reasoning`` must not be). + """ + + @abstractmethod + def run_turn(self, turn: TurnInput) -> Iterator[bytes | TransportEvent]: + """Yield exact provider bytes, optionally with named client streams. + + Channels are ordered as observed by the adapter; no total ordering + between independent operating-system pipes is claimed. + """ + + @abstractmethod + def parse_event(self, raw: bytes) -> dict: + """Normalize one raw event to ``{"kind": , ...}``. + + Raise or return an unrecognized kind for anything unsupported; the + broker retains the raw bytes and marks capture incomplete. + """ + + def close(self) -> None: # pragma: no cover - optional + return None + + +class BoundedWriter: + """Create-only artifact writer confined to one dispatch's namespace. + + This is a cooperative host API, not OS isolation: an executor that calls + ``open`` itself is outside this guarantee. + """ + + def __init__(self, root: Path, read_only_roots: tuple[Path, ...]): + self._root = root + self._ro = read_only_roots + self.written: list[dict] = [] + + @property + def root(self) -> Path: + return self._root + + def write(self, name: str, data: bytes) -> dict: + if not isinstance(name, str) or not ID_RE.match(name) or name in (".", ".."): + raise WriteBoundaryViolation(f"artifact name {name!r} is not a bare artifact name") + if not isinstance(data, (bytes, bytearray)): + raise WriteBoundaryViolation("artifact data must be bytes") + self._root.mkdir(parents=True, exist_ok=True) + resolved_root = self._root.resolve() + target = resolved_root / name + if target.parent != resolved_root or any(resolved_root.is_relative_to(r) for r in self._ro): + raise WriteBoundaryViolation("artifact target outside the run artifact namespace") + fd = os.open(str(target), os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600) + try: + view = memoryview(data) + while view: + n = os.write(fd, view) + if n <= 0: + raise OSError("artifact write made no progress") + view = view[n:] + os.fsync(fd) + finally: + os.close(fd) + rec = {"name": name, "sha256": sha256_hex(bytes(data)), "size": len(data)} + self.written.append(rec) + return rec + + +class Executor(ABC): + @abstractmethod + def identity(self) -> dict: ... + + @abstractmethod + def supported_operations(self) -> frozenset[str]: + """Operations this executor implements; a configured op outside it is rejected.""" + + @abstractmethod + def validate(self, operation: str, arguments: Mapping[str, Any], bound: Mapping[str, Any]) -> None: + """Side-effect-free check. Raise ``ExecutorRejection`` to deny.""" + + @abstractmethod + def execute(self, dispatch: Dispatch, writer: BoundedWriter) -> Receipt: + """Perform the effect. Must be keyed by ``dispatch.dispatch_id``.""" + + @abstractmethod + def reconcile(self, dispatch: Dispatch) -> ReconcileResult: + """Report what happened to ``dispatch_id`` without causing a new effect.""" + + def close(self) -> None: # pragma: no cover - optional + return None + + +@dataclass +class PortSet: + adapter: ModelAdapter + executor: Executor + + +@dataclass(frozen=True) +class PortContext: + args: Mapping[str, str] + model: Mapping[str, Any] # the config's requested model block (no fallback is derived from it) + + +# ----------------------------------------------------------------- identity + + +def source_package(path: str | None) -> dict: + if path is None or not Path(path).is_file(): + raise PortError("port source must be an inspectable Python package", code="unbound_port_source") + root = Path(path).resolve().parent + if not (root / "__init__.py").is_file(): + raise PortError("plain-module ports require packaging before use", code="unbound_port_source") + while (root.parent / "__init__.py").is_file(): + root = root.parent + sources = {} + for file in sorted(root.rglob("*.py")): + if file.is_symlink(): + raise PortError("port source tree contains a symlink") + sources[str(file.relative_to(root))] = sha256_hex(file.read_bytes()) + return sources + + +def describe_port(obj: Any) -> dict: + cls = type(obj) + try: + path = inspect.getsourcefile(cls) + except (OSError, TypeError) as exc: + raise PortError("port source cannot be inspected", code="unbound_port_source") from exc + package_sources = source_package(path) + return { + "class": f"{cls.__module__}.{cls.__qualname__}", + "source_sha256": sha256_hex(Path(path).read_bytes()), + "package_sources": package_sources, + "source_scope": "Python package tree; external binaries, dependencies and resources need explicit pins", + "declared": obj.identity(), + } + + +def load_ports(spec: str, ctx: PortContext) -> PortSet: + """Operator-trusted factory loading. ``spec`` is ``module:attribute``.""" + if not isinstance(spec, str) or spec.count(":") != 1: + raise PortError("ports spec must be module:factory") + mod_name, attr = spec.split(":") + try: + factory = getattr(importlib.import_module(mod_name), attr) + except (ImportError, AttributeError) as exc: + raise PortError(f"cannot load ports factory {spec}: {exc}") from exc + ports = factory(ctx) + if not isinstance(ports, PortSet) or not isinstance(ports.adapter, ModelAdapter) or not isinstance( + ports.executor, Executor + ): + raise PortError("ports factory must return PortSet(ModelAdapter, Executor)") + return ports diff --git a/synaptic_tuner/experimental/weight_editor/replay.py b/synaptic_tuner/experimental/weight_editor/replay.py new file mode 100644 index 000000000..5c9ffe508 --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/replay.py @@ -0,0 +1,280 @@ +"""Independent verification and readable replay of a retained run. + +Reads only the run directory (no ports, no original config, no model). Replay +reconstructs what was observed; it never re-asks a nondeterministic model. +""" + +from __future__ import annotations + +import base64 +import re +from pathlib import Path + +from .canon import canonical_bytes, load_strict_file, sha256_file, sha256_hex +from .errors import EditorError +from .journal import genesis_prev, verify_file +from .state import RunState + + +def load_verified(run_dir: Path) -> tuple[dict, list[dict], list[dict]]: + from .broker import cross_check, read_manifest + + run_dir = Path(run_dir) + if not (run_dir / "manifest.json").is_file(): + raise EditorError(f"{run_dir} is not a retained editor run", code="run_not_found") + manifest = read_manifest(run_dir) + for relpath, key in (("config.json", "config_sha256"), + ("capsule/manifest.json", "capsule_manifest_sha256")): + try: + matches = sha256_file(run_dir / relpath) == manifest["binding"][key] + except OSError: + matches = False + if not matches: + raise EditorError(f"retained input differs from binding: {relpath}", code="retained_input_mismatch") + bd, rid = manifest["binding_digest"], manifest["run_id"] + journal = verify_file(run_dir / "journal" / "events.jsonl", rid, genesis_prev(bd, "journal")) + raw = verify_file(run_dir / "provider" / "events.jsonl", rid, genesis_prev(bd, "provider")) + cross_check(run_dir, journal, raw) + return manifest, journal, raw + + +def _limits(run_dir: Path) -> dict: + cfg, _ = load_strict_file(run_dir / "config.json", what="retained config") + return cfg.get("resources", {}).get("limits", {}) + + +def verify_run(run_dir: Path, *, anchor_file: Path | None = None) -> dict: + """Fail-closed verification. Returns ``{"ok": bool, "problems": [...], ...}``.""" + run_dir = Path(run_dir) + problems: list[dict] = [] + try: + manifest, journal, raw = load_verified(run_dir) + except EditorError as exc: + return {"ok": False, "problems": [{"code": exc.code, "message": str(exc)}]} + state = RunState(_limits(run_dir)) + for rec in journal: + state.apply(rec) + anchor_checked = False + if anchor_file is not None: + try: + if Path(anchor_file).resolve().is_relative_to(run_dir.resolve().parent): + raise EditorError("freeze anchor is inside the run output tree", code="anchor_location") + anchor, _ = load_strict_file(Path(anchor_file), what="external freeze anchor") + expected = {"schema": "weight_editor_freeze_anchor/v1", "run_id": manifest["run_id"], + "binding_digest": manifest["binding_digest"], + "final_selection_sha256": sha256_file(run_dir / "final_selection.json"), + "terminal_manifest_sha256": sha256_file(run_dir / "terminal_manifest.json"), + "raw_head": raw[-1]["digest"] if raw else None} + if (set(anchor) != set(expected) | {"journal_head"} or + any(anchor.get(k) != v for k, v in expected.items()) or + anchor.get("journal_head") not in {r["digest"] for r in journal}): + problems.append({"code": "external_anchor_mismatch"}) + else: + anchor_checked = True + except (EditorError, OSError, ValueError) as exc: + problems.append({"code": "anchor_location" if isinstance(exc, EditorError) and + exc.code == "anchor_location" else "external_anchor_unreadable"}) + for rec in journal: + if rec["type"] != "dispatch_result": + continue + d = rec["data"] + for a in d["artifacts"]: + f = run_dir / a["relpath"] + if not f.is_file() or sha256_file(f) != a["sha256"]: + problems.append({"code": "artifact_mismatch", "artifact": a["relpath"]}) + rf = run_dir / "requests" / d["request_id"] / "receipt.json" + try: + doc, blob = load_strict_file(rf, what="receipt") + if blob != canonical_bytes(doc) + b"\n" or sha256_hex(canonical_bytes(doc)) != d["receipt_sha256"]: + problems.append({"code": "receipt_mismatch", "request": d["request_id"]}) + except EditorError: + problems.append({"code": "receipt_missing", "request": d["request_id"]}) + if (run_dir / "terminal_manifest.json").is_file() and not state.terminal: + problems.append({"code": "journal_truncated_before_terminal", + "message": "terminal manifest exists but the journal has no terminal record"}) + if state.frozen: + fs = run_dir / "final_selection.json" + if not fs.is_file() or sha256_file(fs) != state.frozen["final_selection_sha256"]: + problems.append({"code": "final_selection_mismatch"}) + if state.terminal: + tm = run_dir / "terminal_manifest.json" + if not tm.is_file() or sha256_file(tm) != state.terminal["terminal_manifest_sha256"]: + problems.append({"code": "terminal_manifest_mismatch"}) + else: + term, _ = load_strict_file(tm, what="terminal manifest") + if term["frozen_record_digest"] != state.frozen_record_digest: + problems.append({"code": "terminal_freeze_binding_mismatch"}) + am = run_dir / "artifacts" / "manifest.json" + if not am.is_file() or sha256_file(am) != term["artifacts_manifest_sha256"]: + problems.append({"code": "artifacts_manifest_mismatch"}) + recorded = {a["relpath"] for a in state.artifacts} + unrecorded = [] + adir = run_dir / "artifacts" + for f in sorted(adir.rglob("*")) if adir.is_dir() else []: + if not f.is_file() and not f.is_symlink(): + continue + rel = str(f.relative_to(run_dir)) + if rel not in recorded and rel != "artifacts/manifest.json": + unrecorded.append(rel) + if state.status == "complete" and unrecorded: + problems.append({"code": "unrecorded_artifacts", "files": unrecorded}) + return { + "ok": not problems, + "problems": problems, + "run_id": manifest["run_id"], + "status": "complete" if state.status == "complete" else "incomplete", + "phase": state.phase, + "halt": state.halt, + "journal_records": len(journal), + "raw_records": len(raw), + "journal_head": journal[-1]["digest"] if journal else None, + "raw_head": raw[-1]["digest"] if raw else None, + "unknown_events": state.unknown_events, + "capture_incomplete": state.capture_incomplete, + "capture_qualification": {"qualified": not state.capture_incomplete and + not (state.completed_turns - state.model_verified_turns), + "missing_model_turns": sorted(state.completed_turns - state.model_verified_turns)}, + "external_anchor_checked": anchor_checked, + "integrity_scope": "external freeze anchor" if anchor_checked else "internal consistency; no independent authenticity anchor", + "unrecorded_artifact_files": unrecorded, + "unresolved_dispatches": sorted( + r["dispatch_id"] for r in state.requests.values() if r["status"] in ("intent", "unknown") + ), + "budget": state.ledger.snapshot(), + } + + +# ------------------------------------------------------------- markdown + + +def fence(text: str, lang: str = "") -> str: + longest = max((len(m) for m in re.findall(r"`+", text)), default=0) + bar = "`" * max(3, longest + 1) + return f"{bar}{lang}\n{text}\n{bar}" + + +def _raw_text(rec: dict) -> str: + blob = base64.b64decode(rec["data"]["raw_b64"]) + try: + return blob.decode("utf-8") + except UnicodeDecodeError: + return "[non-UTF-8 bytes, base64] " + rec["data"]["raw_b64"] + + +def render_markdown(run_dir: Path, journal: list[dict], raw: list[dict]) -> str: + run_dir = Path(run_dir) + manifest, _ = load_strict_file(run_dir / "manifest.json", what="run manifest") + raw_by_seq = {r["seq"]: r for r in raw} + state = RunState(_limits(run_dir)) + out: list[str] = [] + w = out.append + b = manifest["binding"] + w(f"# Weight editor transcript `{manifest['run_id']}`") + w("") + w("Derived, read-only view of `journal/events.jsonl` and `provider/events.jsonl`. " + "Raw provider events and named client streams are shown as retained; non-UTF-8 bytes use base64. " + "Independent pipe ordering is observation order. Hidden reasoning is not captured or claimed; " + "only provider-exposed events and summaries appear. Replay reconstructs observation, it does not re-ask the model.") + w("") + w(f"- Requested model: `{canonical_bytes(b['model']).decode()}`") + w(f"- Binding digest: `{manifest['binding_digest']}`") + w(f"- Config sha256: `{b['config_sha256']}`; capsule manifest sha256: `{b['capsule_manifest_sha256']}`") + w(f"- Adapter: `{b['adapter']['class']}`; executor: `{b['executor']['class']}`") + w("") + for rec in journal: + state.apply(rec) + d, t = rec["data"], rec["type"] + tag = f"journal #{rec['seq']}" + if t == "turn_start": + w(f"## Turn {d['turn_index']} `{d['turn_id']}` (session `{d['session_id']}`, {tag})") + w(f"Context digest `{d['context_digest']}`; resumed after interrupted/failed turn: {d['resumed']}") + w("") + w("### Model-visible input") + for m in d["messages"]: + w(f"**{m['role']}**") + w(fence(m["content"])) + elif t == "provider_event": + r = raw_by_seq[d["raw"]["seq"]] + mark = "" if d["capture"]["complete"] else " **UNKNOWN/UNPARSED EVENT, capture incomplete**" + rec_note = " (normalized after crash recovery)" if d.get("recovered_from_raw") else "" + channel = r["data"].get("channel", "provider") + w(f"- Stream `{channel}`, event `{d['kind']}` — raw #{d['raw']['seq']} sha256 `{d['raw']['sha256']}`{mark}{rec_note}") + w(fence(_raw_text(r))) + elif t == "request_received": + w(f"### Request `{d['request_id']}` ({tag}, raw #{d['raw']['seq']})") + p = d["payload"] + w(f"Operation: `{p.get('operation')}`" if isinstance(p, dict) else "Malformed request payload") + args = p.get("arguments", {}) if isinstance(p, dict) else {} + for k, v in (args.items() if isinstance(args, dict) else []): + if isinstance(v, str): + w(f"Argument `{k}` (exact text):") + w(fence(v)) + else: + w(f"Argument `{k}`: `{canonical_bytes(v).decode()}`") + extras = {k: v for k, v in p.items() if k not in ("operation", "arguments")} if isinstance(p, dict) else {} + if extras: + w(f"Other request fields (carry no authority): `{canonical_bytes(extras).decode()}`") + elif t == "request_denied": + w(f"**Denied** `{d['request_id']}` reason `{d['reason']}` — {d['detail']}") + w("Model saw:") + w(fence(d["message"]["content"])) + elif t == "request_admitted": + w(f"Admitted `{d['request_id']}` → dispatch `{d['dispatch_id']}`; reserved cost `{canonical_bytes(d['cost']).decode()}`; " + f"bound objects `{canonical_bytes(d['bound']).decode()}`") + elif t == "dispatch_intent": + w(f"Write-ahead dispatch intent `{d['dispatch_id']}` attempt {d['attempt']} ({d['basis']}, {tag})") + elif t == "dispatch_error": + w(f"**Dispatch error** `{d['dispatch_id']}` outcome `{d['outcome']}` category `{d['category']}`") + elif t == "reconcile_attempt": + w(f"Reconciling `{d['dispatch_id']}` by dispatch id (no re-execution)") + elif t == "reconcile_result": + w(f"Reconcile result for `{d['dispatch_id']}`: **{d['status']}**" + + (f", authority `{canonical_bytes(d['authority']).decode()}`" if d.get("authority") else "") + + (f" — {d['note']}" if d.get("note") else "")) + elif t == "dispatch_result": + rid = d["request_id"] + w(f"Result `{rid}` dispatch `{d['dispatch_id']}` via {d['via']}; receipt status **{d['receipt']['status']}**; " + f"charge `{canonical_bytes(d['charge']).decode()}`" + + (f"; anomalies {d['anomalies']}" if d["anomalies"] else "")) + w(f"Receipt file: [requests/{rid}/receipt.json](requests/{rid}/receipt.json) sha256 `{d['receipt_sha256']}`") + for a in d["artifacts"]: + w(f"- Artifact [{a['relpath']}]({a['relpath']}) sha256 `{a['sha256']}` ({a['size']} bytes)") + w("Tool output exactly as shown to the model:") + w(fence(d["message"]["content"])) + elif t == "handoff": + w(f"### {d['kind'].title()} `{d['from_session']}` → `{d['to_session']}` capsule sha256 `{d['capsule_sha256']}`") + w(fence(canonical_bytes(d["capsule"]).decode())) + elif t == "adapter_error": + w(f"**Adapter error** {d['classification']} (`{d['category']}`) in `{d['turn_id']}`") + elif t == "turn_end": + w(f"Turn `{d['turn_id']}` ended: {d['status']}" + (f" ({d['reason']})" if d.get("reason") else "")) + elif t == "final_choice_received": + w(f"### Final choice received `{d['item_id']}` (raw #{d['raw']['seq']})") + w(fence(canonical_bytes(d["payload"]).decode())) + elif t == "final_choice_denied": + w(f"**Final choice denied** `{d['item_id']}`: {d['reason']} — {d['detail']}") + elif t == "final_patch_frozen": + w(f"## Final choice frozen `{d['choice']}` proposal `{d['proposal_request_id']}`") + w(f"[final_selection.json](final_selection.json) sha256 `{d['final_selection_sha256']}`; journal head before freeze `{d['journal_head']}`; raw head `{d['raw_head']}`") + elif t == "run_halted": + w(f"**Run halted (incomplete): `{d['code']}`** — {d['detail']}") + elif t == "resume_started": + w(f"Resume started (prior status `{d['prior_status']}`)") + elif t == "resume_refused": + w(f"**Resume refused**: `{d['reason']}` {canonical_bytes({k: v for k, v in d.items() if k != 'reason'}).decode()}") + elif t == "tail_recovery": + w(f"**Audited tail recovery** `{d['log']}`: {d['quarantined_bytes']} bytes quarantined at `{d['quarantined_file']}` sha256 `{d['quarantined_sha256']}`") + elif t == "editor_terminal": + w(f"## Terminal manifest bound [terminal_manifest.json](terminal_manifest.json) sha256 `{d['terminal_manifest_sha256']}`") + elif t == "phase_advanced": + w(f"Phase advanced {d['from']} → {d['to']} (reference `{d['reference']}`)") + elif t in ("run_registered", "state_transition"): + w(f"- {t.replace('_', ' ')} ({tag})") + w("") + w("## Budget ledger") + for res, row in state.ledger.snapshot().items(): + w(f"- `{res}`: limit {row['limit']}, committed {row['committed']}, reserved outstanding {row['reserved_outstanding']}") + w("") + w(f"Journal head `{journal[-1]['digest'] if journal else None}`; raw head `{raw[-1]['digest'] if raw else None}`; " + f"unknown events {state.unknown_events}; capture incomplete: {state.capture_incomplete}") + return "\n".join(out) + "\n" diff --git a/synaptic_tuner/experimental/weight_editor/state.py b/synaptic_tuner/experimental/weight_editor/state.py new file mode 100644 index 000000000..4a21cfcd3 --- /dev/null +++ b/synaptic_tuner/experimental/weight_editor/state.py @@ -0,0 +1,226 @@ +"""Run state folded purely from journal records. + +Nothing here is trusted from memory: after a crash the broker rebuilds this +object by replaying the verified journal, so budgets and request dispositions +can never reset on resume. +""" + +from __future__ import annotations + +from typing import Mapping + +from .canon import canonical_bytes, sha256_hex +from .ledger import Ledger + +PHASES = ("registered", "discovery", "final_patch_frozen", "independent_evaluation", "closed") +TERMINAL_REQUEST = ("denied", "done", "rejected") +CONTEXT_GENESIS = "0" * 64 + + +class RunState: + def __init__(self, limits: Mapping[str, float]): + self.phase = "registered" + self.status = "running" # running | halted | complete + self.halt: dict | None = None + self.session_id: str | None = None + self.turn_count = 0 + self.open_turn: str | None = None + self.last_turn_clean = True + self.outbox: list[dict] = [] + self.context_digest = CONTEXT_GENESIS + self.requests: dict[str, dict] = {} + self.finals: dict[str, dict] = {} + self.order: list[tuple[str, str]] = [] # arrival order of ("request"|"final", id) + self.ledger = Ledger(limits) + self.artifact_names: set[str] = set() + self.artifacts: list[dict] = [] + self.results: list[dict] = [] # ordered dispatch results (evidence) + self.capture_incomplete = False + self.unqualified_turns: set[str] = set() + self.unknown_events = 0 + self.returned_models: list[str] = [] + self.model_verified_turns: set[str] = set() + self.completed_turns: set[str] = set() + self.delivered_receipts: set[str] = set() + self.needs_bootstrap = False + self.turn_messages: list[dict] = [] + self.turn_receipts: set[str] = set() + self.raw_referenced = 0 + self.frozen: dict | None = None + self.frozen_record_digest: str | None = None + self.terminal: dict | None = None + self.resume_count = 0 + self.handoffs: list[dict] = [] + self.evaluation_reference: str | None = None + self.registered: dict | None = None + self.records_seen = 0 + + # ------------------------------------------------------------ helpers + def next_request_id(self) -> str: + return f"req-{len(self.requests) + 1:04d}" + + def next_final_id(self) -> str: + return f"fc-{len(self.finals) + 1:04d}" + + def pending(self) -> tuple[str, dict] | None: + for kind, iid in self.order: + if kind == "request": + if self.requests[iid]["status"] not in TERMINAL_REQUEST: + return kind, self.requests[iid] + elif self.finals[iid]["status"] == "received": + return kind, self.finals[iid] + return None + + def push_message(self, msg: Mapping[str, str]) -> None: + self.outbox.append(dict(msg)) + + # --------------------------------------------------------------- fold + def apply(self, rec: dict) -> None: + self.records_seen += 1 + d = rec["data"] + for entry in d.get("ledger", ()): # budget entries ride on the record that causes them + self.ledger.apply(entry) + fn = getattr(self, "_on_" + rec["type"], None) + if fn: + fn(rec, d) + + def _on_run_registered(self, rec, d): + self.registered = d + + def _on_state_transition(self, rec, d): + self.phase = d["to"] + + def _on_phase_advanced(self, rec, d): + self.phase = d["to"] + self.evaluation_reference = d.get("reference") + + def _on_turn_start(self, rec, d): + self.turn_messages = list(d["messages"]) + self.turn_receipts = set() + for rid, req in self.requests.items(): + if req.get("message") in d["messages"]: + self.turn_receipts.add(rid) + self.turn_count += 1 + self.open_turn = d["turn_id"] + self.outbox = [] + self.context_digest = d["context_digest"] + self.needs_bootstrap = False + if d.get("session_id"): + self.session_id = d["session_id"] + + def _on_turn_end(self, rec, d): + self.open_turn = None + self.last_turn_clean = d["status"] == "complete" + if self.last_turn_clean: + self.completed_turns.add(d["turn_id"]) + self.delivered_receipts.update(self.turn_receipts) + else: + self.capture_incomplete = True + self.needs_bootstrap = True + self.outbox = [m for m in self.turn_messages if m["role"] == "tool"] + self.outbox + + def _on_model_identity_verified(self, rec, d): + self.model_verified_turns.add(d["turn_id"]) + self.returned_models.append(d["model"]) + + def _on_provider_event(self, rec, d): + self.raw_referenced = max(self.raw_referenced, d["raw"]["seq"]) + kind = d["kind"] + if not d["capture"]["complete"]: + self.capture_incomplete = True + self.unqualified_turns.add(d["turn_id"]) + if kind == "unknown": + self.unknown_events += 1 + if kind == "truncation": + self.capture_incomplete = True + self.unqualified_turns.add(d["turn_id"]) + if kind == "session": + p = d["payload"] + if isinstance(p.get("session_id"), str): + self.session_id = p["session_id"] + + def _on_handoff(self, rec, d): + self.handoffs.append(d) + if d.get("to_session"): + self.session_id = d["to_session"] + self.push_message(d["message"]) + self.needs_bootstrap = True + + def _on_request_received(self, rec, d): + self.requests[d["request_id"]] = { + "id": d["request_id"], "status": "received", "payload": d["payload"], + "turn_id": d["turn_id"], "attempts": 0, "seq": rec["seq"], + } + self.order.append(("request", d["request_id"])) + + def _on_request_denied(self, rec, d): + self.requests[d["request_id"]]["status"] = "denied" + self.requests[d["request_id"]]["denial"] = d["reason"] + self.push_message(d["message"]) + + def _on_request_admitted(self, rec, d): + r = self.requests[d["request_id"]] + r.update(status="admitted", operation=d["operation"], arguments=d["arguments"], + bound=d["bound"], dispatch_id=d["dispatch_id"], cost=d["cost"]) + self.artifact_names.update(d.get("artifact_names", ())) + + def _on_dispatch_intent(self, rec, d): + r = self.requests[d["request_id"]] + r["status"] = "intent" + r["attempts"] = d["attempt"] + + def _on_dispatch_error(self, rec, d): + r = self.requests[d["request_id"]] + if d["outcome"] == "not_started": + r["status"] = "rejected" + self.push_message(d["message"]) + else: + r["status"] = "unknown" + + def _on_dispatch_result(self, rec, d): + r = self.requests[d["request_id"]] + r["status"] = "done" + r["receipt"] = d["receipt"] + r["receipt_sha256"] = d["receipt_sha256"] + r["artifacts"] = d["artifacts"] + r["message"] = d["message"] + self.results.append({"request_id": d["request_id"], "dispatch_id": d["dispatch_id"], + "receipt_sha256": d["receipt_sha256"]}) + for a in d["artifacts"]: + self.artifacts.append({**a, "dispatch_id": d["dispatch_id"], "request_id": d["request_id"]}) + self.push_message(d["message"]) + + def _on_final_choice_received(self, rec, d): + self.finals[d["item_id"]] = {"id": d["item_id"], "status": "received", "payload": d["payload"], + "turn_id": d["turn_id"]} + self.order.append(("final", d["item_id"])) + + def _on_final_choice_denied(self, rec, d): + self.finals[d["item_id"]]["status"] = "denied" + self.push_message(d["message"]) + + def _on_final_patch_frozen(self, rec, d): + self.finals[d["item_id"]]["status"] = "accepted" + self.phase = "final_patch_frozen" + self.frozen = d + self.frozen_record_digest = rec["digest"] + + def _on_run_halted(self, rec, d): + self.status = "halted" + self.halt = d + + def _on_resume_started(self, rec, d): + self.resume_count += 1 + self.status = "running" + self.halt = None + + def _on_editor_terminal(self, rec, d): + self.terminal = d + self.status = "complete" + + def _on_broker_notice(self, rec, d): + self.push_message(d["message"]) + + +def chain_context(prev: str, messages: list[Mapping[str, str]]) -> str: + return sha256_hex(prev.encode() + canonical_bytes(messages)) diff --git a/tests/batch/test_hf_schema.py b/tests/batch/test_hf_schema.py new file mode 100644 index 000000000..e2f1db344 --- /dev/null +++ b/tests/batch/test_hf_schema.py @@ -0,0 +1,71 @@ +"""Real CPU grammar decoding and generic conditional-model dispatch.""" +import json +import sys + +import pytest + +torch = pytest.importorskip("torch") +from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast +from tokenizers import Tokenizer, models, pre_tokenizers, decoders + +from tuner.batch.engines.hf_batched import HFBatchedGenerateEngine +from tuner.batch.engines.base import GenerateItem +from shared.utilities.text_model import load_text_generation_model + + +def test_missing_grammar_dependency_refuses_before_model_load(monkeypatch): + monkeypatch.setitem(sys.modules, "xgrammar", None) + with pytest.raises(RuntimeError, match="optional xgrammar"): + HFBatchedGenerateEngine("must-not-be-loaded", json_schema={"type": "object"}) + + +def test_real_schema_decoding_resets_matcher_between_batches_and_calls(): + pytest.importorskip("xgrammar") + vocab = {char: index for index, char in enumerate(sorted(pre_tokenizers.ByteLevel.alphabet()))} + vocab.update({"[EOS]": 256, "[PAD]": 257}) + backend = Tokenizer(models.BPE(vocab=vocab, merges=[])) + backend.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) + backend.decoder = decoders.ByteLevel() + tok = PreTrainedTokenizerFast(tokenizer_object=backend, eos_token="[EOS]", pad_token="[PAD]") + cfg = LlamaConfig(vocab_size=258, hidden_size=32, intermediate_size=64, + num_hidden_layers=1, num_attention_heads=2, num_key_value_heads=2, + eos_token_id=256, pad_token_id=257, max_position_embeddings=256) + torch.manual_seed(17) + model = LlamaForCausalLM(cfg).eval() + # Keep the random fixture from spending its entire token allowance on + # schema-permitted whitespace. Grammar still supplies every JSON constraint. + model.lm_head.bias = torch.nn.Parameter(torch.zeros(258)) + with torch.no_grad(): + for char in (" ", "\t", "\r", "\n"): + model.lm_head.bias[tok.encode(char, add_special_tokens=False)] = -100 + schema = {"type": "object", "properties": {"answer": {"const": "ok"}}, + "required": ["answer"], "additionalProperties": False} + engine = HFBatchedGenerateEngine("unused", model=model, tokenizer=tok, device="cpu", + json_schema=schema, structured_output_backend="xgrammar", max_new_tokens=64) + items = [GenerateItem(id=str(i), prompt=prompt) for i, prompt in enumerate(["Hi", "A longer prompt"])] + first = engine.generate(items, batch_size=1) + again = engine.generate(list(reversed(items)), batch_size=1) + for row in first + again: + assert json.loads(row.completion_text) == {"answer": "ok"} + assert row.finish_reason == "eos" + assert {r.id: r.completion_token_ids for r in first} == {r.id: r.completion_token_ids for r in again} + assert engine.provenance()["structured_output_backend"] == "xgrammar" + + +def test_conditional_model_dispatch_is_registered_and_does_not_retry_weight_errors(monkeypatch): + import transformers as tf + class ConditionalConfig: + pass + cfg = ConditionalConfig() + monkeypatch.setattr(tf.AutoConfig, "from_pretrained", lambda *a, **k: cfg) + monkeypatch.setattr(tf.AutoModelForCausalLM, "_model_mapping", {}) + monkeypatch.setattr(tf.AutoModelForImageTextToText, "_model_mapping", {ConditionalConfig: object}) + calls = [] + def conditional(name, **kwargs): + calls.append((name, kwargs)) + raise OSError("bad checkpoint") + monkeypatch.setattr(tf.AutoModelForImageTextToText, "from_pretrained", conditional) + monkeypatch.setattr(tf.AutoModelForCausalLM, "from_pretrained", lambda *a, **k: pytest.fail("wrong loader")) + with pytest.raises(OSError, match="bad checkpoint"): + load_text_generation_model("local-checkpoint", revision="a" * 40, dtype="bfloat16") + assert len(calls) == 1 and calls[0][1]["config"] is cfg and calls[0][1]["revision"] == "a" * 40 diff --git a/tests/experimental/__init__.py b/tests/experimental/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/experimental/weight_editor/__init__.py b/tests/experimental/weight_editor/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/experimental/weight_editor/codex_fake/fake_codex.py b/tests/experimental/weight_editor/codex_fake/fake_codex.py new file mode 100644 index 000000000..4a73f1486 --- /dev/null +++ b/tests/experimental/weight_editor/codex_fake/fake_codex.py @@ -0,0 +1,56 @@ +"""Synthetic stand-in for the codex CLI. Never contacts a model or reads credentials. + +Copied next to a ``scenario.json`` by the tests and launched through a generated +shebang. Each ``exec`` invocation consumes the next scenario turn and appends its +argv/stdin/env names to ``calls.jsonl`` for assertions. +""" + +import base64 +import json +import os +import subprocess +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def main() -> int: + scen = json.load(open(os.path.join(HERE, "scenario.json"))) + argv = sys.argv[1:] + if argv == ["--version"]: + print(scen.get("version", "codex-cli 0.166.0")) + return 0 + if argv[:2] == ["login", "status"]: + print(scen.get("login", "Logged in using ChatGPT")) + return 0 + if not argv or argv[0] != "exec": + print("fake codex: unsupported invocation", file=sys.stderr) + return 2 + stdin = sys.stdin.buffer.read() + calls = os.path.join(HERE, "calls.jsonl") + n = sum(1 for _ in open(calls)) if os.path.exists(calls) else 0 + with open(calls, "a") as fh: + fh.write(json.dumps({"argv": argv, "stdin_b64": base64.b64encode(stdin).decode(), "cwd": os.getcwd(), + "env_names": sorted(os.environ)}) + "\n") + turn = scen["turns"][n] + if turn.get("spawn_child"): + child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(300)"]) + with open(os.path.join(HERE, "pids.json"), "w") as fh: + json.dump({"parent": os.getpid(), "child": child.pid}, fh) + if "stderr_b64" in turn: + sys.stderr.buffer.write(base64.b64decode(turn["stderr_b64"])) + sys.stderr.buffer.flush() + out = base64.b64decode(turn["stdout_b64"]) if "stdout_b64" in turn else b"" + for i in range(0, len(out), turn.get("chunk", 1 << 20)): # arbitrary pipe chunking + sys.stdout.buffer.write(out[i:i + turn.get("chunk", 1 << 20)]) + sys.stdout.buffer.flush() + if turn.get("write_into_cwd"): + open("native-write.txt", "w").write("x") + if turn.get("sleep"): + time.sleep(turn["sleep"]) + return int(turn.get("exit", 0)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/experimental/weight_editor/conftest.py b/tests/experimental/weight_editor/conftest.py new file mode 100644 index 000000000..b9661a02c --- /dev/null +++ b/tests/experimental/weight_editor/conftest.py @@ -0,0 +1,162 @@ +"""Shared harness: every scenario goes through the public CLI in a subprocess. + +Outputs live under ``scratch/`` (never /tmp) and are removed unless a test fails. +""" + +from __future__ import annotations + +import json +import os +import shutil +import signal +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import pytest + +from synaptic_tuner.experimental.weight_editor.fakes import write_fixture + +REPO = Path(__file__).resolve().parents[3] +PKG = "synaptic_tuner.experimental.weight_editor" +FAKES = f"{PKG}.fakes:build_ports" + + +@pytest.fixture +def workdir(request): + root = REPO / "scratch" / "test-weight-editor" / f"{uuid.uuid4().hex[:8]}" + root.mkdir(parents=True) + yield root + failed = getattr(request.node, "rep_call", None) is not None and request.node.rep_call.failed + if not failed: + shutil.rmtree(root, ignore_errors=True) + + +@pytest.hookimpl(hookwrapper=True, tryfirst=True) +def pytest_runtest_makereport(item, call): + outcome = yield + setattr(item, "rep_" + outcome.get_result().when, outcome.get_result()) + + +def _env(): + env = dict(os.environ, PYTHONPATH=str(REPO), PYTHONDONTWRITEBYTECODE="1") + return env + + +class Fixture: + def __init__(self, workdir: Path, **kw): + self.paths = write_fixture(workdir / "fx", **kw) + self.config = self.paths["config"] + self.effects = self.paths["effects"] + self.runs = self.paths["runs"] + self.capsule = self.paths["capsule"] + + # ---- CLI + def ports_args(self, **extra): + out = ["--ports", FAKES, "--ports-arg", f"script={self.paths['script']}", + "--ports-arg", f"effects_dir={self.effects}"] + for k, v in extra.items(): + out += ["--ports-arg", f"{k}={v}"] + return out + + def cli(self, *args, check_json=True): + proc = subprocess.run([sys.executable, "-m", PKG, *map(str, args)], cwd=REPO, env=_env(), + capture_output=True, text=True, timeout=120) + try: + data = json.loads(proc.stdout) if proc.stdout.strip() else None + except json.JSONDecodeError: + data = None + return proc.returncode, data, proc + + def run(self, run_id="r1", config=None, **ports): + return self.cli("run", "--config", config or self.config, "--run-id", run_id, *self.ports_args(**ports)) + + def resume(self, run_id="r1", config=None, extra=(), **ports): + return self.cli("resume", "--config", config or self.config, "--run-id", run_id, *extra, + *self.ports_args(**ports)) + + def popen(self, verb, run_id="r1", **ports): + return subprocess.Popen( + [sys.executable, "-m", PKG, verb, "--config", str(self.config), "--run-id", run_id, + *map(str, self.ports_args(**ports))], + cwd=REPO, env=_env(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + + def wait_marker(self, stage, proc, timeout=60): + marker = self.effects / f"paused-{stage}" + end = time.time() + timeout + while time.time() < end: + if marker.exists(): + return + if proc.poll() is not None: + raise AssertionError(f"process exited early: {proc.communicate()}") + time.sleep(0.05) + raise AssertionError("pause marker never appeared") + + def sigkill(self, proc): + proc.send_signal(signal.SIGKILL) + proc.wait(timeout=30) + assert proc.returncode == -signal.SIGKILL + + # ---- inspection + def run_dir(self, run_id="r1"): + return self.runs / run_id + + def journal(self, run_id="r1"): + return read_jsonl(self.run_dir(run_id) / "journal" / "events.jsonl") + + def raw(self, run_id="r1"): + return read_jsonl(self.run_dir(run_id) / "provider" / "events.jsonl") + + def effect_lines(self): + f = self.effects / "effects.log" + return [json.loads(x) for x in f.read_text().splitlines()] if f.exists() else [] + + +def read_jsonl(path: Path): + return [json.loads(x) for x in path.read_text().splitlines() if x.strip()] + + +def types(journal): + return [r["type"] for r in journal] + + +def of_type(journal, t): + return [r for r in journal if r["type"] == t] + + +@pytest.fixture +def make(workdir): + count = {"n": 0} + + def factory(**kw): + count["n"] += 1 + return Fixture(workdir / f"case{count['n']}", **kw) + + return factory + + +# ---- script builders +def req(op, **arguments): + return {"type": "tool_request", "operation": op, "arguments": arguments} + + +def final(choice="no_edit", proposal=None, rationale="synthetic justification"): + d = {"type": "final_choice", "choice": choice, "rationale": rationale} + if proposal: + d["proposal"] = proposal + return d + + +def script(*turns): + return {"turns": [{"events": t} if isinstance(t, list) else t for t in turns]} + + +QUERY12 = req("query_development", items=["dev-001", "dev-002"]) +OK_PATCH = json.dumps({"tensor": "w.layer0", "deltas": [0.1, -0.1, 0.05]}) +BAD_PATCH = json.dumps({"tensor": "w.layer0", "deltas": [0.1, 9.0, 0.05]}) + + +def patch(name, text=OK_PATCH, tensor="w.layer0"): + return req("propose_patch", name=name, tensor=tensor, patch=text, justification=f"synthetic reason for {name}") diff --git a/tests/experimental/weight_editor/test_admission_and_budget.py b/tests/experimental/weight_editor/test_admission_and_budget.py new file mode 100644 index 000000000..c164968cb --- /dev/null +++ b/tests/experimental/weight_editor/test_admission_and_budget.py @@ -0,0 +1,135 @@ +"""Forbidden access must have no executor effect; budgets are caller-owned and never reset.""" + +from __future__ import annotations + +import json + +from .conftest import QUERY12, final, of_type, patch, req, script, types + + +def denied_reasons(fx, run_id="r1"): + return [(r["data"]["request_id"], r["data"]["reason"]) for r in of_type(fx.journal(run_id), "request_denied")] + + +def test_forbidden_requests_are_denied_with_no_executor_effects(make): + turn1 = [ + {"type": "tool_request", "operation": "inspect_weights", "arguments": {"tensor": "w.layer0"}, + "command": "cat /etc/passwd"}, # command authority + req("inspect_weights", tensor="/etc/passwd"), # absolute path + req("inspect_weights", tensor="../../capsule/tensors/w.layer0.json"), # traversal + req("inspect_weights", tensor="file:///etc/hostname"), # URL scheme + req("inspect_weights", tensor="dev-999"), # unknown id + req("query_development", items=["heldout-007"]), # withheld id + req("inspect_weights", tensor="dev-001"), # wrong object kind + req("run_shell", cmd="id"), # unadmitted op + req("analyze", tensor="w.layer0"), # not configured + req("inspect_weights", tensor="w.layer0", output_root="/"), # policy override + req("inspect_weights", tensor="w.layer0", budget=10**9), # budget override + req("inspect_weights"), # missing arg + req("inspect_weights", tensor="w.layer0", extra=1), # undeclared arg + patch("w.layer0"), # write onto base/source id + patch("../../escape"), # write traversal + req("query_development", items=["dev-001", "dev-001"]), # duplicate ids + req("query_development", items=["dev-001", "dev-002", "dev-003", "dev-004", "dev-001"]), # over max_items + {"type": "tool_request", "operation": "inspect_weights", "arguments": []}, # malformed + {"type": "tool_request", "arguments": {"tensor": "w.layer0"}}, # no op + {"type": "tool_request", "operation": "inspect_weights", "arguments": {"tensor": "w.layer0"}, + "policy": {"admit": "all"}}, # policy field + ] + fx = make(script=script(turn1, [final()])) + code, out, _ = fx.run() + assert code == 0, out + assert fx.effect_lines() == [] + assert list((fx.effects / "dispatches").iterdir()) == [] # executor never touched at all + assert out["dispatches"] == {} + reasons = [r for _, r in denied_reasons(fx)] + assert reasons == [ + "forbidden_field", "path_authority", "path_authority", "path_authority", "unknown_object", + "withheld_id", "unknown_object", "unadmitted_operation", "unadmitted_operation", "forbidden_field", + "forbidden_field", "missing_argument", "unknown_argument", "source_or_base_write", "path_authority", + "invalid_argument", "invalid_argument", "malformed_request", "malformed_request", "forbidden_field", + ] + assert "dispatch_intent" not in types(fx.journal()) + assert not any((fx.paths["root"] / "escape").parent.glob("escape*")) + # every attempt, denied or not, was charged to the requests meter + assert out["budget"]["requests"]["committed"] == len(turn1) + assert "dispatches" not in out["budget"] + + +def test_withheld_and_unknown_ids_look_identical_to_the_model(make): + fx = make(script=script([req("query_development", items=["heldout-007"]), + req("query_development", items=["dev-999"])], [final()])) + assert fx.run()[0] == 0 + msgs = [json.loads(r["data"]["message"]["content"]) for r in of_type(fx.journal(), "request_denied")] + assert msgs[0]["detail"] == msgs[1]["detail"] == "unknown or unadmitted object" + assert {k: v for k, v in msgs[0].items() if k != "request_id"} == { + k: v for k, v in msgs[1].items() if k != "request_id"} + audit = {r["data"]["reason"] for r in of_type(fx.journal(), "request_denied")} + assert audit == {"withheld_id", "unknown_object"} # distinguished only in the audit trail + + +def test_executor_validation_denial_has_no_effect_and_no_charge(make): + fx = make(script=script([patch("p1", text=" ")], [final()])) + # patch text is non-empty-checked by the executor port (side-effect-free validate) + code, out, _ = fx.run() + assert code == 0 + assert denied_reasons(fx) == [("req-0001", "executor_validation")] + assert fx.effect_lines() == [] + assert out["budget"].get("cpu_units", {"charged": 0})["charged"] == 0 + + +def test_budget_exhaustion_denies_without_effect_and_is_audited(make): + fx = make(limits={"gpu_units": 1.0, "examples": 2}, + script=script([QUERY12, req("query_development", items=["dev-003"]), req("query_development", items=["dev-004"])], + [final()])) + code, out, _ = fx.run() + assert code == 0 + assert len(fx.effect_lines()) == 1 # only the first query fit under the physical budget + assert denied_reasons(fx) == [("req-0002", "budget_exceeded"), ("req-0003", "budget_exceeded")] + assert out["budget"]["gpu_units"]["committed"] == 1.0 and out["budget"]["gpu_units"]["reserved_outstanding"] == 0 + reserve = [e for r in of_type(fx.journal(), "request_admitted") for e in r["data"]["ledger"]] + assert {e["op"] for e in reserve} == {"reserve"} # reservation precedes the charge, both in the audit trail + + +def test_no_default_money_or_token_cap_is_invented(make): + fx = make(script=script([req("inspect_weights", tensor="w.layer0")] * 25, [final()])) + code, out, _ = fx.run() + assert code == 0 and len(fx.effect_lines()) == 25 + assert all(row["limit"] is None for row in out["budget"].values()) + + +def test_request_and_turn_limits_halt_and_do_not_reset_on_resume(make): + fx = make(limits={"requests": 2}, script=script( + [req("inspect_weights", tensor="w.layer0")] * 3, [final()])) + code, out, _ = fx.run() + assert code == 4 and out["status"] == "incomplete" and out["halt"]["code"] == "budget_exhausted" + assert len(fx.effect_lines()) == 2 and denied_reasons(fx) == [("req-0003", "budget_exceeded")] + turns_before = len(of_type(fx.journal(), "turn_start")) + code2, out2, _ = fx.resume() + assert code2 == 4 and out2["halt"]["code"] == "budget_exhausted" + assert out2["budget"]["requests"]["committed"] == 3 # charges survive resume + assert len(of_type(fx.journal(), "turn_start")) == turns_before # model not called again + + fx2 = make(limits={"model_turns": 1}, script=script([req("inspect_weights", tensor="w.layer0")], [final()])) + code, out, _ = fx2.run() + assert code == 4 and out["halt"]["code"] == "budget_exhausted" and out["turns"] == 1 + assert len(fx2.effect_lines()) == 1 + + +def test_nan_usage_from_executor_is_charged_at_reservation_and_flagged(make): + fx = make(limits={"gpu_units": 10}, script=script([QUERY12], [final()])) + code, out, _ = fx.run(fault="bad_usage") + assert code == 0 + res = of_type(fx.journal(), "dispatch_result")[0]["data"] + assert "usage_invalid_charged_reservation_only" in res["anomalies"] + assert out["budget"]["gpu_units"]["committed"] == 1.0 # conservative: reservation, never zero, never NaN + + +def test_late_query_after_frozen_choice_has_no_effect(make): + fx = make(script=script([patch("p1")], [final("patch", "req-0001"), QUERY12, req("inspect_weights", tensor="w.layer0")])) + code, out, _ = fx.run() + assert code == 0 and out["phase"] == "final_patch_frozen" + assert len(fx.effect_lines()) == 1 # only the proposal; the post-freeze queries never reached the executor + assert [r for _, r in denied_reasons(fx)] == ["phase_closed", "phase_closed"] + assert types(fx.journal()).index("final_patch_frozen") < [ + i for i, r in enumerate(fx.journal()) if r["type"] == "request_denied"][0] diff --git a/tests/experimental/weight_editor/test_cli_basics.py b/tests/experimental/weight_editor/test_cli_basics.py new file mode 100644 index 000000000..6b9af7636 --- /dev/null +++ b/tests/experimental/weight_editor/test_cli_basics.py @@ -0,0 +1,163 @@ +"""Smoke, validation and registration behavior through the public CLI.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys + +import pytest + +from synaptic_tuner.experimental.weight_editor.canon import sha256_hex + +from .conftest import PKG, REPO, final, script + + +def test_synthetic_smoke_runs_verifies_and_exports(workdir): + proc = subprocess.run([sys.executable, "-m", PKG, "smoke", "--workdir", str(workdir / "smoke")], cwd=REPO, + env=dict(os.environ, PYTHONPATH=str(REPO)), capture_output=True, text=True) + assert proc.returncode == 0, proc.stderr + out = json.loads(proc.stdout) + assert out["ok"] and out["summary"]["status"] == "complete" + assert out["effect_count"] == out["unique_dispatches"] == 4 # one effect per admitted dispatch + assert out["summary"]["unknown_events"] == 0 and out["summary"]["capture_qualification"]["qualified"] is True + assert out["summary"]["hidden_reasoning_captured"] is False + # smoke never overwrites + again = subprocess.run([sys.executable, "-m", PKG, "smoke", "--workdir", str(workdir / "smoke")], cwd=REPO, + env=dict(os.environ, PYTHONPATH=str(REPO)), capture_output=True, text=True) + assert again.returncode == 1 and json.loads(again.stdout)["error"]["code"] == "run_exists" + + +def test_core_imports_without_torch_or_model_stack(): + code = ("import sys, synaptic_tuner.experimental.weight_editor.cli as c;" + "print(sorted(m for m in ('torch','transformers','openai','anthropic','requests') if m in sys.modules))") + proc = subprocess.run([sys.executable, "-c", code], cwd=REPO, env=dict(os.environ, PYTHONPATH=str(REPO)), + capture_output=True, text=True) + assert proc.stdout.strip() == "[]", proc.stdout + proc.stderr + + +def test_validate_reports_without_effects_or_run(make): + fx = make(script=script([final()])) + code, out, _ = fx.cli("validate", "--config", fx.config, *fx.ports_args()) + assert code == 0 and out["ok"] + assert out["operations"] == ["inspect_weights", "propose_patch", "query_development"] + assert out["limits"].startswith("none configured") # no invented default budget + assert "not verified" in out["ports"]["isolation_note"] + assert not fx.runs.exists() and fx.effect_lines() == [] + + +def test_unsupported_operation_is_rejected_by_executor_port(make): + fx = make(script=script([final()]), extra_ops={ + "analyze": {"arguments": {"tensor": {"type": "ref", "kind": "tensor"}}, "required": ["tensor"]}}) + code, out, _ = fx.cli("validate", "--config", fx.config, *fx.ports_args()) + assert code == 1 and out["error"]["code"] == "unsupported_capability" + assert out["error"]["unsupported"] == ["analyze"] + code, out, _ = fx.run() + assert code == 1 and out["error"]["code"] == "unsupported_capability" + assert not fx.runs.exists() or not list(fx.runs.iterdir()) + + +def test_no_silent_model_fallback(make): + fx = make(script=script([final()])) + code, out, _ = fx.cli("validate", "--config", fx.config, *fx.ports_args(model="some-other-model")) + assert code == 1 and out["error"]["code"] == "model_mismatch" + code, out, _ = fx.run(model="some-other-model") + assert code == 1 and out["error"]["code"] == "model_mismatch" + assert fx.effect_lines() == [] and (not fx.runs.exists() or not list(fx.runs.iterdir())) + + +def _edit_config(fx, fn): + cfg = json.loads(fx.config.read_text()) + fn(cfg) + fx.config.write_text(json.dumps(cfg)) + + +def _edit_capsule(fx, fn): + path = fx.paths["capsule_manifest"] + doc = json.loads(path.read_text()) + fn(doc) + path.write_text(json.dumps(doc)) + + +def _heldout(doc): + doc["objects"][2]["split"] = "heldout" + + +def _traversal(doc): + doc["objects"][2]["path"] = "../outside.json" + + +def _absolute(doc): + doc["objects"][2]["path"] = "/etc/hostname" + + +def _symlink_escape(fx): + outside = fx.paths["root"] / "outside.json" + outside.write_text("{}") + link = fx.capsule / "dev" / "link.json" + link.symlink_to(outside) + _edit_capsule(fx, lambda d: d["objects"].append( + {"id": "dev-link", "kind": "dev_item", "path": "dev/link.json", + "sha256": sha256_hex(b"{}"), "split": "development"})) + + +@pytest.mark.parametrize("mutate,code", [ + (lambda fx: _edit_capsule(fx, _heldout), "non_development_object"), + (lambda fx: _edit_capsule(fx, _traversal), "path_traversal"), + (lambda fx: _edit_capsule(fx, _absolute), "path_not_relative"), + (_symlink_escape, "path_escape"), + (lambda fx: _edit_capsule(fx, lambda d: d["objects"][2].update(sha256="0" * 64)), "capsule_hash_mismatch"), + (lambda fx: _edit_capsule(fx, lambda d: d["objects"].append(dict(d["objects"][0]))), "capsule_invalid"), + (lambda fx: _edit_config(fx, lambda c: c.update(policy={"budget": "unlimited"})), "config_invalid"), + (lambda fx: _edit_config(fx, lambda c: c.update(shell="bash")), "config_invalid"), + (lambda fx: _edit_config(fx, lambda c: c["model"].pop("model")), "config_invalid"), + (lambda fx: _edit_config(fx, lambda c: c.update(resources={"limits": {"gpu_units": -1}})), "config_invalid"), + (lambda fx: _edit_config(fx, lambda c: c["operations"]["query_development"]["cost"].update( + gpu_units={"len_of": "items", "per_item": -2})), "config_invalid"), + (lambda fx: _edit_config(fx, lambda c: c.update(operations={})), "config_invalid"), + (lambda fx: _edit_config(fx, lambda c: c.update(output_root="capsule/out")), "output_root_overlap"), + (lambda fx: _edit_config(fx, lambda c: c["operations"]["inspect_weights"]["arguments"].update( + path={"type": "text", "max_length": 10})), "authority_argument_name"), +]) +def test_config_and_capsule_rejections_happen_before_any_effect(make, mutate, code): + fx = make(script=script([final()])) + mutate(fx) + ccode, out, _ = fx.cli("validate", "--config", fx.config, *fx.ports_args()) + assert ccode == 1 and out["error"]["code"] == code, out + assert fx.run()[0] == 1 + assert fx.effect_lines() == [] and not (fx.runs.exists() and list(fx.runs.iterdir())) + + +def test_nan_and_duplicate_keys_in_config_are_not_strict_json(make): + fx = make(script=script([final()])) + fx.config.write_text('{"schema": "weight_editor_config/v1", "resources": {"limits": {"gpu_units": NaN}}}') + code, out, _ = fx.cli("validate", "--config", fx.config, *fx.ports_args()) + assert code == 1 and "strict JSON" in out["error"]["message"] + fx.config.write_text('{"schema": "a", "schema": "b"}') + code, out, _ = fx.cli("validate", "--config", fx.config, *fx.ports_args()) + assert code == 1 and "duplicate key" in out["error"]["message"] + + +def test_runs_are_never_overwritten_and_run_ids_are_contained(make): + fx = make(script=script([final()])) + assert fx.run("r1")[0] == 0 + before = (fx.run_dir("r1") / "journal" / "events.jsonl").read_bytes() + code, out, _ = fx.run("r1") + assert code == 1 and out["error"]["code"] == "run_exists" + assert (fx.run_dir("r1") / "journal" / "events.jsonl").read_bytes() == before + for bad in ("../escape", "/abs/path", "A B", "a/b", ".hidden", ""): + code, out, _ = fx.run(bad) + assert code != 0 and (out is None or out["error"]["code"] in ("bad_run_id", "run_exists")), bad + assert not (fx.paths["root"] / "escape").exists() + + +def test_symlinked_run_slot_cannot_redirect_outside_output_root(make): + fx = make(script=script([final()])) + outside = fx.paths["root"] / "outside-target" + outside.mkdir() + fx.runs.mkdir() + (fx.runs / "evil").symlink_to(outside) + code, out, _ = fx.run("evil") + assert code == 1 and out["error"]["code"] == "run_exists" + assert list(outside.iterdir()) == [] diff --git a/tests/experimental/weight_editor/test_codex_account_adapter.py b/tests/experimental/weight_editor/test_codex_account_adapter.py new file mode 100644 index 000000000..cd37b5e53 --- /dev/null +++ b/tests/experimental/weight_editor/test_codex_account_adapter.py @@ -0,0 +1,504 @@ +"""Codex account adapter against a fake executable. Synthetic only: no model, no auth, no network.""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import shutil +import sys +import threading +import time +import uuid +from pathlib import Path + +import pytest + +from synaptic_tuner.experimental.weight_editor.adapters import codex_account as ca +from synaptic_tuner.experimental.weight_editor.adapters.codex_account import ( + PROVIDER, CodexAccountAdapter, build_codex_account_ports, normalize, +) +from synaptic_tuner.experimental.weight_editor.broker import EditorRun +from synaptic_tuner.experimental.weight_editor.config import load_config +from synaptic_tuner.experimental.weight_editor.errors import ( + AdapterCancelled, AdapterFailure, AdapterTimeout, PortError, UnsupportedCapability, +) +from synaptic_tuner.experimental.weight_editor.fakes import FakeEffectExecutor, write_fixture +from synaptic_tuner.experimental.weight_editor.ports import PortContext, TransportEvent, TurnInput + +REPO = Path(__file__).resolve().parents[3] +FAKE_SRC = Path(__file__).with_name("codex_fake") / "fake_codex.py" +MODEL = {"provider": PROVIDER, "model": "synthetic-model-1", "settings": {"reasoning_effort": "medium"}} +THREAD = "0199aaaa-bbbb-7ccc-8ddd-eeeeffff0001" + + +# ------------------------------------------------------------ synthetic stream builders + +def line(obj) -> bytes: + return (json.dumps(obj) + "\n").encode() + + +def envelope(**kw) -> str: + base = {"action": None, "operation": None, "arguments_json": None, "choice": None, "proposal": None, + "rationale": ""} + base.update(kw) + return json.dumps(base) + + +def request_env(op, args, why="synthetic rationale"): + return envelope(action="request", operation=op, arguments_json=json.dumps(args), rationale=why) + + +def final_env(choice, proposal=None, why="synthetic final rationale"): + return envelope(action="final_choice", choice=choice, proposal=proposal, rationale=why) + + +def stream(text, thread=THREAD, model="synthetic-model-1", extra=(), complete=True, reasoning=True): + started = {"type": "thread.started", "thread_id": thread} + if model: + started["model"] = model # synthetic: models a client that reports returned identity + out = line(started) + line({"type": "turn.started"}) + if reasoning: + out += line({"type": "item.completed", "item": {"id": "item_0", "type": "reasoning", + "text": "synthetic exposed summary"}}) + for e in extra: + out += e if isinstance(e, bytes) else line(e) + if text is not None: + out += line({"type": "item.completed", "item": {"id": "item_1", "type": "agent_message", "text": text}}) + if complete: + out += line({"type": "turn.completed", "usage": {"input_tokens": 11, "cached_input_tokens": 0, + "output_tokens": 7, "reasoning_output_tokens": 3}}) + return out + + +# ------------------------------------------------------------ harness + +class Rig: + def __init__(self, root: Path, turns, **scen): + self.root = root + self.bin = root / "bin" + self.work = root / "work" + self.control = root / "control" + self.home = root / "home" + for d in (self.bin, self.work, self.control, self.home): + d.mkdir(parents=True) + self.exe = self.bin / "codex" + self.exe.write_text(f"#!{sys.executable}\n" + FAKE_SRC.read_text()) + self.exe.chmod(0o755) + self.set_turns(turns, **scen) + self.env = {"PATH": os.environ.get("PATH", "/usr/bin"), "HOME": str(self.home), "LANG": "C.UTF-8", + "PYTHONDONTWRITEBYTECODE": "1", "UNRELATED_SECRETISH": "should-not-pass"} + + def set_turns(self, turns, **scen): + norm = [] + for t in turns: + t = dict(t) + if "stdout" in t: + t["stdout_b64"] = base64.b64encode(t.pop("stdout")).decode() + if "stderr" in t: + t["stderr_b64"] = base64.b64encode(t.pop("stderr")).decode() + norm.append(t) + (self.bin / "scenario.json").write_text(json.dumps({"turns": norm, **scen})) + + @property + def sha(self): + return hashlib.sha256(self.exe.read_bytes()).hexdigest() + + def markers(self): + out = [] + for d in (self.work, *self.work.parents): + for n in ca.ANCESTOR_MARKERS: + if (d / n).exists(): + out.append(str(d / n)) + return tuple(out) + + def adapter(self, **kw): + args = dict(model=MODEL, codex_path=self.exe, expected_sha256=self.sha, + expected_version="codex-cli 0.166.0", work_dir=self.work, control_dir=self.control, + mode="probe", base_env=self.env, acknowledged_markers=self.markers(), kill_grace_s=1.0) + args.update(kw) + return CodexAccountAdapter(**args) + + def calls(self): + p = self.bin / "calls.jsonl" + return [json.loads(x) for x in p.read_text().splitlines()] if p.exists() else [] + + +@pytest.fixture +def root(request): + r = REPO / "scratch" / "test-codex-account-adapter" / uuid.uuid4().hex[:8] + r.mkdir(parents=True) + yield r + rep = getattr(request.node, "rep_call", None) + if rep is None or not rep.failed: + shutil.rmtree(r, ignore_errors=True) + + +def turn_input(idx=1, session=None, messages=({"role": "user", "content": "Begin discovery."},), resumed=False): + return TurnInput("run-x", f"turn-{idx:04d}", idx, session, tuple(messages), "ctx", resumed) + + +def drain(adapter, ti): + events, err = [], None + try: + for ev in adapter.run_turn(ti): + events.append(ev) + except AdapterFailure as exc: + err = exc + return events, err + + +def chan(events, name): + return b"".join(e.data for e in events if e.channel == name) + + +# ------------------------------------------------------------ construction / identity / flags + +def test_flags_disable_every_tool_and_bind_identity(root): + rig = Rig(root, []) + a = rig.adapter() + argv = a.argv_for(None) + assert argv[:2] == [str(rig.exe), "exec"] and argv[-1] == "-" + for flag in ("--json", "--ignore-user-config", "--ignore-rules", "--strict-config", "--skip-git-repo-check", + "--output-schema"): + assert flag in argv + assert "--ephemeral" not in argv # resume needs the persisted provider thread + cs = [argv[i + 1] for i, x in enumerate(argv) if x == "-c"] + for feat in ca.DISABLED_FEATURES: + assert f"features.{feat}=false" in cs + for needed in ('forced_login_method="chatgpt"', 'sandbox_mode="read-only"', 'web_search="disabled"', + "tools.update_plan.enabled=false", "skills.include_instructions=false", "mcp_servers={}", + "project_doc_max_bytes=0", 'model_reasoning_effort="medium"', "show_raw_agent_reasoning=false"): + assert needed in cs + assert argv[argv.index("-m") + 1] == "synthetic-model-1" + resume = a.argv_for(THREAD) + assert resume[1:3] == ["exec", "resume"] and resume[-2:] == [THREAD, "-"] + assert resume[3:-2] == argv[2:-1] # identical effective flags on resume + + ident = a.identity() + assert {k: ident[k] for k in ("provider", "model", "settings")} == MODEL + assert ident["client_sha256"] == rig.sha and ident["client_version"] == "codex-cli 0.166.0" + assert ident["capabilities"]["raw_events"] is True + assert ident["capabilities"]["captures_hidden_reasoning"] is False + assert ident["qualification"]["qualified"] is False and ident["qualification"]["blockers"] + assert ident["returned_identity"]["synthesized"] is False + assert "UNRELATED_SECRETISH" not in ident["effective_config"]["env_names"] + assert json.loads((rig.control / "response-schema.json").read_text())["additionalProperties"] is False + # stable across construction (broker drift check relies on it) + assert rig.adapter().identity() == ident + + +def test_refusals_fail_closed(root): + rig = Rig(root, []) + with pytest.raises(PortError, match="API-key"): + rig.adapter(base_env={**rig.env, "OPENAI_API_KEY": "synthetic"}) + with pytest.raises(PortError, match="sha256"): + rig.adapter(expected_sha256="0" * 64) + with pytest.raises(PortError, match="version"): + rig.adapter(expected_version="codex-cli 9.9.9") + with pytest.raises(UnsupportedCapability): + rig.adapter(model={**MODEL, "settings": {"temperature": "0"}}) + with pytest.raises(UnsupportedCapability): + rig.adapter(model={**MODEL, "provider": "openai-api"}) + with pytest.raises(PortError, match="markers"): + rig.adapter(acknowledged_markers=()) + with pytest.raises(PortError, match="mode"): + rig.adapter(mode="auto") + with pytest.raises(PortError, match="qualification_record"): + rig.adapter(mode="qualified") + (rig.control / "instructions.md").write_text("tampered") + with pytest.raises(PortError, match="differs"): + rig.adapter() + (rig.control / "instructions.md").unlink() + (rig.work / "stray").write_text("x") + with pytest.raises(PortError, match="empty"): + rig.adapter() + + +def test_api_key_login_mode_refused(root): + rig = Rig(root, [], login="Logged in using an API key") + with pytest.raises(PortError, match="ChatGPT"): + rig.adapter() + + +def test_qualified_mode_requires_matching_record(root): + rig = Rig(root, []) + probe = rig.adapter() + rec = {"schema": ca.QUALIFICATION_SCHEMA, "client_sha256": rig.sha, + "effective_config_sha256": probe.identity()["effective_config_sha256"], "model": MODEL, + "verified": {"native_tool_catalogue_empty": True, "model_visible_instructions": True, + "returned_model_reported": True, "no_client_internal_retry": True}, + "evidence_sha256": "e" * 64} + p = root / "qual.json" + p.write_text(json.dumps(rec)) + q = rig.adapter(mode="qualified", qualification_record=p) + assert q.identity()["qualification"]["qualified"] is True and q.identity()["qualification"]["blockers"] == [] + for bad in ({"effective_config_sha256": "x"}, {"verified": {**rec["verified"], "returned_model_reported": False}}): + p.write_text(json.dumps({**rec, **bad})) + with pytest.raises(PortError): + rig.adapter(mode="qualified", qualification_record=p) + + +def test_composition_helper_needs_real_executor(root): + rig = Rig(root, []) + ctx = PortContext(args={}, model=MODEL) + kw = dict(codex_path=rig.exe, expected_sha256=rig.sha, expected_version="codex-cli 0.166.0", + work_dir=rig.work, control_dir=rig.control, mode="probe", base_env=rig.env, + acknowledged_markers=rig.markers()) + with pytest.raises(PortError): + build_codex_account_ports(ctx, object(), **kw) + with pytest.raises(PortError): + build_codex_account_ports(ctx, FakeEffectExecutor(root / "fx"), model=MODEL, **kw) + ports = build_codex_account_ports(ctx, FakeEffectExecutor(root / "fx"), **kw) + assert isinstance(ports.adapter, CodexAccountAdapter) + + +# ------------------------------------------------------------ exact capture and mapping + +def test_exact_raw_stdout_stderr_and_input_retention(root): + out = stream(request_env("inspect_weights", {"tensor": "w.layer0"})) + err = b"synthetic diagnostic \xff\x00 bytes\npartial-no-newline" + rig = Rig(root, [{"stdout": out, "stderr": err, "chunk": 7}]) + a = rig.adapter() + ti = turn_input() + events, exc = drain(a, ti) + assert exc is None + assert all(isinstance(e, TransportEvent) for e in events) + assert chan(events, "provider") == out # byte-exact, newlines included, despite 7-byte chunking + assert [e.data for e in events if e.channel == "provider"] == out.splitlines(keepends=True) + assert chan(events, "client_stderr") == err + launch, stdin = [e.data for e in events if e.channel == "client_input"] + assert events[0].channel == events[1].channel == "client_input" # recorded before the process ran + call = rig.calls()[0] + assert base64.b64decode(call["stdin_b64"]) == stdin + assert json.loads(launch)["argv"] == [str(rig.exe)] + call["argv"] + assert json.loads(stdin)["messages"] == [dict(m) for m in ti.messages] + assert "UNRELATED_SECRETISH" not in call["env_names"] and "OPENAI_API_KEY" not in call["env_names"] + assert call["cwd"] == str(rig.work) + kinds = [a.parse_event(e.data)["kind"] for e in events if e.channel == "provider"] + assert kinds == ["session", "session", "reasoning_summary", "request", "finish"] + req = a.parse_event(out.splitlines(keepends=True)[3]) + assert req == {"kind": "request", "operation": "inspect_weights", "arguments": {"tensor": "w.layer0"}, + "rationale": "synthetic rationale"} + sess = a.parse_event(out.splitlines(keepends=True)[0]) + assert sess["session_id"] == THREAD and sess["model"] == "synthetic-model-1" + + +def test_mapping_rules(): + fin = normalize(line({"type": "item.completed", "item": {"type": "agent_message", "id": "i", + "text": final_env("no_edit")}})) + assert fin == {"kind": "final_choice", "choice": "no_edit", "rationale": "synthetic final rationale"} + fin = normalize(line({"type": "item.completed", "item": {"type": "agent_message", "id": "i", + "text": final_env("patch", "req-0002")}})) + assert fin["proposal"] == "req-0002" + plain = normalize(line({"type": "item.completed", "item": {"type": "agent_message", "id": "i", + "text": "please run inspect_weights"}})) + assert plain["kind"] == "message" # ordinary text never becomes a request + for bad in (envelope(action="request", operation="x", arguments_json="[1]"), + envelope(action="request", operation="x", arguments_json='{"a":1,"a":2}'), + envelope(action="final_choice", choice="maybe"), + json.dumps({"action": "request", "operation": "x", "arguments_json": "{}", "rationale": "", + "choice": None, "proposal": None, "extra": 1})): + with pytest.raises(ValueError): + normalize(line({"type": "item.completed", "item": {"type": "agent_message", "id": "i", "text": bad}})) + assert normalize(line({"type": "item.started", "item": {"type": "command_execution", "id": "c"}}))["kind"] == "unknown" + assert normalize(line({"type": "future.event"}))["kind"] == "unknown" + with pytest.raises(ValueError): + normalize(b"not json\n") + + +# ------------------------------------------------------------ failure detection (raise after retaining) + +FAILS = { + "native_tool_event": dict(extra=[{"type": "item.started", "item": {"id": "c1", "type": "command_execution", + "command": "ls"}}]), + "unknown_provider_event": dict(extra=[{"type": "future.packet", "x": 1}]), + "malformed_provider_event": dict(extra=[b"{not json\n"]), + "provider_error": dict(extra=[{"type": "error", "message": "Reconnecting... 1/5"}]), + "missing_turn_completion": dict(complete=False), + "returned_model_unobserved": dict(model=None), +} + + +@pytest.mark.parametrize("code", sorted(FAILS)) +def test_failures_retained_then_raised(root, code): + out = stream(request_env("inspect_weights", {"tensor": "w.layer0"}), **FAILS[code]) + rig = Rig(root, [{"stdout": out}]) + events, exc = drain(rig.adapter(), turn_input()) + assert exc is not None and exc.code == code + got = chan(events, "provider") + assert out.startswith(got) and got # everything observed before the kill is retained exactly + + +def test_multiple_actions_and_missing_action(root): + two = stream(request_env("a", {}), extra=[{"type": "item.completed", "item": { + "id": "x", "type": "agent_message", "text": request_env("b", {})}}]) + rig = Rig(root, [{"stdout": two}, {"stdout": stream("just prose, no action")}]) + a = rig.adapter() + assert drain(a, turn_input())[1].code == "multiple_actions" + assert drain(a, turn_input())[1].code == "no_structured_action" + + +def test_truncated_stream_nonzero_exit_and_trailing_output(root): + full = stream(final_env("no_edit")) + rig = Rig(root, [{"stdout": full[:-5]}, {"stdout": full, "exit": 1}, + {"stdout": full + line({"type": "turn.started"})}]) + a = rig.adapter() + ev, exc = drain(a, turn_input()) + assert exc.code == "truncated_stream" and chan(ev, "provider") == full[:-5] + ev, exc = drain(a, turn_input()) + assert exc.code == "nonzero_exit" and chan(ev, "provider") == full + assert drain(a, turn_input())[1].code == "output_after_completion" + + +def test_native_write_into_work_dir_detected(root): + rig = Rig(root, [{"stdout": stream(final_env("no_edit")), "write_into_cwd": True}]) + assert drain(rig.adapter(), turn_input())[1].code == "work_dir_dirty" + + +# ------------------------------------------------------------ session / resume / drift + +def test_resume_uses_journaled_thread_and_detects_drift(root): + rig = Rig(root, [{"stdout": stream(request_env("a", {}))}, {"stdout": stream(final_env("no_edit"))}, + {"stdout": stream(final_env("no_edit"), thread="0199-other-thread")}]) + a = rig.adapter() + assert drain(a, turn_input(1))[1] is None + tool_reply = ({"role": "tool", "content": '{"request_id":"req-0001","status":"ok"}'},) + assert drain(a, turn_input(2, THREAD, tool_reply))[1] is None + calls = rig.calls() + assert calls[1]["argv"][:2] == ["exec", "resume"] and calls[1]["argv"][-2:] == [THREAD, "-"] + assert json.loads(base64.b64decode(calls[1]["stdin_b64"]))["messages"] == [dict(tool_reply[0])] + assert drain(a, turn_input(3, THREAD, tool_reply))[1].code == "session_drift" + + +def test_resume_refusals_before_spawn(root): + rig = Rig(root, [{"stdout": stream(final_env("no_edit"))}]) + a = rig.adapter() + for ti, code in ((turn_input(2, THREAD, resumed=True), "resume_after_interruption"), + (turn_input(2, "bad id with spaces"), "session_invalid"), + (turn_input(2, None, messages=()), "missing_bootstrap")): + ev, exc = drain(a, ti) + assert exc.code == code and ev == [] + # a fresh bootstrap without a session is allowed (core resends instructions/catalog) + assert drain(a, turn_input(5, None))[1] is None + assert rig.calls()[0]["argv"][1] != "resume" + # client bytes swapped mid-run + rig.exe.write_text(rig.exe.read_text() + "\n# changed\n") + assert drain(a, turn_input(6, None))[1].code == "client_drift" + + +# ------------------------------------------------------------ cancellation / timeout / cleanup + +def _alive(pid): + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + try: # zombie counts as dead + return Path(f"/proc/{pid}/stat").read_text().split()[2] != "Z" + except OSError: + return False + + +def test_timeout_kills_owned_process_group(root): + rig = Rig(root, [{"stdout": line({"type": "thread.started", "thread_id": THREAD, "model": "m"}), + "spawn_child": True, "sleep": 300}]) + a = rig.adapter(turn_timeout_s=1.5) + t0 = time.monotonic() + with pytest.raises(AdapterTimeout): + list(a.run_turn(turn_input())) + assert time.monotonic() - t0 < 20 + pids = json.loads((rig.bin / "pids.json").read_text()) + deadline = time.monotonic() + 5 + while time.monotonic() < deadline and (_alive(pids["parent"]) or _alive(pids["child"])): + time.sleep(0.1) + assert not _alive(pids["parent"]) and not _alive(pids["child"]) + + +def test_cancel_from_another_thread(root): + rig = Rig(root, [{"stdout": line({"type": "thread.started", "thread_id": THREAD}), "spawn_child": True, + "sleep": 300}]) + a = rig.adapter() + threading.Timer(1.0, a.cancel).start() + with pytest.raises(AdapterCancelled): + list(a.run_turn(turn_input())) + pids = json.loads((rig.bin / "pids.json").read_text()) + time.sleep(0.5) + assert not _alive(pids["child"]) + + +def test_generator_close_cleans_up(root): + rig = Rig(root, [{"stdout": line({"type": "thread.started", "thread_id": THREAD}), "spawn_child": True, + "sleep": 300}]) + a = rig.adapter() + gen = a.run_turn(turn_input()) + for ev in gen: + if ev.channel == "provider": + break + gen.close() # e.g. broker stopped consuming + pids = json.loads((rig.bin / "pids.json").read_text()) + time.sleep(0.5) + assert not _alive(pids["parent"]) and not _alive(pids["child"]) + + +# ------------------------------------------------------------ through the real broker + +def _broker(root, rig, model=MODEL): + fx = write_fixture(root / "fx", model=model) + cfg = load_config(fx["config"]) + from synaptic_tuner.experimental.weight_editor.ports import PortSet + ports = PortSet(rig.adapter(), FakeEffectExecutor(fx["effects"])) + return fx, EditorRun.create(cfg, ports, "run-codex-1") + + +def test_broker_end_to_end_synthetic(root): + patch = json.dumps({"tensor": "w.layer0", "deltas": [0.1, -0.1, 0.05]}) + t1 = stream(request_env("inspect_weights", {"tensor": "w.layer0"})) + t2 = stream(request_env("propose_patch", {"name": "edit-a", "tensor": "w.layer0", "patch": patch, + "justification": "small"})) + t3 = stream(final_env("patch", "req-0002")) + rig = Rig(root, [{"stdout": t1, "stderr": b"diag-1\n"}, {"stdout": t2}, {"stdout": t3}]) + fx, run = _broker(root, rig) + try: + summary = run.run() + finally: + run.close() + assert summary["status"] == "complete", summary + assert summary["capture_incomplete"] is False + raw = [json.loads(x) for x in (Path(summary["run_dir"]) / "provider" / "events.jsonl").read_text().splitlines()] + prov = b"".join(base64.b64decode(r["data"]["raw_b64"]) for r in raw if r["data"]["channel"] == "provider") + assert prov == t1 + t2 + t3 + errs = b"".join(base64.b64decode(r["data"]["raw_b64"]) for r in raw if r["data"]["channel"] == "client_stderr") + assert errs == b"diag-1\n" + effects = (fx["effects"] / "effects.log").read_text().splitlines() + assert [json.loads(x)["op"] for x in effects] == ["inspect_weights", "propose_patch"] + calls = rig.calls() + assert calls[0]["argv"][1] != "resume" and all(c["argv"][1] == "resume" for c in calls[1:]) + first = json.loads(base64.b64decode(calls[0]["stdin_b64"]))["messages"] + assert any("BROKER CATALOG" in m["content"] for m in first) + + +def test_broker_halts_without_effects_on_native_tool(root): + t1 = stream(request_env("inspect_weights", {"tensor": "w.layer0"}), + extra=[{"type": "item.completed", "item": {"id": "w", "type": "web_search", "query": "q"}}]) + rig = Rig(root, [{"stdout": t1}]) + fx, run = _broker(root, rig) + try: + summary = run.run() + finally: + run.close() + assert summary["status"] == "incomplete" and summary["halt"]["code"] == "adapter_failure" + assert summary["capture_incomplete"] is True + assert not (fx["effects"] / "effects.log").exists() + + +def test_broker_halts_without_returned_model(root): + rig = Rig(root, [{"stdout": stream(request_env("inspect_weights", {"tensor": "w.layer0"}), model=None)}]) + fx, run = _broker(root, rig) + try: + summary = run.run() + finally: + run.close() + assert summary["status"] == "incomplete" + assert not (fx["effects"] / "effects.log").exists() diff --git a/tests/experimental/weight_editor/test_crash_and_reconciliation.py b/tests/experimental/weight_editor/test_crash_and_reconciliation.py new file mode 100644 index 000000000..1df3cc2cc --- /dev/null +++ b/tests/experimental/weight_editor/test_crash_and_reconciliation.py @@ -0,0 +1,179 @@ +"""Real SIGKILL at the dispatch boundary, reconciliation and no duplicate effects.""" + +from __future__ import annotations + +import json + +import pytest + +from .conftest import QUERY12, final, of_type, req, script, types + +GPU_LIMITS = {"gpu_units": 10, "examples": 10} + + +def fixture_with_query(make, **kw): + # turn 1 issues one 2-item "GPU" query; turn 2 freezes no_edit after seeing the result + return make(limits=GPU_LIMITS, script=script([QUERY12], [final()]), **kw) + + +def kill_at(fx, stage, run_id="r1", op="query_development"): + proc = fx.popen("run", run_id, pause_at=stage, pause_op=op) + fx.wait_marker(stage, proc) + fx.sigkill(proc) + return proc + + +def dispatch_id(fx): + return of_type(fx.journal(), "dispatch_intent")[0]["data"]["dispatch_id"] + + +def test_sigkill_after_effect_before_receipt_reconciles_complete_without_duplicate(make): + fx = fixture_with_query(make) + kill_at(fx, "after_effect") + assert len(fx.effect_lines()) == 1 # the effect really happened before the kill + code, out, _ = fx.cli("verify", "--run-dir", fx.run_dir()) + assert code == 0 and out["status"] == "incomplete" and out["unresolved_dispatches"] == [dispatch_id(fx)] + assert not (fx.run_dir() / "terminal_manifest.json").exists() + # the write-ahead intent and the reservation survived; no result was recorded + assert types(fx.journal())[-1] == "dispatch_intent" + code, out, _ = fx.resume() + assert code == 0 and out["status"] == "complete" + assert len(fx.effect_lines()) == 1 # no duplicate GPU effect + result = of_type(fx.journal(), "dispatch_result")[0]["data"] + assert result["via"] == "reconciliation" + assert [r["data"]["status"] for r in of_type(fx.journal(), "reconcile_result")] == ["complete"] + gpu = out["budget"]["gpu_units"] + assert gpu["committed"] == 1.0 and gpu["reserved_outstanding"] == 0 # charged exactly once, not lost + assert fx.cli("verify", "--run-dir", fx.run_dir())[0] == 0 + # the model saw the real result on the next turn + second = of_type(fx.journal(), "turn_start")[1]["data"]["messages"] + assert json.loads(next(m["content"] for m in second if m["role"] == "tool"))["status"] == "ok" + + +def test_sigkill_before_executor_started_is_proven_unstarted_and_runs_exactly_once(make): + fx = fixture_with_query(make) + kill_at(fx, "before_started") + assert fx.effect_lines() == [] + code, out, _ = fx.resume() + assert code == 0 and out["status"] == "complete" + assert len(fx.effect_lines()) == 1 + j = fx.journal() + intents = of_type(j, "dispatch_intent") + assert [(i["data"]["attempt"], i["data"]["basis"]) for i in intents] == [ + (1, "initial"), (2, "proven_unstarted_reconciliation")] + assert intents[0]["data"]["dispatch_id"] == intents[1]["data"]["dispatch_id"] # stable id across resume + rec = of_type(j, "reconcile_result")[0]["data"] + assert rec["status"] == "unstarted" and rec["authority"]["dispatch_id"] == dispatch_id(fx) + assert out["budget"]["gpu_units"]["committed"] == 1.0 and out["budget"]["gpu_units"]["reserved_outstanding"] == 0 + + +@pytest.mark.parametrize("stage,effects_after_kill", [("after_started", 0), ("before_done", 1)]) +def test_sigkill_with_unknown_outcome_never_reexecutes_and_keeps_the_charge(make, stage, effects_after_kill): + fx = fixture_with_query(make) + kill_at(fx, stage) + assert len(fx.effect_lines()) == effects_after_kill + for attempt in range(3): # repeated resumes stay safe + code, out, _ = fx.resume() + assert code == 3 and out["status"] == "incomplete" and out["halt"]["code"] == "reconciliation_needed" + assert len(fx.effect_lines()) == effects_after_kill # no implicit retry, ever + assert out["dispatches"] == {dispatch_id(fx): "intent"} + gpu = out["budget"]["gpu_units"] + assert gpu["committed"] == 0 and gpu["reserved_outstanding"] == 1.0 # charge held, never reset or released + assert len(of_type(fx.journal(), "dispatch_intent")) == 1 + assert [r["data"]["status"] for r in of_type(fx.journal(), "reconcile_result")] == ["unknown"] * 3 + code, out, _ = fx.cli("verify", "--run-dir", fx.run_dir()) + assert code == 0 and out["unresolved_dispatches"] == [dispatch_id(fx)] and out["status"] == "incomplete" + assert not (fx.run_dir() / "final_selection.json").exists() + assert "reconciliation_needed" in "".join(r["data"]["code"] for r in of_type(fx.journal(), "run_halted")) + # reservation was never exceeded: a further query cannot spend the held units + assert out["budget"]["gpu_units"]["charged"] == 1.0 + + +def test_executor_exception_after_effect_is_ambiguous_and_never_retried(make): + fx = fixture_with_query(make) + code, out, _ = fx.run(fault="raise_after_effect") + assert code == 3 and out["halt"]["code"] == "reconciliation_needed" + assert len(fx.effect_lines()) == 1 + err = of_type(fx.journal(), "dispatch_error")[0]["data"] + assert err["outcome"] == "unknown" and err["category"] == "RuntimeError" + code, out, _ = fx.resume() # same executor, fault removed + assert code == 3 and len(fx.effect_lines()) == 1 # reconcile saw started-but-not-done -> unknown + assert out["budget"]["gpu_units"]["reserved_outstanding"] == 1.0 + + +def test_executor_rejection_before_effect_releases_the_reservation_and_continues(make): + fx = fixture_with_query(make) + code, out, _ = fx.run(fault="reject_execute") + assert code == 0 and fx.effect_lines() == [] + err = of_type(fx.journal(), "dispatch_error")[0]["data"] + assert err["outcome"] == "not_started" + assert out["budget"]["gpu_units"]["reserved_outstanding"] == 0 and out["budget"]["gpu_units"]["committed"] == 0 + assert out["dispatches"] == {dispatch_id(fx): "rejected"} + + +def test_executor_write_outside_artifact_namespace_is_refused_and_creates_nothing(make): + fx = fixture_with_query(make) + base_before = {p: p.read_bytes() for p in fx.capsule.rglob("*") if p.is_file()} + code, out, _ = fx.run(fault="escape_write") + assert code == 3 # boundary violation leaves outcome unknown by design + err = of_type(fx.journal(), "dispatch_error")[0]["data"] + assert err["boundary_violation"] is True and err["category"] == "WriteBoundaryViolation" + assert not list(fx.paths["root"].rglob("escape.txt")) + assert {p: p.read_bytes() for p in fx.capsule.rglob("*") if p.is_file()} == base_before # base untouched + assert fx.effect_lines() == [] + + +def test_sigkill_mid_turn_discards_retained_requests_and_never_claims_full_capture(make): + fx = make(limits=GPU_LIMITS, script=script( + [{"type": "session_started", "session_id": "S1", "model": "fake-editor-1"}, QUERY12, {"self_sigkill": True}, + req("inspect_weights", tensor="w.layer0")], + [final()], [final()])) + code, out, proc = fx.run() + assert code == -9 # the adapter really SIGKILLed the process mid-turn + assert len(fx.raw()) == 2 and fx.effect_lines() == [] + assert "dispatch_intent" not in types(fx.journal()) + code, out, _ = fx.resume() + assert code == 6 and out["status"] == "complete" and not out["capture_qualification"]["qualified"] + j = fx.journal() + ends = of_type(j, "turn_end") + assert ends[0]["data"] == {"turn_id": "turn-0001", "status": "interrupted", "reason": "process_crash_or_kill"} + assert fx.effect_lines() == [] # interrupted requests have no authority + assert of_type(j, "turn_start")[1]["data"]["resumed"] is True + assert out["budget"].get("gpu_units", {}).get("committed", 0) == 0 + assert fx.cli("verify", "--run-dir", fx.run_dir())[0] == 6 + + +def test_raw_event_fsynced_but_not_yet_normalized_is_recovered_not_lost(make): + from synaptic_tuner.experimental.weight_editor.journal import HashChainLog, genesis_prev + import base64, json as _json + from synaptic_tuner.experimental.weight_editor.canon import sha256_hex + + fx = make(limits=GPU_LIMITS, script=script( + [{"type": "session_started", "session_id": "S1", "model": "fake-editor-1"}, {"self_sigkill": True}], + [final()], [final()])) + assert fx.run()[0] == -9 + manifest = _json.loads((fx.run_dir() / "manifest.json").read_text()) + # simulate a crash between the raw-log fsync and the journal append of one more provider event + raw_log = HashChainLog(fx.run_dir() / "provider" / "events.jsonl", "r1", + genesis_prev(manifest["binding_digest"], "provider")) + ev = _json.dumps({"type": "tool_request", "operation": "inspect_weights", "arguments": {"tensor": "w.layer1"}}).encode() + raw_log.append("provider_raw", {"turn_id": "turn-0001", "raw_b64": base64.b64encode(ev).decode(), + "raw_sha256": sha256_hex(ev), "size": len(ev)}) + raw_log.close() + code, out, _ = fx.resume() + assert code == 6 + recovered = [e for e in of_type(fx.journal(), "provider_event") if e["data"]["recovered_from_raw"]] + assert len(recovered) == 1 and recovered[0]["data"]["kind"] == "request" + assert fx.effect_lines() == [] + + +def test_single_writer_lock_refuses_a_second_writer_and_dies_with_the_process(make): + fx = fixture_with_query(make) + proc = fx.popen("run", "r1", pause_at="after_started", pause_op="query_development") + fx.wait_marker("after_started", proc) + code, out, _ = fx.resume() # second writer while the first is alive + assert code == 1 and out["error"]["code"] == "lock_held" + assert fx.effect_lines() == [] + fx.sigkill(proc) + code, out, _ = fx.resume() # lock released by the kernel on SIGKILL + assert code == 3 and out["halt"]["code"] == "reconciliation_needed" diff --git a/tests/experimental/weight_editor/test_integrity_and_drift.py b/tests/experimental/weight_editor/test_integrity_and_drift.py new file mode 100644 index 000000000..6381d0cce --- /dev/null +++ b/tests/experimental/weight_editor/test_integrity_and_drift.py @@ -0,0 +1,248 @@ +"""Tamper evidence, audited tail recovery and immutable run binding.""" + +from __future__ import annotations + +import json + +import pytest + +from .conftest import final, of_type, patch, req, script + +TWO_STEP = None + + +def halted_fixture(make, **kw): + """Run that stops after turn 2 on a provider timeout so it can be resumed.""" + fx = make(script=script([req("inspect_weights", tensor="w.layer0"), patch("p1")], + {"events": [], "fail": "timeout"}, + [final("patch", "req-0002")]), **kw) + code, out, _ = fx.run() + assert code == 4 and out["halt"]["code"] == "adapter_failure" + return fx + + +def complete_fixture(make): + fx = make(script=script([req("inspect_weights", tensor="w.layer0"), patch("p1")], [final("patch", "req-0002")])) + assert fx.run()[0] == 0 + return fx + + +def jfile(fx): + return fx.run_dir() / "journal" / "events.jsonl" + + +def verify(fx, run_dir=None): + return fx.cli("verify", "--run-dir", run_dir or fx.run_dir()) + + +def test_clean_run_verifies(make): + fx = complete_fixture(make) + code, out, _ = verify(fx) + assert code == 0 and out["ok"] and out["problems"] == [] + + +def flip(path, needle, repl): + data = path.read_bytes() + assert needle in data + path.write_bytes(data.replace(needle, repl, 1)) + + +def _drop_line(fx): + lines = jfile(fx).read_bytes().split(b"\n") + del lines[5] + jfile(fx).write_bytes(b"\n".join(lines)) + + +def _swap_lines(fx): + lines = jfile(fx).read_bytes().split(b"\n") + lines[4], lines[5] = lines[5], lines[4] + jfile(fx).write_bytes(b"\n".join(lines)) + + +def _truncate_before_terminal(fx): + lines = jfile(fx).read_bytes().split(b"\n") + jfile(fx).write_bytes(b"\n".join(lines[:-2]) + b"\n") # clean record boundary, valid prefix + + +def _forge_digest(fx): + lines = jfile(fx).read_text().split("\n") + rec = json.loads(lines[6]) + rec["data"]["tampered"] = True # consistent JSON, digest not recomputed + lines[6] = json.dumps(rec, sort_keys=True, separators=(",", ":")) + jfile(fx).write_text("\n".join(lines)) + + +@pytest.mark.parametrize("tamper,code", [ + (lambda fx: flip(jfile(fx), b"synthetic reason for p1", b"synthetic reason for p2"), "journal_corrupt"), + (_drop_line, "journal_corrupt"), + (_swap_lines, "journal_corrupt"), + (_forge_digest, "journal_corrupt"), + (lambda fx: jfile(fx).write_bytes(jfile(fx).read_bytes().replace(b",", b", ", 1)), "journal_corrupt"), # whitespace + (lambda fx: flip(fx.run_dir() / "provider" / "events.jsonl", b'"size":', b'"size": '), "journal_corrupt"), + (_truncate_before_terminal, "journal_truncated_before_terminal"), + (lambda fx: flip(fx.run_dir() / "manifest.json", b'"fake-editor-1"', b'"other-editor-1"'), "manifest_tampered"), +]) +def test_chain_tampering_fails_closed(make, tamper, code): + fx = complete_fixture(make) + tamper(fx) + exit_code, out, _ = verify(fx) + assert exit_code == 5 and out["ok"] is False + found = out["problems"][0]["code"] if "problems" in out else out["error"]["code"] + assert found == code, out + + +def test_raw_event_alteration_is_detected_through_the_normalized_journal(make): + fx = complete_fixture(make) + raw = fx.run_dir() / "provider" / "events.jsonl" + recs = [json.loads(x) for x in raw.read_text().splitlines()] + import base64 + recs[0]["data"]["raw_b64"] = base64.b64encode(b'{"type":"assistant_message","text":"forged"}').decode() + raw.write_text("\n".join(json.dumps(r, sort_keys=True, separators=(",", ":")) for r in recs) + "\n") + assert verify(fx)[0] == 5 + + +def test_artifact_receipt_and_final_selection_edits_are_detected(make): + for victim in ("artifact", "receipt", "final", "terminal", "artifacts_manifest"): + fx = complete_fixture(make) + d = fx.run_dir() + target = { + "artifact": next(d.glob("artifacts/dsp-*/p1.patch.json")), + "receipt": d / "requests" / "req-0002" / "receipt.json", + "final": d / "final_selection.json", + "terminal": d / "terminal_manifest.json", + "artifacts_manifest": d / "artifacts" / "manifest.json", + }[victim] + target.write_bytes(target.read_bytes() + b" ") + code, out, _ = verify(fx) + assert code == 5 and not out["ok"], victim + + +def test_partial_line_fails_closed_then_audited_recovery_quarantines_it(make): + fx = halted_fixture(make) + jf = jfile(fx) + good = jf.read_bytes() + partial = b'{"data":{"half":"written"},"digest":"abc' + jf.write_bytes(good + partial) + code, out, _ = verify(fx) + assert code == 5 and out["problems"][0]["code"] == "partial_tail" + code, out, _ = fx.resume() + assert code == 5 and out["error"]["code"] == "partial_tail" # default: fail closed, nothing deleted + assert jf.read_bytes() == good + partial + code, out, _ = fx.resume(extra=["--recover-partial-tail"]) + assert code == 6 and out["status"] == "complete" and not out["capture_qualification"]["qualified"] + rec = of_type(fx.journal(), "tail_recovery")[0]["data"] + q = fx.run_dir() / rec["quarantined_file"] + assert q.read_bytes() == partial # preserved byte-for-byte + assert rec["quarantined_bytes"] == len(partial) + from synaptic_tuner.experimental.weight_editor.canon import sha256_hex + assert rec["quarantined_sha256"] == sha256_hex(partial) + assert verify(fx)[0] == 6 + assert "Audited tail recovery" in (fx.run_dir() / "transcript.md").read_text() + + +def test_corruption_is_not_hidden_by_tail_recovery(make): + fx = halted_fixture(make) + flip(jfile(fx), b"inspect_weights", b"inspect_weightz") + code, out, _ = fx.resume(extra=["--recover-partial-tail"]) + assert code == 5 and out["error"]["code"] == "journal_corrupt" + assert not (fx.run_dir() / "quarantine").exists() + + +# ---------------------------------------------------------------- drift + + +def refused_without_effects(fx, resume_result, code_name): + code, out, _ = resume_result + assert code in (1, 5), out + assert out["error"]["code"] == code_name, out + return out["error"] + + +def snapshot(fx): + return (len(fx.effect_lines()), len(of_type(fx.journal(), "turn_start")), len(fx.raw())) + + +def test_config_drift_refuses_resume_and_is_audited(make): + fx = halted_fixture(make) + snap = snapshot(fx) + cfg = json.loads(fx.config.read_text()) + cfg["final_choice"]["allow_no_edit"] = False + fx.config.write_text(json.dumps(cfg)) + out = refused_without_effects(fx, fx.resume(), "identity_drift") + assert "config_sha256" in out["components"] + assert snapshot(fx) == snap + refusal = of_type(fx.journal(), "resume_refused")[-1]["data"] + assert refusal["reason"] == "identity_drift" and "config_sha256" in refusal["components"] + + +def test_whitespace_only_config_edit_still_refuses_because_bytes_are_bound(make): + fx = halted_fixture(make) + fx.config.write_text(fx.config.read_text() + "\n\n") + refused_without_effects(fx, fx.resume(), "identity_drift") + + +def test_model_selection_drift_is_refused_never_substituted(make): + fx = halted_fixture(make) + snap = snapshot(fx) + refused_without_effects(fx, fx.resume(model="other-model"), "model_mismatch") + assert snapshot(fx) == snap + cfg = json.loads(fx.config.read_text()) + cfg["model"]["model"] = "other-model" + fx.config.write_text(json.dumps(cfg)) + refused_without_effects(fx, fx.resume(model="other-model"), "identity_drift") + assert snapshot(fx) == snap + + +def test_model_settings_drift_is_refused(make): + fx = halted_fixture(make) + cfg = json.loads(fx.config.read_text()) + cfg["model"]["settings"]["effort"] = "different" + fx.config.write_text(json.dumps(cfg)) + refused_without_effects(fx, fx.resume(), "identity_drift") + + +def test_capsule_byte_drift_is_refused_before_any_port_exists(make): + fx = halted_fixture(make) + snap = snapshot(fx) + t = fx.capsule / "tensors" / "w.layer0.json" + t.write_text(json.dumps({"values": [9, 9, 9]})) + refused_without_effects(fx, fx.resume(), "capsule_hash_mismatch") + assert snapshot(fx) == snap + assert of_type(fx.journal(), "resume_refused")[-1]["data"]["reason"] == "config_or_capsule_invalid" + + +def test_capsule_manifest_drift_is_refused(make): + fx = halted_fixture(make) + p = fx.paths["capsule_manifest"] + p.write_text(p.read_text() + "\n") + refused_without_effects(fx, fx.resume(), "identity_drift") + + +def test_supplied_source_runtime_binding_is_part_of_identity(make, workdir): + fx = make(script=script([req("inspect_weights", tensor="w.layer0")], {"events": [], "fail": "timeout"}, [final()])) + b1, b2 = workdir / "b1.json", workdir / "b2.json" + b1.write_text(json.dumps({"tuner_commit": "aaa", "runtime_lock_sha256": "1" * 64})) + b2.write_text(json.dumps({"tuner_commit": "bbb", "runtime_lock_sha256": "1" * 64})) + base = ["--config", fx.config, "--run-id", "r1", *fx.ports_args()] + assert fx.cli("run", *base, "--binding-file", b1)[0] == 4 + res = fx.cli("resume", *base, "--binding-file", b2) + assert res[0] == 1 and res[1]["error"]["code"] == "identity_drift" and res[1]["error"]["components"] == ["supplied"] + assert fx.cli("resume", *base)[1]["error"]["code"] == "identity_drift" # absent binding also differs + assert fx.cli("resume", *base, "--binding-file", b1)[0] == 6 + + +def test_port_implementation_drift_is_refused(make, workdir): + fx = halted_fixture(make) + script_path = fx.paths["script"] + doc = json.loads(script_path.read_text()) + doc["turns"][2]["events"][0]["rationale"] = "changed model behavior" + script_path.write_text(json.dumps(doc)) # adapter identity binds the script bytes + out = refused_without_effects(fx, fx.resume(), "identity_drift") + assert "adapter" in out["components"] + + +def test_resume_under_identical_bytes_succeeds(make): + fx = halted_fixture(make) + code, out, _ = fx.resume() + assert code == 6 and out["status"] == "complete" and out["resumes"] == 1 + assert len(fx.effect_lines()) == 2 diff --git a/tests/experimental/weight_editor/test_recording_and_replay.py b/tests/experimental/weight_editor/test_recording_and_replay.py new file mode 100644 index 000000000..cb1c818f1 --- /dev/null +++ b/tests/experimental/weight_editor/test_recording_and_replay.py @@ -0,0 +1,245 @@ +"""Exact raw retention, normalized journal, boundaries, receipts and independent replay.""" + +from __future__ import annotations + +import base64 +import json +import re +import shutil + +import pytest + +from synaptic_tuner.experimental.weight_editor.canon import sha256_hex + +from .conftest import BAD_PATCH, OK_PATCH, QUERY12, final, of_type, patch, req, script, types + +ODD_RAW = '{"type":"assistant_message", "text":"spacing\\u00e9 \\n kept"}' # odd whitespace/escapes +MALFORMED = '{"type": "assistant_message", "text": ' # truncated JSON +FUTURE = '{"type":"future_event","payload":{"k":[1,2,3]}}' +BINARY = b"\xff\xfe\x00 not utf8" + + +def test_exact_raw_events_and_unknown_events_are_retained(make): + fx = make(script=script( + [{"raw": ODD_RAW}, {"raw": MALFORMED}, {"raw": FUTURE}, {"raw_b64": base64.b64encode(BINARY).decode()}, + {"type": "reasoning_summary", "text": "visible summary only"}, req("inspect_weights", tensor="w.layer0")], + [final()])) + code, out, _ = fx.run() + assert code == 4 and out["halt"]["code"] == "capture_incomplete" + assert fx.effect_lines() == [] + code, out, _ = fx.resume() + assert code == 6 and not out["capture_qualification"]["qualified"] + raw = fx.raw() + emitted = [ODD_RAW.encode(), MALFORMED.encode(), FUTURE.encode(), BINARY] + assert [base64.b64decode(r["data"]["raw_b64"]) for r in raw[:4]] == emitted # byte-exact + assert all(r["data"]["raw_sha256"] == sha256_hex(base64.b64decode(r["data"]["raw_b64"])) for r in raw) + events = of_type(fx.journal(), "provider_event") + kinds = [e["data"]["kind"] for e in events] + assert kinds[:5] == ["message", "unknown", "unknown", "unknown", "reasoning_summary"] + for e in events[1:4]: + assert e["data"]["capture"]["complete"] is False and e["data"]["raw"]["seq"] in (2, 3, 4) + assert out["unknown_events"] == 3 and out["capture_incomplete"] is True + term = json.loads((fx.run_dir() / "terminal_manifest.json").read_text()) + assert term["capture_incomplete"] is True and term["hidden_reasoning_captured"] is False + text = (fx.run_dir() / "transcript.md").read_text() + assert "UNKNOWN/UNPARSED EVENT" in text and FUTURE in text and "visible summary only" in text + assert "base64] " + base64.b64encode(BINARY).decode() in text + + +def test_model_visible_messages_and_provider_metadata_are_recorded(make): + fx = make(script=script( + [{"type": "session_started", "session_id": "S1", "model": "fake-editor-1"}, + {"type": "usage", "input_tokens": 12, "output_tokens": 3}, + req("inspect_weights", tensor="w.layer0"), {"type": "turn_finished", "finish_reason": "tool_use"}], + [final()])) + assert fx.run()[0] == 0 + j = fx.journal() + starts = of_type(j, "turn_start") + assert starts[0]["data"]["messages"][0] == {"role": "system", "content": "Synthetic editor task: propose a small safe edit.\n"} + assert starts[0]["data"]["messages"][-1]["content"].startswith("BROKER CATALOG") + result = of_type(j, "dispatch_result")[0]["data"]["message"] + assert starts[1]["data"]["messages"] == [result] # exactly what the model next saw + assert starts[1]["data"]["session_id"] == "S1" + payloads = {e["data"]["kind"]: e["data"]["payload"] for e in of_type(j, "provider_event")} + assert payloads["usage"]["output_tokens"] == 3 and payloads["finish"]["finish_reason"] == "tool_use" + reg = of_type(j, "run_registered")[0]["data"] + assert reg["model_requested"] == {"provider": "fake", "model": "fake-editor-1", "settings": {"effort": "fixture"}} + + +def test_returned_model_identity_violation_halts_and_discards_that_turns_requests(make): + fx = make(script=script( + [{"type": "session_started", "session_id": "S1", "model": "a-different-model"}, + req("inspect_weights", tensor="w.layer0")], [final()])) + code, out, _ = fx.run() + assert code == 4 and out["halt"]["code"] == "model_drift" + assert fx.effect_lines() == [] + assert [r["data"]["reason"] for r in of_type(fx.journal(), "request_denied")] == ["model_drift"] + + +@pytest.mark.parametrize("fail,cls", [("cancelled", "cancelled"), ("timeout", "timeout"), ("provider_error", "provider_error")]) +def test_adapter_failures_are_recorded_halt_and_are_not_success(make, fail, cls): + fx = make(script=script( + [req("inspect_weights", tensor="w.layer0")], + {"events": [{"type": "assistant_message", "text": "partial before failure"}], "fail": fail}, + [final()])) + code, out, _ = fx.run() + assert code == 4 and out["status"] == "incomplete" and out["halt"]["code"] == "adapter_failure" + assert not (fx.run_dir() / "terminal_manifest.json").exists() + err = of_type(fx.journal(), "adapter_error")[0]["data"] + assert err["classification"] == cls + assert any(r["data"]["kind"] == "message" for r in of_type(fx.journal(), "provider_event")) # partial traffic kept + code, out, _ = fx.resume() # explicit operator resume starts a fresh, flagged turn + assert code == 6 and not out["capture_qualification"]["qualified"] + assert [s["data"]["resumed"] for s in of_type(fx.journal(), "turn_start")] == [False, False, True] + assert len(fx.effect_lines()) == 1 + + +def test_final_assistant_text_alone_is_never_success(make): + fx = make(script=script([{"type": "assistant_message", "text": "I am done, the edit is great"}, + {"type": "turn_finished", "finish_reason": "stop"}])) + code, out, _ = fx.run() + assert code == 4 and out["status"] == "incomplete" and out["halt"]["code"] == "model_ended_without_choice" + assert not (fx.run_dir() / "final_selection.json").exists() + assert not (fx.run_dir() / "terminal_manifest.json").exists() + assert fx.cli("verify", "--run-dir", fx.run_dir())[1]["status"] == "incomplete" + + +def test_handoff_and_compaction_capsules_are_captured_exactly(make): + cap = {"summary": "synthetic compaction", "continuation_offset": 7, "kept": ["a", "b"]} + fx = make(script=script( + [{"type": "session_started", "session_id": "S1", "model": "fake-editor-1"}, + {"type": "handoff", "new_session_id": "S2", "capsule": cap}, + {"type": "truncation", "capsule": {"dropped_messages": 4}, "new_session_id": "S2"}, + req("inspect_weights", tensor="w.layer0")], [final()])) + assert fx.run()[0] == 4 + assert fx.resume()[0] == 6 + j = fx.journal() + hs = of_type(j, "handoff") + assert hs[0]["data"]["capsule"] == cap and hs[0]["data"]["from_session"] == "S1" and hs[0]["data"]["to_session"] == "S2" + assert hs[1]["data"]["kind"] == "truncation" + starts = of_type(j, "turn_start") + assert starts[1]["data"]["session_id"] == "S2" + ctx = [m["content"] for m in starts[1]["data"]["messages"]] + assert any(c.startswith("HANDOFF CAPSULE") and '"continuation_offset":7' in c for c in ctx) + assert any(c.startswith("TRUNCATION CAPSULE") for c in ctx) + + +def test_valid_and_invalid_patch_receipts_remain_in_the_ledger_and_only_valid_is_selectable(make): + fx = make(script=script( + [patch("good"), patch("bad", BAD_PATCH), patch("wrong", json.dumps({"tensor": "w.layer1", "deltas": [0.1]})), + patch("nan", '{"tensor": "w.layer0", "deltas": [NaN]}')], + [final("patch", "req-0002", "choose the oversized one")], # invalid -> must be refused + [final("patch", "req-0001", "choose the valid one")])) + code, out, _ = fx.run() + assert code == 0 + statuses = {r["data"]["request_id"]: r["data"]["receipt"]["status"] for r in of_type(fx.journal(), "dispatch_result")} + assert statuses == {"req-0001": "ok", "req-0002": "invalid", "req-0003": "invalid", "req-0004": "invalid"} + for rid in statuses: # each receipt and its artifact are retained on disk + doc = json.loads((fx.run_dir() / "requests" / rid / "receipt.json").read_text()) + assert doc["receipt"]["status"] == statuses[rid] + art = doc["artifacts"][0] + assert sha256_hex((fx.run_dir() / art["relpath"]).read_bytes()) == art["sha256"] + denied = of_type(fx.journal(), "final_choice_denied") + assert [d["data"]["reason"] for d in denied] == ["not_selectable"] + sel = json.loads((fx.run_dir() / "final_selection.json").read_text()) + assert sel["proposal_request_id"] == "req-0001" + frozen = of_type(fx.journal(), "final_patch_frozen")[0] + assert sel["journal_head"] == fx.journal()[frozen["seq"] - 2]["digest"] # record just before the freeze + assert sel["raw_head"] == fx.raw()[-1]["digest"] + assert sel["proposal_artifacts"][0]["sha256"] == sha256_hex(OK_PATCH.encode()) + assert sel["rationale"] == "choose the valid one" + assert sha256_hex((fx.run_dir() / "final_selection.json").read_bytes()) == frozen["data"]["final_selection_sha256"] + term = json.loads((fx.run_dir() / "terminal_manifest.json").read_text()) + assert term["final_selection_sha256"] == frozen["data"]["final_selection_sha256"] + assert term["frozen_record_digest"] == frozen["digest"] + + +def test_final_choice_requires_visible_rationale_and_known_choice(make): + fx = make(script=script( + [patch("good")], + [{"type": "final_choice", "choice": "patch", "proposal": "req-0001"}], + [{"type": "final_choice", "choice": "patch", "proposal": "req-0001", "rationale": "ok", "command": "x"}], + [{"type": "final_choice", "choice": "ship_it", "rationale": "ok"}], + [{"type": "final_choice", "choice": "no_edit", "proposal": "req-0001", "rationale": "ok"}], + [final("patch", "req-9999")], + [final("patch", "req-0001")])) + code, out, _ = fx.run() + assert code == 0 + assert [d["data"]["reason"] for d in of_type(fx.journal(), "final_choice_denied")] == [ + "rationale_required", "malformed", "malformed", "not_allowed", "not_selectable"] + + +def test_no_discovery_after_freeze_or_evaluation(make): + fx = make(script=script([patch("good")], [final("patch", "req-0001")], [QUERY12])) + assert fx.run()[0] == 0 + turns = len(of_type(fx.journal(), "turn_start")) + code, out, _ = fx.resume() # idempotent on a complete run; the model is not consulted + assert code == 0 and out["status"] == "complete" and len(of_type(fx.journal(), "turn_start")) == turns + assert fx.cli("advance", "--run-dir", fx.run_dir(), "--to", "closed", "--reference", "x")[1]["error"]["code"] == "bad_transition" + anchor = fx.paths["root"] / "freeze-anchor.json" + assert fx.cli("anchor", "--run-dir", fx.run_dir(), "--output", anchor)[0] == 0 + code, out, _ = fx.cli("advance", "--run-dir", fx.run_dir(), "--to", "independent_evaluation", "--reference", "eval-lane-1", "--anchor-file", anchor) + assert code == 0 and out["phase"] == "independent_evaluation" + code, out, _ = fx.resume() + assert code == 1 and out["error"]["code"] == "phase_closed" + assert fx.effect_lines().__len__() == 1 and len(of_type(fx.journal(), "turn_start")) == turns + assert types(fx.journal())[-1] == "resume_refused" + assert fx.cli("verify", "--run-dir", fx.run_dir())[0] == 0 + assert fx.cli("advance", "--run-dir", fx.run_dir(), "--to", "closed", "--reference", "done", "--anchor-file", anchor)[0] == 0 + + +def test_advance_refuses_an_incomplete_run(make): + fx = make(script=script([{"type": "assistant_message", "text": "no choice"}])) + assert fx.run()[0] == 4 + code, out, _ = fx.cli("advance", "--run-dir", fx.run_dir(), "--to", "independent_evaluation", "--reference", "x") + assert code == 1 and out["error"]["code"] == "bad_transition" + + +def test_independent_replay_links_exact_code_tool_output_and_artifacts(make, workdir): + code_with_fences = json.dumps({"tensor": "w.layer0", "deltas": [0.1], "note": "```python\nprint(1)\n```"}) + fx = make(script=script( + [req("inspect_weights", tensor="w.layer0"), patch("edit-a", code_with_fences)], + [final("patch", "req-0002")])) + assert fx.run()[0] == 0 + # Move the retained run elsewhere and delete the original inputs: replay must need nothing else. + moved = workdir / "moved-run" + shutil.copytree(fx.run_dir(), moved) + shutil.rmtree(fx.paths["root"]) + code, out, _ = fx.cli("verify", "--run-dir", moved) + assert code == 0 and out["ok"] and out["status"] == "complete" + exported = workdir / "export.md" + code, out, _ = fx.cli("replay", "--run-dir", moved, "--output", exported) + assert code == 0 + text = exported.read_text() + assert text == (moved / "transcript.md").read_text() + # exact code fragment appears inside a fence longer than any backtick run in it + fence = re.search(r"Argument `patch` \(exact text\):\n(`{4,})\n(.*?)\n\1\n", text, re.S) + assert fence and fence.group(2) == code_with_fences + # exact tool output as shown to the model + journal = [json.loads(x) for x in (moved / "journal" / "events.jsonl").read_text().splitlines()] + results = of_type(journal, "dispatch_result") + for r in results: + assert r["data"]["message"]["content"] in text + # artifact link resolves to bytes with the printed sha256 + m = re.search(r"- Artifact \[(artifacts/dsp-[0-9a-f]+/edit-a\.patch\.json)\]\(\1\) sha256 `([0-9a-f]{64})`", text) + assert m and sha256_hex((moved / m.group(1)).read_bytes()) == m.group(2) + assert (moved / m.group(1)).read_text() == code_with_fences + # receipt file linked, and raw bytes shown match the retained raw log + assert "requests/req-0002/receipt.json" in text + raw = [json.loads(x) for x in (moved / "provider" / "events.jsonl").read_text().splitlines()] + assert base64.b64decode(raw[0]["data"]["raw_b64"]).decode() in text + # the derived view never silently replaces an existing different file + exported.write_text("changed") + code, out, _ = fx.cli("replay", "--run-dir", moved, "--output", exported) + assert code == 1 and out["error"]["code"] == "output_exists" + assert fx.cli("replay", "--run-dir", moved, "--output", exported, "--force")[0] == 0 + assert exported.read_text() == text + + +def test_replay_reconstructs_observation_without_running_any_port(make, workdir): + fx = make(script=script([patch("p1")], [final("patch", "req-0001")])) + assert fx.run()[0] == 0 + effects_before = fx.effect_lines() + for _ in range(2): + assert fx.cli("replay", "--run-dir", fx.run_dir(), "--output", workdir / "t.md", "--force")[0] == 0 + assert fx.effect_lines() == effects_before diff --git a/tests/experimental/weight_editor/test_review_guards.py b/tests/experimental/weight_editor/test_review_guards.py new file mode 100644 index 000000000..2d9028fd4 --- /dev/null +++ b/tests/experimental/weight_editor/test_review_guards.py @@ -0,0 +1,266 @@ +"""Adversarial regression cases; operator actions still go through the real CLI.""" + +import json +import os +import shutil +import subprocess +import sys +import importlib.util + +import pytest + +from synaptic_tuner.experimental.weight_editor.canon import canonical_bytes, sha256_hex +from synaptic_tuner.experimental.weight_editor.journal import _digest +from synaptic_tuner.experimental.weight_editor.errors import PortError +from synaptic_tuner.experimental.weight_editor.ports import describe_port, source_package + +from .conftest import PKG, REPO, final, of_type, patch, req, script + + +@pytest.mark.parametrize("failure", ["provider_error", "timeout", "sigkill"]) +def test_failed_turn_cannot_execute_its_patch_or_freeze_on_resume(make, failure): + events = [patch("lost"), final("patch", "req-0001")] + turn = {"events": events, "fail": failure} + if failure == "sigkill": + events.append({"self_sigkill": True}) + fx = make(script=script(turn, [final()])) + assert fx.run()[0] == (-9 if failure == "sigkill" else 4) + assert not (fx.run_dir() / "final_selection.json").exists() + code, out, _ = fx.resume() + assert code == 6 and not out["capture_qualification"]["qualified"] + assert fx.effect_lines() == [] + assert json.loads((fx.run_dir() / "final_selection.json").read_text())["choice"] == "no_edit" + assert of_type(fx.journal(), "final_choice_denied")[0]["data"]["reason"] in { + "failed_turn", "interrupted_turn"} + anchor = fx.paths["root"] / "anchor.json" + assert fx.cli("anchor", "--run-dir", fx.run_dir(), "--output", anchor)[1]["error"]["code"] == "run_unqualified" + + +@pytest.mark.parametrize("event", ["usage", "turn_finished", "assistant_message"]) +def test_model_drift_is_detected_in_any_normalized_event(make, event): + fx = make(script=script([req("inspect_weights", tensor="w.layer0"), + {"type": event, "model": "other-model"}])) + code, out, _ = fx.run() + assert code == 4 and out["halt"]["code"] == "model_drift" + assert fx.effect_lines() == [] + + +def test_returned_identity_is_required_each_turn(make): + fx = make(script=script([req("inspect_weights", tensor="w.layer0")], + {"events": [patch("unsafe"), final()], "model_identity": False})) + code, out, _ = fx.run() + assert code == 4 and out["halt"]["code"] == "model_identity_unverified" + assert len(fx.effect_lines()) == 1 # only the earlier, identity-verified turn + assert not (fx.run_dir() / "final_selection.json").exists() + + +def test_no_session_retry_gets_instructions_and_catalog(make): + fx = make(script=script({"events": [], "fail": "timeout"}, [final()])) + assert fx.run()[0] == 4 + assert fx.resume()[0] == 6 + starts = of_type(fx.journal(), "turn_start") + assert starts[0]["data"]["messages"] == starts[1]["data"]["messages"] + assert starts[1]["data"]["messages"][-1]["content"].startswith("BROKER CATALOG") + + +def test_final_choice_requires_receipt_delivery(make): + fx = make(script=script([patch("first"), final("patch", "req-0001")], + [final("patch", "req-0001")])) + assert fx.run()[0] == 0 + denials = of_type(fx.journal(), "final_choice_denied") + assert [d["data"]["reason"] for d in denials] == ["receipt_not_seen"] + assert len(of_type(fx.journal(), "turn_start")) == 2 + + +def test_unmeasured_resource_limits_are_rejected(make): + fx = make(limits={"tokens": 1}, script=script([final()])) + code, out, _ = fx.run() + assert code == 1 and out["error"]["code"] == "unmeasured_resource" + assert fx.effect_lines() == [] + + +def test_dispatch_attempt_limit_is_checked_before_redispatch(make): + fx = make(limits={"dispatch_attempts": 1}, + script=script([req("query_development", items=["dev-001"])], [final()])) + proc = fx.popen("run", pause_at="before_started", pause_op="query_development") + fx.wait_marker("before_started", proc) + fx.sigkill(proc) + code, out, _ = fx.resume() + assert code == 4 and out["halt"]["code"] == "budget_exhausted" + assert out["budget"]["dispatch_attempts"]["committed"] == 1 + assert fx.effect_lines() == [] + + +def test_executor_exception_text_is_not_model_visible(make): + fx = make(script=script([patch("invalid", text=" ")], + [req("inspect_weights", tensor="w.layer0")], [final()])) + assert fx.run(fault="reject_execute")[0] == 0 + denial = of_type(fx.journal(), "request_denied")[0]["data"] + assert denial["detail"] == "patch must be non-empty" + assert json.loads(denial["message"]["content"])["detail"] == "operation rejected by executor validation" + rejection = of_type(fx.journal(), "dispatch_error")[0]["data"] + assert json.loads(rejection["message"]["content"])["detail"] == "operation rejected by executor" + + +def test_package_helper_changes_refuse_resume(make, tmp_path): + fx = make(script=script({"events": [], "fail": "timeout"}, [final()])) + consumer = tmp_path / "consumer" + shutil.copytree(REPO / "synaptic_tuner", consumer / "synaptic_tuner", + ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + + def call(verb): + proc = subprocess.run([sys.executable, "-m", PKG, verb, "--config", str(fx.config), + "--run-id", "r1", *map(str, fx.ports_args())], cwd=consumer, + env=dict(os.environ, PYTHONPATH=str(consumer)), capture_output=True, text=True) + return proc.returncode, json.loads(proc.stdout) + + assert call("run")[0] == 4 + helper = consumer / "synaptic_tuner/experimental/weight_editor/admission.py" + helper.write_bytes(helper.read_bytes() + b"\n# changed helper\n") + code, out = call("resume") + assert code == 1 and out["error"]["code"] == "identity_drift" + assert "broker_sources" in out["error"]["components"] + + +def _forge_rationale_and_rechain(run_dir): + """Demonstrate the documented limit of a mutable, internally chained directory.""" + journal = run_dir / "journal/events.jsonl" + records = [json.loads(x) for x in journal.read_text().splitlines()] + prev = records[0]["prev"] + frozen = None + final_sha = None + for rec in records: + data = rec["data"] + if rec["type"] == "provider_event" and data["kind"] == "final_choice": + data["payload"]["rationale"] = "FORGED rationale" + if rec["type"] == "final_choice_received": + data["payload"]["rationale"] = "FORGED rationale" + if rec["type"] == "final_patch_frozen": + path = run_dir / "final_selection.json" + sel = json.loads(path.read_text()) + sel.update(rationale="FORGED rationale", journal_head=prev) + blob = canonical_bytes(sel) + b"\n" + path.write_bytes(blob) + final_sha = sha256_hex(blob) + data.update(final_selection_sha256=final_sha, journal_head=prev) + if rec["type"] == "editor_terminal": + path = run_dir / "terminal_manifest.json" + terminal = json.loads(path.read_text()) + terminal.update(frozen_record_digest=frozen, final_selection_sha256=final_sha) + blob = canonical_bytes(terminal) + b"\n" + path.write_bytes(blob) + data["terminal_manifest_sha256"] = sha256_hex(blob) + rec["prev"] = prev + rec["digest"] = _digest(rec) + if rec["type"] == "final_patch_frozen": + frozen = rec["digest"] + prev = rec["digest"] + journal.write_bytes(b"".join(canonical_bytes(rec) + b"\n" for rec in records)) + + +def test_external_anchor_catches_full_rewrite_and_blocks_evaluation(make): + fx = make(script=script([final(rationale="ORIGINAL rationale")])) + assert fx.run()[0] == 0 + anchor = fx.paths["root"] / "anchor.json" + assert fx.cli("anchor", "--run-dir", fx.run_dir(), "--output", anchor)[0] == 0 + assert fx.cli("verify", "--run-dir", fx.run_dir(), "--anchor-file", anchor)[1]["external_anchor_checked"] + _forge_rationale_and_rechain(fx.run_dir()) + # Internal consistency alone is honestly labelled; independent custody detects this rewrite. + code, out, _ = fx.cli("verify", "--run-dir", fx.run_dir()) + assert code == 0 and "internal consistency" in out["integrity_scope"] + code, out, _ = fx.cli("verify", "--run-dir", fx.run_dir(), "--anchor-file", anchor) + assert code == 5 and out["problems"][0]["code"] == "external_anchor_mismatch" + out = fx.cli("advance", "--run-dir", fx.run_dir(), "--to", "independent_evaluation", + "--reference", "evaluation", "--anchor-file", anchor)[1] + assert out["error"]["code"] == "run_unqualified" + + +def test_advance_verifies_patch_artifacts(make): + fx = make(script=script([patch("p")], [final("patch", "req-0001")])) + assert fx.run()[0] == 0 + anchor = fx.paths["root"] / "anchor.json" + assert fx.cli("anchor", "--run-dir", fx.run_dir(), "--output", anchor)[0] == 0 + artifact = next(fx.run_dir().glob("artifacts/dsp-*/*.patch.json")) + artifact.write_text("changed patch") + code, out, _ = fx.cli("advance", "--run-dir", fx.run_dir(), "--to", "independent_evaluation", + "--reference", "evaluation", "--anchor-file", anchor) + assert code == 1 and out["error"]["code"] == "run_unqualified" + + +@pytest.mark.parametrize("relative", ["config.json", "capsule/manifest.json"]) +def test_retained_inputs_are_checked_against_binding(make, relative): + fx = make(script=script([final()])) + assert fx.run()[0] == 0 + path = fx.run_dir() / relative + path.write_bytes(path.read_bytes() + b" ") + code, out, _ = fx.cli("verify", "--run-dir", fx.run_dir()) + assert code == 5 and out["problems"][0]["code"] == "retained_input_mismatch" + + +def test_plain_or_dynamic_ports_are_refused(tmp_path, monkeypatch): + path = tmp_path / "plain_port.py" + path.write_text("class Plain:\n def identity(self): return {}\n") + spec = importlib.util.spec_from_file_location("plain_test_port", path) + module = importlib.util.module_from_spec(spec) + monkeypatch.setitem(sys.modules, "plain_test_port", module) + spec.loader.exec_module(module) + for obj in (module.Plain(), type("Dynamic", (), {"__module__": "nonexistent_port"})()): + with pytest.raises(PortError) as exc: + describe_port(obj) + assert exc.value.code == "unbound_port_source" + + +def test_source_binding_covers_package_import_initializers(): + from synaptic_tuner.experimental.weight_editor import broker + + sources = source_package(broker.__file__) + assert {"__init__.py", "_version.py", "experimental/__init__.py"} <= sources.keys() + + +@pytest.mark.parametrize("returned", ["wrong-model", ["wrong-model"], {"name": "wrong-model"}]) +def test_recovered_model_mismatch_belongs_to_interrupted_turn(make, returned): + import base64 + from synaptic_tuner.experimental.weight_editor.journal import HashChainLog, genesis_prev + + fx = make(script=script([{"self_sigkill": True}], [final()])) + assert fx.run()[0] == -9 + manifest = json.loads((fx.run_dir() / "manifest.json").read_text()) + raw = HashChainLog(fx.run_dir() / "provider/events.jsonl", "r1", + genesis_prev(manifest["binding_digest"], "provider")) + event = json.dumps({"type": "session_started", "model": returned}).encode() + raw.append("provider_raw", {"turn_id": "turn-0001", "raw_b64": base64.b64encode(event).decode(), + "raw_sha256": sha256_hex(event), "size": len(event)}) + raw.close() + code, out, _ = fx.resume() + assert code == 6 and out["status"] == "complete" + ends = of_type(fx.journal(), "turn_end") + assert ends[0]["data"]["model_drift"]["returned"] == returned + assert ends[1]["data"]["status"] == "complete" + + +def test_stray_artifact_blocks_evaluation_and_internal_anchor_is_not_external(make): + fx = make(script=script([final()])) + assert fx.run()[0] == 0 + anchor = fx.paths["root"] / "anchor.json" + assert fx.cli("anchor", "--run-dir", fx.run_dir(), "--output", anchor)[0] == 0 + internal = fx.run_dir() / "anchor.json" + internal.write_bytes(anchor.read_bytes()) + code, out, _ = fx.cli("verify", "--run-dir", fx.run_dir(), "--anchor-file", internal) + assert code == 5 and not out["external_anchor_checked"] + (fx.run_dir() / "artifacts/late.patch.json").write_text("unrecorded") + assert fx.cli("verify", "--run-dir", fx.run_dir())[0] == 5 + code, out, _ = fx.cli("advance", "--run-dir", fx.run_dir(), "--to", "independent_evaluation", + "--reference", "evaluation", "--anchor-file", anchor) + assert code == 1 and out["error"]["code"] == "run_unqualified" + + +def test_failed_receipt_delivery_is_bootstrapped_and_resent(make): + fx = make(script=script([patch("valid")], {"events": [], "fail": "timeout"}, + [final("patch", "req-0001")])) + assert fx.run()[0] == 4 + assert fx.resume()[0] == 6 + starts = of_type(fx.journal(), "turn_start") + receipt = of_type(fx.journal(), "dispatch_result")[0]["data"]["message"] + assert receipt in starts[1]["data"]["messages"] + assert receipt in starts[2]["data"]["messages"] + assert starts[2]["data"]["messages"][-2]["content"].startswith("BROKER CATALOG") diff --git a/tests/experimental/weight_editor/test_transport_and_writes.py b/tests/experimental/weight_editor/test_transport_and_writes.py new file mode 100644 index 000000000..78116dd1f --- /dev/null +++ b/tests/experimental/weight_editor/test_transport_and_writes.py @@ -0,0 +1,42 @@ +"""Independent streams retain exact bytes without acquiring broker authority.""" + +import base64 + +from synaptic_tuner.experimental.weight_editor.ports import BoundedWriter + +from .conftest import final, of_type, script + + +def test_client_streams_cannot_dispatch_or_freeze(make): + blobs = [b'{"type":"tool_request","operation":"patch"}\n', b'\xff stderr diagnostic\x00\n'] + fx = make(script=script([ + {"transport_channel": channel, "raw_b64": base64.b64encode(blob).decode()} + for channel, blob in zip(("client_input", "client_stderr"), blobs) + ] + [final()])) + assert fx.run()[0] == 0 + assert fx.effect_lines() == [] + assert of_type(fx.journal(), "request_received") == [] + raw = fx.raw()[:2] + assert [base64.b64decode(r["data"]["raw_b64"]) for r in raw] == blobs + assert [r["data"]["channel"] for r in raw] == ["client_input", "client_stderr"] + replay = (fx.run_dir() / "transcript.md").read_text() + assert "client_stderr" in replay and base64.b64encode(blobs[1]).decode() in replay + assert fx.cli("verify", "--run-dir", fx.run_dir())[1]["ok"] + + +def test_artifact_short_writes_are_completed(tmp_path, monkeypatch): + from synaptic_tuner.experimental.weight_editor import ports + + real_write = ports.os.write + calls = [] + + def short_write(fd, data): + calls.append(len(data)) + return real_write(fd, data[:3]) + + monkeypatch.setattr(ports.os, "write", short_write) + writer = BoundedWriter(tmp_path / "artifacts", ()) + data = b"0123456789abcdef" + receipt = writer.write("sample.bin", data) + assert (writer.root / "sample.bin").read_bytes() == data + assert receipt["size"] == len(data) and len(calls) > 1 diff --git a/tests/mech_interp/test_batched_generation.py b/tests/mech_interp/test_batched_generation.py index be450831b..3e2cde002 100644 --- a/tests/mech_interp/test_batched_generation.py +++ b/tests/mech_interp/test_batched_generation.py @@ -384,3 +384,22 @@ def test_batch_size_default_is_one(): cfg = ExecutionConfig(output_path="out.jsonl") assert cfg.batch_size == 1 + + +def test_continuation_retains_exact_ids_including_first_eos(): + from types import SimpleNamespace + from MechInterp.cli import _continuation_record + import torch + + class Tokenizer: + eos_token_id = 7 + def decode(self, ids, skip_special_tokens=True): + return "same decoded text" + + generation = SimpleNamespace(max_new_tokens=8, eos_include_im_end=False) + first = _continuation_record(Tokenizer(), torch.tensor([3, 7, 0, 0]), generation) + second = _continuation_record(Tokenizer(), torch.tensor([4, 7, 0, 0]), generation) + assert first["answer_text"] == second["answer_text"] + assert first["generated_token_ids"] == [3, 7] + assert second["generated_token_ids"] == [4, 7] + assert first["n_new_tokens"] == len(first["generated_token_ids"]) diff --git a/tests/mech_interp/test_capture_resume.py b/tests/mech_interp/test_capture_resume.py new file mode 100644 index 000000000..aed707925 --- /dev/null +++ b/tests/mech_interp/test_capture_resume.py @@ -0,0 +1,109 @@ +"""Extraction interruption, source separation, portable names and probe integrity.""" + +import json + +import pytest + +from MechInterp.cli import _load_activation_matrix +from MechInterp.extraction import PositionSpec, extract_rows +from MechInterp.extraction.persistence import safe_key +from tests.mech_interp.test_batched_generation import _build_tiny_model, _build_tiny_tokenizer + + +def run_capture(root, rows, *, model=None, **kwargs): + return extract_rows( + model or _build_tiny_model(), _build_tiny_tokenizer(), rows, + render_fn=lambda row: row["prompt"], content_end_fn=None, + spec=PositionSpec(families=["anchor"], layers=[1, 2]), + out_dir=root, forward_only=True, **kwargs, + ) + + +ROWS = [{"row_key": "source:one", "prompt": "hello world"}, + {"row_key": "source/two", "prompt": "world hello"}] + + +def test_interruption_resume_skips_durable_rows_and_matches_clean_capture(tmp_path): + model = _build_tiny_model() + original = model.forward + count = 0 + + def interrupted(*args, **kwargs): + nonlocal count + count += 1 + if count == 2: + raise RuntimeError("simulated interruption") + return original(*args, **kwargs) + + model.forward = interrupted + root = tmp_path / "resumed" + with pytest.raises(RuntimeError, match="interruption"): + run_capture(root, ROWS, model=model, resume=True, run_identity={"fixture": "v1"}) + assert len((root / "capture.runlog.jsonl").read_text().splitlines()) == 1 + assert not (root / "manifest.json").exists() + with pytest.raises(FileNotFoundError): + _load_activation_matrix(str(root), "anchor", [{"row_key": ROWS[0]["row_key"], "label": 0}]) + + count = 0 + model.forward = interrupted + manifest = run_capture(root, ROWS, model=model, resume=True, run_identity={"fixture": "v1"}) + assert count == 1 # the committed first row was never evaluated again + clean = run_capture(tmp_path / "clean", ROWS) + assert manifest == clean + for record in manifest["rows"]: + for info in record["capture_files"].values(): + assert (root / info["file"]).read_bytes() == (tmp_path / "clean" / info["file"]).read_bytes() + + +def test_resume_refuses_different_patch_inputs_or_source_and_corrupt_files(tmp_path): + root = tmp_path / "capture" + run_capture(root, ROWS, resume=True, run_identity={"model": "v1"}, manifest_extra={"weight_patch": None}) + for rows, identity, patch in ( + (ROWS, {"model": "v2"}, None), + ([{**ROWS[0], "prompt": "changed"}, ROWS[1]], {"model": "v1"}, None), + (ROWS, {"model": "v1"}, {"patch_digest": "different"}), + ): + with pytest.raises(RuntimeError, match="fingerprint mismatch"): + run_capture(root, rows, resume=True, run_identity=identity, manifest_extra={"weight_patch": patch}) + with pytest.raises(ValueError, match="non-empty"): + run_capture(root, ROWS) + artifact = next(root.glob("*.safetensors")) + artifact.write_bytes(b"corrupted") + with pytest.raises(ValueError, match="hash mismatch"): + run_capture(root, ROWS, resume=True, run_identity={"model": "v1"}, manifest_extra={"weight_patch": None}) + + +def test_probe_uses_manifest_and_checks_capture_bytes(tmp_path): + root = tmp_path / "capture" + manifest = run_capture(root, ROWS) + labels = [{"row_key": row["row_key"], "label": i} for i, row in enumerate(ROWS)] + labels.append({"row_key": "stray", "label": 1}) + (root / "stray__anchor.safetensors").write_bytes(b"not a capture") + matrices, y = _load_activation_matrix(str(root), "anchor", labels) + assert set(matrices) == {1, 2} + assert y.tolist() == [0, 1] + (root / manifest["rows"][0]["capture_files"]["anchor"]["file"]).write_bytes(b"tampered") + with pytest.raises(ValueError, match="hash mismatch"): + _load_activation_matrix(str(root), "anchor", labels) + + +def test_portable_names_and_key_validation_before_forward(tmp_path): + keys = ["a/b", "a_b", "a::b", "a__b", "x:y", "../escape", "a\\b", "CON", "NUL", "🌻"] + manifest = run_capture(tmp_path / "portable", [{"row_key": key, "prompt": "hello"} for key in keys]) + files = [row["capture_files"]["anchor"]["file"] for row in manifest["rows"]] + assert len(set(files)) == len(keys) + assert all(not any(char in name for char in '\\/:*?"<>|') for name in files) + for keys in (["duplicate", "duplicate"], ["A", "a"], ["a/b", safe_key("a/b")]): + with pytest.raises(ValueError, match="unique"): + run_capture(tmp_path / "invalid", [{"row_key": key, "prompt": "hello"} for key in keys]) + with pytest.raises(ValueError, match="non-empty"): + run_capture(tmp_path / "missing", [{"prompt": "hello"}]) + + +def test_torn_journal_tail_is_recovered_and_completed_files_are_checked(tmp_path): + root = tmp_path / "capture" + run_capture(root, ROWS, resume=True, run_identity={"fixture": "v1"}) + with (root / "capture.runlog.jsonl").open("ab") as stream: + stream.write(b'{"row_key":') + run_capture(root, ROWS, resume=True, run_identity={"fixture": "v1"}) + assert len([json.loads(line) for line in (root / "capture.runlog.jsonl").read_text().splitlines()]) == 2 diff --git a/tests/mech_interp/test_capture_sites.py b/tests/mech_interp/test_capture_sites.py new file mode 100644 index 000000000..83c975924 --- /dev/null +++ b/tests/mech_interp/test_capture_sites.py @@ -0,0 +1,471 @@ +"""CPU tests for explicit module-site activation capture (extract capture_sites).""" + +from __future__ import annotations + +import json + +import pytest +import torch +from safetensors import safe_open +from safetensors.torch import load_file +from torch import nn + +from MechInterp.extraction import PositionSpec, extract_rows +from MechInterp.extraction.sites import SiteCapture, SiteSpec, resolve_sites, to_site_specs +from tests.mech_interp.test_batched_generation import _build_tiny_model, _build_tiny_tokenizer + +D, H = 6, 10 # model width, MLP width + + +class Mlp(nn.Module): + def __init__(self): + super().__init__() + self.gate_proj = nn.Linear(D, H, bias=False) + self.up_proj = nn.Linear(D, H, bias=False) + self.down_proj = nn.Linear(H, D, bias=False) + + def forward(self, x): + return self.down_proj(torch.nn.functional.silu(self.gate_proj(x)) * self.up_proj(x)) + + +class Block(nn.Module): + def __init__(self): + super().__init__() + self.mlp = Mlp() + + def forward(self, x): + return x + self.mlp(x) + + +class _Inner(nn.Module): + def __init__(self, n_layers): + super().__init__() + self.layers = nn.ModuleList(Block() for _ in range(n_layers)) + + def forward(self, x): + for layer in self.layers: + x = layer(x) + return x + + +class Tiny(nn.Module): + """Layout ``model.model.layers`` -> resolved by get_decoder_layer's 'model.layers' path.""" + + def __init__(self, n_layers=3, dtype=torch.float32): + super().__init__() + torch.manual_seed(0) + self.model = _Inner(n_layers) + self.to(dtype) + + def forward(self, x): + return self.model(x) + + +def _x(seq=7, dtype=torch.float32, seed=1): + return torch.randn(1, seq, D, generator=torch.Generator().manual_seed(seed)).to(dtype) + + +def _hook_counts(model): + n = 0 + for m in model.modules(): + n += len(m._forward_hooks) + len(m._forward_pre_hooks) + len(m._forward_hooks_with_kwargs) + return n + + +def _site_hook_count(model): + """Hooks installed by SiteCapture (HF models also carry their own lazy hooks).""" + n = 0 + for m in model.modules(): + for table in (m._forward_hooks, m._forward_pre_hooks): + n += sum("SiteCapture" in getattr(h, "__qualname__", "") for h in table.values()) + return n + + +class ManualHook: + """The reference: a hook registered by hand that keeps the whole tensor.""" + + def __init__(self, module, kind): + self.value = None + if kind == "input": + self.h = module.register_forward_pre_hook(lambda m, a: setattr(self, "value", a[0].detach().clone())) + else: + self.h = module.register_forward_hook(lambda m, a, o: setattr(self, "value", o.detach().clone())) + + +@pytest.mark.parametrize("tensor", ["input", "output"]) +def test_capture_equals_manual_hook_at_selected_positions_only(tensor): + model = Tiny() + manual = ManualHook(model.model.layers[1].mlp.down_proj, tensor) + x = _x(seq=9) + positions = [0, 3, 8] + with SiteCapture(model, [SiteSpec(1, "mlp.down_proj", tensor)]) as cap: + cap.begin(positions) + with torch.no_grad(): + model(x) + manual.h.remove() + got = cap.results()[f"L1.mlp.down_proj.{tensor}"] + full = manual.value[0] + assert got.shape == (3, H if tensor == "input" else D) # only selected positions retained + assert got.dtype == torch.float32 and got.device.type == "cpu" + assert torch.equal(got, full[positions]) + assert cap.positions == positions + meta = cap.metadata()[f"L1.mlp.down_proj.{tensor}"] + assert meta["layer"] == 1 and meta["layer_convention"] == "decoder_block" + + +def test_multiple_sites_and_layer_indexing_is_decoder_block_explicit(): + model = Tiny(n_layers=3) + sites = [SiteSpec(0, "mlp.down_proj", "input"), SiteSpec(2, "mlp.gate_proj", "output")] + refs = [ManualHook(model.model.layers[0].mlp.down_proj, "input"), ManualHook(model.model.layers[2].mlp.gate_proj, "output")] + with SiteCapture(model, sites) as cap: + cap.begin([2, 4]) + model(_x()) + res = cap.results() + assert torch.equal(res["L0.mlp.down_proj.input"], refs[0].value[0][[2, 4]]) + assert torch.equal(res["L2.mlp.gate_proj.output"], refs[1].value[0][[2, 4]]) + for r in refs: + r.h.remove() + + +def test_bf16_source_is_persisted_as_exact_float32_with_dtype_metadata(): + model = Tiny(dtype=torch.bfloat16) + manual = ManualHook(model.model.layers[0].mlp.down_proj, "input") + with SiteCapture(model, [SiteSpec(0, "mlp.down_proj", "input")]) as cap: + cap.begin([1]) + model(_x(dtype=torch.bfloat16)) + out = cap.results()["L0.mlp.down_proj.input"] + assert out.dtype == torch.float32 + assert torch.equal(out, manual.value[0][[1]].float()) + assert cap.metadata()["L0.mlp.down_proj.input"]["source_dtype"] == "bfloat16" + + +def test_hooks_are_removed_after_normal_exit_and_after_forward_failure(): + model = Tiny() + assert _hook_counts(model) == 0 + with SiteCapture(model, [SiteSpec(0, "mlp.down_proj", "input"), SiteSpec(1, "mlp.down_proj", "output")]) as cap: + assert _hook_counts(model) == 2 + cap.begin([0]) + model(_x()) + assert _hook_counts(model) == 0 + + class Boom(nn.Module): + def forward(self, x): + raise RuntimeError("forward failed") + + model.model.layers[2].mlp = Boom() + with pytest.raises(RuntimeError, match="forward failed"): + with SiteCapture(model, [SiteSpec(0, "mlp.down_proj", "input")]) as cap: + cap.begin([0]) + model(_x()) + assert _hook_counts(model) == 0 + + +def test_hooks_are_removed_when_registration_fails_midway(monkeypatch): + model = Tiny() + target = model.model.layers[1].mlp.down_proj + + def refuse(*a, **k): + raise RuntimeError("cannot register") + + monkeypatch.setattr(target, "register_forward_hook", refuse) + cap = SiteCapture(model, [SiteSpec(0, "mlp.down_proj", "input"), SiteSpec(1, "mlp.down_proj", "output")]) + with pytest.raises(RuntimeError, match="cannot register"): + cap.__enter__() + assert _hook_counts(model) == 0 # the first (already registered) hook was removed + + +def test_error_inside_capture_still_removes_hooks_for_bad_positions(): + model = Tiny() + with pytest.raises(ValueError, match="outside sequence length"): + with SiteCapture(model, [SiteSpec(0, "mlp.down_proj", "input")]) as cap: + cap.begin([50]) + model(_x(seq=7)) + assert _hook_counts(model) == 0 + + +def test_unarmed_forward_captures_nothing_and_results_refuse(): + model = Tiny() + with SiteCapture(model, [SiteSpec(0, "mlp.down_proj", "input")]) as cap: + model(_x()) + with pytest.raises(ValueError, match="did not fire"): + cap.results() + + +def test_module_firing_twice_and_batched_input_are_refused(): + model = Tiny() + + class Twice(nn.Module): # calls its down_proj twice in one forward + def __init__(self): + super().__init__() + self.down_proj = nn.Linear(D, D, bias=False) + + def forward(self, x): + return self.down_proj(self.down_proj(x)) + + model.model.layers[0].mlp = Twice() + with pytest.raises(ValueError, match="more than once"): + with SiteCapture(model, [SiteSpec(0, "mlp.down_proj", "input")]) as cap: + cap.begin([0]) + model(_x()) + fresh = Tiny() + with pytest.raises(ValueError, match=r"\[1, seq, features\]"): + with SiteCapture(fresh, [SiteSpec(0, "mlp.down_proj", "input")]) as cap: + cap.begin([0]) + fresh(torch.randn(2, 5, D)) + assert _hook_counts(fresh) == 0 + + +def test_bad_sites_are_refused_before_any_hook_exists(): + model = Tiny(n_layers=2) + for bad, msg in ( + (SiteSpec(5, "mlp.down_proj", "input"), "out of range"), + (SiteSpec(0, "mlp.nope", "input"), "no submodule"), + ): + with pytest.raises(ValueError, match=msg): + SiteCapture(model, [bad]) + with pytest.raises(ValueError, match="unique"): + to_site_specs([SiteSpec(0, "mlp.down_proj", "input")] * 2) + with pytest.raises(ValueError, match="'input' or 'output'"): + to_site_specs([{"layer": 0, "module": "mlp.down_proj", "tensor": "grad"}]) + with pytest.raises(ValueError, match="decoder layers"): + resolve_sites(nn.Linear(2, 2), [SiteSpec(0, "x", "input")]) + assert _hook_counts(model) == 0 + with pytest.raises(ValueError, match="non-empty"): + SiteCapture(model, [SiteSpec(0, "mlp.down_proj", "input")]).begin([]) + + +# -------------------------------------------------------------------------- +# extract_rows integration on a tiny real GPT-2 +# -------------------------------------------------------------------------- + +ROWS = [ + {"row_key": "a", "prompt": "w1 w2 w3"}, + {"row_key": "b", "prompt": "w4 w5 w6 w7 w8"}, +] +SITE = {"layer": 1, "module": "mlp.c_proj", "tensor": "input"} + + +def _content_end(full, prompt_len, tokenizer): + return int(full.shape[0]) - 1 + + +def _extract(tmp, name, **kw): + out = tmp / name + manifest = extract_rows( + _build_tiny_model(), + _build_tiny_tokenizer(), + ROWS, + render_fn=lambda r: r["prompt"], + content_end_fn=_content_end, + spec=PositionSpec(families=["anchor", "answer_end"], layers=[1, 2]), + out_dir=out, + max_new_tokens=4, + **kw, + ) + return out, manifest + + +def test_extract_without_capture_sites_is_unchanged_and_with_them_is_additive(tmp_path): + plain, plain_manifest = _extract(tmp_path, "plain") + sited, sited_manifest = _extract(tmp_path, "sited", capture_sites=[SITE]) + names = sorted(p.name for p in plain.iterdir()) + assert not any(".sites." in n for n in names) + assert "capture_sites" not in plain_manifest + # residual files are byte-identical with and without the option + for n in names: + assert (plain / n).read_bytes() == (sited / n).read_bytes() or n == "manifest.json" + extra = sorted(set(p.name for p in sited.iterdir()) - set(names)) + assert extra == [f"{k}__{f}.sites.safetensors" for k in ("a", "b") for f in ("anchor", "answer_end")] + assert {k: v for k, v in sited_manifest.items() if k not in {"capture_sites", "capture_site_layer_convention", "capture_site_persist_dtype", "rows"}} == { + k: v for k, v in plain_manifest.items() if k != "rows" + } + assert sited_manifest["capture_site_layer_convention"] == "decoder_block" + assert sited_manifest["capture_sites"] == [{"key": "L1.mlp.c_proj.input", **SITE}] + + +def test_extract_site_capture_equals_manual_hook_and_records_metadata(tmp_path): + model, tok = _build_tiny_model(), _build_tiny_tokenizer() + out = tmp_path / "o" + manifest = extract_rows( + model, tok, ROWS, render_fn=lambda r: r["prompt"], content_end_fn=_content_end, + spec=PositionSpec(families=["anchor", "answer_end"], layers=[]), out_dir=out, + max_new_tokens=4, capture_sites=[SITE], + ) + manual = ManualHook(model.transformer.h[1].mlp.c_proj, "input") + for rec in manifest["rows"]: + ids = tok(next(r["prompt"] for r in ROWS if r["row_key"] == rec["row_key"]), return_tensors="pt")["input_ids"] + full = model.generate(input_ids=ids, attention_mask=torch.ones_like(ids), max_new_tokens=4, do_sample=False, num_beams=1, return_dict_in_generate=True).sequences[0] + with torch.no_grad(): + model(input_ids=full[: rec["content_end"] + 1].unsqueeze(0), attention_mask=torch.ones(1, rec["content_end"] + 1, dtype=torch.long), use_cache=False) + ref = manual.value[0] + for family, pos in (("anchor", rec["prompt_len"] - 1), ("answer_end", rec["content_end"])): + path = out / f"{rec['row_key']}__{family}.sites.safetensors" + got = load_file(str(path))["L1.mlp.c_proj.input"] + assert got.shape == (1, 128) and got.dtype == torch.float32 + assert torch.equal(got, ref[[pos]].float()) + with safe_open(str(path), "pt") as f: + meta = f.metadata() + assert meta["layer_convention"] == "decoder_block" and json.loads(meta["positions"]) == [pos] + info = rec["site_captures"][family] + assert info["positions"] == [pos] + assert info["sites"]["L1.mlp.c_proj.input"] == {"shape": [1, 128], "persist_dtype": "float32", "source_dtype": "float32"} + manual.h.remove() + assert _site_hook_count(model) == 0 + # no residual layers requested -> no residual files, only site files + assert all(".sites." in p.name or p.name == "manifest.json" for p in out.iterdir()) + + +def test_extract_refuses_bad_site_before_generating(tmp_path): + model = _build_tiny_model() + calls = [] + orig = model.generate + model.generate = lambda *a, **k: calls.append(1) or orig(*a, **k) + with pytest.raises(ValueError, match="no submodule"): + extract_rows( + model, _build_tiny_tokenizer(), ROWS, render_fn=lambda r: r["prompt"], content_end_fn=_content_end, + spec=PositionSpec(), out_dir=tmp_path / "o", capture_sites=[{**SITE, "module": "mlp.missing"}], + ) + assert not calls + + +def test_extract_forward_failure_removes_site_hooks(tmp_path): + model = _build_tiny_model() + block = model.transformer.h[1] + original_forward = block.mlp.c_proj.forward + + def failing(x): + original_forward(x) # fire the hook, then fail the pass + raise RuntimeError("mid-forward failure") + + # generate() must succeed, the clean forward then fails after the hook fired + real_forward = model.forward + + def forward(*a, **k): + if k.get("output_hidden_states"): + block.mlp.c_proj.forward = failing + return real_forward(*a, **k) + + model.forward = forward + with pytest.raises(RuntimeError, match="mid-forward failure"): + extract_rows( + model, _build_tiny_tokenizer(), ROWS, render_fn=lambda r: r["prompt"], content_end_fn=_content_end, + spec=PositionSpec(), out_dir=tmp_path / "o", max_new_tokens=3, capture_sites=[SITE], + ) + assert _site_hook_count(model) == 0 + + +# -------------------------------------------------------------------------- +# use_cache and forward_only +# -------------------------------------------------------------------------- + + +class _ForwardSpy: + """Records the use_cache argument of every model(...) call.""" + + def __init__(self, model): + self.calls = [] + self.generate_calls = 0 + real_forward, real_generate = model.forward, model.generate + + def forward(*a, **k): + if k.get("output_hidden_states"): + self.calls.append(k.get("use_cache")) + return real_forward(*a, **k) + + def generate(*a, **k): + self.generate_calls += 1 + return real_generate(*a, **k) + + model.forward, model.generate = forward, generate + + +def _extract_spied(tmp, name, **kw): + model = _build_tiny_model() + spy = _ForwardSpy(model) + out = tmp / name + manifest = extract_rows( + model, _build_tiny_tokenizer(), ROWS, render_fn=lambda r: r["prompt"], + content_end_fn=kw.pop("content_end_fn", _content_end), + spec=kw.pop("spec", PositionSpec(families=["anchor", "answer_end"], layers=[1])), + out_dir=out, max_new_tokens=kw.pop("max_new_tokens", 4), **kw, + ) + return model, spy, out, manifest + + +def test_capture_use_cache_is_configurable_and_default_is_unchanged(tmp_path): + _, spy_default, out_default, m_default = _extract_spied(tmp_path, "d", capture_sites=[SITE]) + assert set(spy_default.calls) == {False} # historical teacher-forced behavior + assert "capture_use_cache" not in m_default + + _, spy_true, out_true, m_true = _extract_spied(tmp_path, "t", capture_sites=[SITE], use_cache=True) + assert set(spy_true.calls) == {True} + assert m_true["capture_use_cache"] is True + # for a plain causal LM the captured values do not depend on the cache flag + for n in sorted(p.name for p in out_default.iterdir() if p.name != "manifest.json"): + a, b = load_file(str(out_default / n)), load_file(str(out_true / n)) + assert a.keys() == b.keys() and all(torch.equal(a[k], b[k]) for k in a) + + +def test_site_capture_equals_manual_hook_with_use_cache_true(tmp_path): + model, spy, out, manifest = _extract_spied( + tmp_path, "c", spec=PositionSpec(families=["anchor", "answer_end"], layers=[]), + capture_sites=[SITE], use_cache=True, + ) + assert set(spy.calls) == {True} + manual = ManualHook(model.transformer.h[1].mlp.c_proj, "input") + for rec in manifest["rows"]: + ids = _build_tiny_tokenizer()(next(r["prompt"] for r in ROWS if r["row_key"] == rec["row_key"]), return_tensors="pt")["input_ids"] + full = model.generate(input_ids=ids, attention_mask=torch.ones_like(ids), max_new_tokens=4, do_sample=False, num_beams=1, return_dict_in_generate=True).sequences[0] + n = rec["content_end"] + 1 + with torch.no_grad(): + model(input_ids=full[:n].unsqueeze(0), attention_mask=torch.ones(1, n, dtype=torch.long), use_cache=True) + ref = manual.value[0] + got = load_file(str(out / f"{rec['row_key']}__anchor.sites.safetensors"))["L1.mlp.c_proj.input"] + assert torch.equal(got, ref[[rec["prompt_len"] - 1]].float()) + manual.h.remove() + + +def test_forward_only_anchor_capture_never_generates(tmp_path): + spec = PositionSpec(families=["anchor"], layers=[1, 2]) + model, spy, out, manifest = _extract_spied( + tmp_path, "f", spec=spec, content_end_fn=None, capture_sites=[SITE], + use_cache=True, forward_only=True, max_new_tokens=999, + ) + assert spy.generate_calls == 0 and set(spy.calls) == {True} + assert manifest["forward_only"] is True and manifest["n_answered"] == 2 + manual = ManualHook(model.transformer.h[1].mlp.c_proj, "input") + for rec in manifest["rows"]: + prompt = next(r["prompt"] for r in ROWS if r["row_key"] == rec["row_key"]) + ids = _build_tiny_tokenizer()(prompt, return_tensors="pt")["input_ids"] + assert rec["seq_total"] == rec["prompt_len"] == ids.shape[1] and rec["answer_text"] == "" + with torch.no_grad(): + res = model(input_ids=ids, attention_mask=torch.ones_like(ids), output_hidden_states=True, use_cache=False) + site = load_file(str(out / f"{rec['row_key']}__anchor.sites.safetensors"))["L1.mlp.c_proj.input"] + assert torch.equal(site, manual.value[0][[-1]].float()) + resid = load_file(str(out / f"{rec['row_key']}__anchor.safetensors")) + assert torch.equal(resid["L1"][0], res.hidden_states[1][0, -1].float()) + manual.h.remove() + + +def test_forward_only_requires_anchor_family_and_content_end_otherwise(): + model, tok = _build_tiny_model(), _build_tiny_tokenizer() + common = dict(render_fn=lambda r: r["prompt"], out_dir="unused") + with pytest.raises(ValueError, match="'anchor' family"): + extract_rows(model, tok, ROWS, content_end_fn=None, spec=PositionSpec(families=["anchor", "answer_end"]), forward_only=True, **common) + with pytest.raises(ValueError, match="content_end_fn is required"): + extract_rows(model, tok, ROWS, content_end_fn=None, spec=PositionSpec(), **common) + + +def test_extract_config_use_cache_forward_only_contract(): + from MechInterp.config import ExtractConfig + + base = dict(rows_path="r", output_dir="o", render_fn="m:r") + legacy = ExtractConfig(**base, content_end_fn="m:c") + assert legacy.use_cache is False and legacy.forward_only is False + assert ExtractConfig(**base, content_end_fn="m:c", use_cache=True).use_cache is True + fo = ExtractConfig(**base, families=["anchor"], forward_only=True) + assert fo.content_end_fn is None + with pytest.raises(Exception, match="content_end_fn"): + ExtractConfig(**base) # still required when generating + with pytest.raises(Exception, match="forward_only requires"): + ExtractConfig(**base, forward_only=True) # default families include answer_end diff --git a/tests/mech_interp/test_dose_calibration.py b/tests/mech_interp/test_dose_calibration.py index e3db165c7..f29dfd821 100644 --- a/tests/mech_interp/test_dose_calibration.py +++ b/tests/mech_interp/test_dose_calibration.py @@ -298,7 +298,7 @@ def test_pipeline_compiles_dose_calibrate_with_gpu_ack(tmp_path): plan = build_pipeline_plan(cfg, repo_root=tmp_path, provider="local", gpu_ack=True) cmd = plan["stages"][0]["command"] - assert cmd[:4] == ["python", str(tmp_path / "tuner.py"), "mechinterp", "dose-calibrate"] + assert cmd[:5] == ["python", "-m", "tuner", "mechinterp", "dose-calibrate"] assert "--mi-config" in cmd assert str(cfg_path) in cmd assert cmd[cmd.index("--model") + 1] == "Tiny/Model" diff --git a/tests/mech_interp/test_intervention_hooks.py b/tests/mech_interp/test_intervention_hooks.py index c2a446450..3e075e72e 100644 --- a/tests/mech_interp/test_intervention_hooks.py +++ b/tests/mech_interp/test_intervention_hooks.py @@ -334,3 +334,17 @@ def test_hook_readback_offtarget_catches_real_inactive_movement(): rb = hook._readback(moved, d, True, torch.tensor([2, 2]), None, torch.tensor([2.0, 0.0]), pre) assert rb["offtarget_abs_max"] == pytest.approx(2.0) + + +def test_bf16_noop_readback_uses_same_direction_before_and_after(): + generator = torch.Generator().manual_seed(20261103) + direction = torch.randn(2560, generator=generator) + direction /= direction.norm() + hidden = (torch.randn(3, 4, 2560, generator=generator) * 10).to(torch.bfloat16) + hook = InterventionHook('erase_write', direction, strength=0.0, + position='final', measure_readback=True) + output = hook(None, None, hidden) + assert torch.equal(output, hidden) # No actual movement occurred. + # This used to report >1e-3 because pre used float32 direction while + # post used its bf16-rounded copy. A tolerance change cannot fix a metric. + assert hook.last_readback['offtarget_abs_max'] == 0.0 diff --git a/tests/mech_interp/test_pipeline.py b/tests/mech_interp/test_pipeline.py index c0a1f6f68..021b028d2 100644 --- a/tests/mech_interp/test_pipeline.py +++ b/tests/mech_interp/test_pipeline.py @@ -159,7 +159,7 @@ def test_host_pipeline_splits_engine_executable_from_project_workdir(tmp_path): assert Path(cfg.runtime.workdir) == project assert Path(cfg.stages[0].config) == recipe.parent / "probe.yaml" - assert Path(plan["stages"][0]["command"][1]) == engine / "tuner.py" + assert plan["stages"][0]["command"][1:4] == ["-m", "tuner", "mechinterp"] assert Path(plan["stages"][0]["workdir"]) == project diff --git a/tests/mech_interp/test_steer_record_passthrough.py b/tests/mech_interp/test_steer_record_passthrough.py index df410560e..f0ace69ae 100644 --- a/tests/mech_interp/test_steer_record_passthrough.py +++ b/tests/mech_interp/test_steer_record_passthrough.py @@ -128,6 +128,7 @@ def test_computed_keys_are_never_shadowed_by_a_same_named_pool_field(): row = _fresh_row() row["answer_text"] = "SHOULD NOT SURVIVE" row["n_new_tokens"] = -1 + row["generated_token_ids"] = [-1] row["terminated_naturally"] = "spoofed" model = _build_tiny_model() @@ -139,6 +140,8 @@ def test_computed_keys_are_never_shadowed_by_a_same_named_pool_field(): assert rec["answer_text"] != "SHOULD NOT SURVIVE" assert rec["n_new_tokens"] != -1 + assert rec["generated_token_ids"] != [-1] + assert len(rec["generated_token_ids"]) == rec["n_new_tokens"] assert rec["terminated_naturally"] != "spoofed" assert isinstance(rec["n_new_tokens"], int) assert isinstance(rec["terminated_naturally"], bool) diff --git a/tests/mech_interp/test_weight_patch_core.py b/tests/mech_interp/test_weight_patch_core.py new file mode 100644 index 000000000..dc31f07c5 --- /dev/null +++ b/tests/mech_interp/test_weight_patch_core.py @@ -0,0 +1,973 @@ +"""CPU tests for the generic weight-patch core: spec, safetensors I/O, planning, +in-memory apply/revert and create-only export. Tiny local checkpoints only.""" + +from __future__ import annotations + +import json +import errno +import os +import struct +from pathlib import Path + +import pytest +import torch +import yaml +from safetensors.torch import load_file, save_file + +from MechInterp.weights import runtime as wruntime +from MechInterp.weights.checkpoint import ( + inspect_checkpoint, + open_checkpoint, +) +from MechInterp.weights.errors import WeightPatchError +from MechInterp.weights.patch import load_payload +from MechInterp.weights.safetensors_io import hash_file_with_regions, read_header, read_region +from MechInterp.weights.spec import ( + InspectRequest, + load_patch_spec, + parse_patch_spec, + read_document, +) +from MechInterp.weights.workflow import ( + export_patch_config, + plan_against_checkpoint, + validate_patch_config, +) + +from tests.mech_interp.weight_patch_fixtures import ( + DOWN0, + DOWN1, + EMBED, + GATE0, + NORM, + OTHER_REVISION, + REVISION, + base_tensors, + file_sha, + make_spec, + raw_sha, + rewrite_spec, + standard_ops_and_arrays, + write_checkpoint, +) + + +def refusal(code): + return pytest.raises(WeightPatchError, match=rf"^\[{code}\]") + + +@pytest.fixture +def ckpt_dir(tmp_path): + tensors = write_checkpoint(tmp_path / "base") + return tmp_path / "base", tensors + + +def _std_spec(tmp_path, ckpt_dir, **kw): + root, tensors = ckpt_dir + ops, arrays = standard_ops_and_arrays() + return make_spec( + tmp_path / "spec", + tensors, + ops, + arrays, + checkpoint=root, + base_extra=kw.pop("base_extra", {"index_sha256": file_sha(root / "model.safetensors.index.json")}), + **kw, + ) + + +# -------------------------------------------------------------------------- +# safetensors I/O +# -------------------------------------------------------------------------- + + +def test_header_reader_agrees_with_safetensors_library_and_hashes_bf16_bytes(ckpt_dir): + root, tensors = ckpt_dir + sf = read_header(root / "model-00001-of-00002.safetensors") + assert set(sf.entries) == {DOWN0, GATE0, NORM} + assert sf.metadata == {"format": "pt"} + lib = load_file(str(sf.path)) + whole, regions = hash_file_with_regions(sf) + assert whole == file_sha(sf.path) + for name, entry in sf.entries.items(): + assert entry.torch_dtype == str(lib[name].dtype).removeprefix("torch.") + assert list(entry.shape) == list(lib[name].shape) + # region hash == independent hash of the stored dtype bytes (bf16 included) + assert regions[name] == raw_sha(tensors[name]) + got = torch.frombuffer(read_region(sf, entry), dtype=lib[name].dtype).reshape(entry.shape) + assert torch.equal(got, lib[name]) + assert tensors[DOWN0].dtype == torch.bfloat16 + + +def _header_bytes(path: Path): + raw = path.read_bytes() + (n,) = struct.unpack(" 0 + assert new[0, 0].view(torch.int16) == tensors[DOWN0][0, 0].view(torch.int16) # still -0.0 bitwise + assert torch.signbit(new[0, 0].float()) + + +def test_sub_ulp_delta_is_unchanged_not_budgeted(tmp_path): + tensors = base_tensors() + root = tmp_path / "ck" + write_checkpoint(root, tensors, sharded=False) + ops = [{"id": "tiny", "tensor": DOWN0, "op": "add_rank_one", "scale": 1e-12, "arrays": {"u": "u", "v": "v"}}] + spec_path = make_spec( + tmp_path / "s", tensors, ops, {"u": torch.randn(8), "v": torch.randn(16)}, checkpoint=root, + base_extra={"index_sha256": file_sha(root / "model.safetensors")}, + ) + spec, digest = load_patch_spec(spec_path) + _, _, _, plan = plan_against_checkpoint(spec, digest) + assert plan.is_noop # realized delta in bf16 is zero + + +# -------------------------------------------------------------------------- +# Revision / source binding +# -------------------------------------------------------------------------- + + +def test_binding_requires_content_pins_or_revision_evidence(tmp_path, ckpt_dir): + with refusal("binding"): + _plan(tmp_path, ckpt_dir, base_extra={}) # no pins, plain dir, no evidence + + +def test_wrong_index_or_file_hash_refuses(tmp_path, ckpt_dir): + with refusal("binding"): + _plan(tmp_path / "a", ckpt_dir, base_extra={"index_sha256": "0" * 64}) + root, _ = ckpt_dir + files = {n: file_sha(root / n) for n in os.listdir(root) if n.endswith(".safetensors")} + _plan(tmp_path / "ok", ckpt_dir, base_extra={"files_sha256": files}) + bad = dict(files) + bad["model-00001-of-00002.safetensors"] = "f" * 64 + with refusal("binding"): + _plan(tmp_path / "b", ckpt_dir, base_extra={"files_sha256": bad}) + with refusal("binding"): # must list exactly the checkpoint's files + _plan(tmp_path / "c", ckpt_dir, base_extra={"files_sha256": {k: files[k] for k in list(files)[:1]}}) + + +def test_revision_evidence_from_snapshot_dir_and_download_metadata(tmp_path): + tensors = base_tensors() + ops, arrays = standard_ops_and_arrays() + + def run(dirname_rev, declared): + root = tmp_path / dirname_rev[:6] / "snapshots" / dirname_rev + write_checkpoint(root, tensors, sharded=False) + spec_path = make_spec( + tmp_path / f"s{dirname_rev[:6]}{declared[:3]}", tensors, + [ops[0]], {k: v for k, v in arrays.items() if k.startswith("r1")}, + checkpoint=root, revision=declared, + ) + spec, digest = load_patch_spec(spec_path) + return plan_against_checkpoint(spec, digest) + + _, binding, _, _ = run(REVISION, REVISION) # no content pin; evidence suffices + assert binding["revision_evidence"][0]["source"] == "hf_snapshot_directory" + assert binding["content_pinned"] is False + with refusal("binding"): # the snapshot says OTHER_REVISION, spec declares REVISION + run(OTHER_REVISION, REVISION) + + root = tmp_path / "dl" + write_checkpoint(root, tensors, sharded=False) + meta = root / ".cache" / "huggingface" / "download" + meta.mkdir(parents=True) + (meta / "model.safetensors.metadata").write_text(f"{OTHER_REVISION}\netag\n123\n") + spec_path = make_spec( + tmp_path / "sd", tensors, [ops[0]], {k: v for k, v in arrays.items() if k.startswith("r1")}, + checkpoint=root, + base_extra={"index_sha256": file_sha(root / "model.safetensors")}, + ) + spec, digest = load_patch_spec(spec_path) + with refusal("binding"): # content pinned, but local metadata contradicts the declared revision + plan_against_checkpoint(spec, digest) + + +# -------------------------------------------------------------------------- +# In-memory apply / revert (runtime) +# -------------------------------------------------------------------------- + + +class TinyModule(torch.nn.Module): + """Parameter names mirror the fixture checkpoint names via ParameterDict-less attrs.""" + + def __init__(self, tensors, prefix=""): + super().__init__() + self._names = {} + for i, (name, t) in enumerate(tensors.items()): + attr = f"p{i}" + setattr(self, attr, torch.nn.Parameter(t.clone(), requires_grad=False)) + self._names[prefix + name] = attr + + def named_parameters(self, *a, **k): # expose checkpoint-style names + for name, attr in self._names.items(): + yield name, getattr(self, attr) + + +def _prepared(tmp_path, ckpt_dir, **kw): + spec_path = _std_spec(tmp_path, ckpt_dir, **kw) + spec, digest = load_patch_spec(spec_path) + return wruntime.prepare_patch(spec_path, digest), spec_path, digest + + +def test_apply_matches_planned_bytes_and_revert_is_exact(tmp_path, ckpt_dir): + root, tensors = ckpt_dir + model = TinyModule(tensors) + prepared, _, _ = _prepared(tmp_path, ckpt_dir) + before = {n: raw_sha(p) for n, p in model.named_parameters()} + applied = wruntime.apply_patch(model, prepared) + params = dict(model.named_parameters()) + modified = applied.plan.modified + assert set(modified) == {DOWN0, GATE0} + for name, tp in modified.items(): + assert raw_sha(params[name]) == tp.after_sha256 != before[name] + for name in (DOWN1, EMBED, NORM): + assert raw_sha(params[name]) == before[name] + # same bytes the disk-based plan produced + _, _, _, disk_plan = plan_against_checkpoint(prepared.spec, prepared.spec_sha256) + assert disk_plan.patch_digest() == applied.plan.patch_digest() + applied.revert() + assert {n: raw_sha(p) for n, p in model.named_parameters()} == before + applied.revert() # idempotent + + +def test_context_manager_reverts_even_on_error(tmp_path, ckpt_dir): + root, tensors = ckpt_dir + model = TinyModule(tensors) + prepared, _, _ = _prepared(tmp_path, ckpt_dir) + before = {n: raw_sha(p) for n, p in model.named_parameters()} + with pytest.raises(RuntimeError): + with wruntime.patched(model, prepared) as applied: + assert raw_sha(dict(model.named_parameters())[DOWN0]) != before[DOWN0] + raise RuntimeError("boom") + assert applied.reverted + assert {n: raw_sha(p) for n, p in model.named_parameters()} == before + + +def test_wrong_base_refuses_and_leaves_module_untouched(tmp_path, ckpt_dir): + root, tensors = ckpt_dir + wrong = {k: v.clone() for k, v in tensors.items()} + wrong[GATE0][0, 0] = wrong[GATE0][0, 0] + 1 # second tensor differs + model = TinyModule(wrong) + prepared, _, _ = _prepared(tmp_path, ckpt_dir) + before = {n: raw_sha(p) for n, p in model.named_parameters()} + with refusal("base_hash_mismatch"): + wruntime.apply_patch(model, prepared) + assert {n: raw_sha(p) for n, p in model.named_parameters()} == before # first tensor not half-patched + + +def test_budget_refusal_leaves_module_untouched(tmp_path, ckpt_dir): + root, tensors = ckpt_dir + model = TinyModule(tensors) + prepared, _, _ = _prepared(tmp_path, ckpt_dir, budget={"max_relative_frobenius": 1e-9}) + before = {n: raw_sha(p) for n, p in model.named_parameters()} + with refusal("budget"): + wruntime.apply_patch(model, prepared) + assert {n: raw_sha(p) for n, p in model.named_parameters()} == before + + +def test_commit_verification_failure_rolls_back_every_tensor(tmp_path, ckpt_dir, monkeypatch): + root, tensors = ckpt_dir + model = TinyModule(tensors) + prepared, _, _ = _prepared(tmp_path, ckpt_dir) + before = {n: raw_sha(p) for n, p in model.named_parameters()} + real = wruntime.tensor_sha256 + calls = {"n": 0} + + def flaky(t): + calls["n"] += 1 + return "0" * 64 if calls["n"] == 2 else real(t) + + monkeypatch.setattr(wruntime, "tensor_sha256", flaky) + with refusal("apply"): + wruntime.apply_patch(model, prepared) + monkeypatch.setattr(wruntime, "tensor_sha256", real) + assert {n: raw_sha(p) for n, p in model.named_parameters()} == before + + +def test_runtime_prefix_rules_map_checkpoint_names_to_module_names(tmp_path, ckpt_dir): + root, tensors = ckpt_dir + model = TinyModule(tensors, prefix="lm.") + prepared, spec_path, _ = _prepared( + tmp_path, ckpt_dir, + base_extra={ + "index_sha256": file_sha(root / "model.safetensors.index.json"), + "runtime_prefix_rules": [{"checkpoint_prefix": "blk.", "runtime_prefix": "lm.blk."}], + }, + ) + with refusal("binding"): # tensors only exist under "lm."; rule maps blk.* -> lm.blk.* + wruntime.apply_patch(TinyModule(tensors, prefix="other."), prepared) + applied = wruntime.apply_patch(model, prepared) + assert dict(model.named_parameters())["lm." + DOWN0] is not None + applied.revert() + + +def test_declared_revision_must_equal_patch_revision(tmp_path, ckpt_dir): + prepared, _, digest = _prepared(tmp_path, ckpt_dir) + wruntime.check_declared_revision(prepared, REVISION) + with refusal("binding"): + wruntime.check_declared_revision(prepared, OTHER_REVISION) + with refusal("binding"): + wruntime.check_declared_revision(prepared, None) + + class Cfg: + _commit_hash = OTHER_REVISION + + class M: + config = Cfg() + + with refusal("binding"): # a loaded model that resolved another commit is refused + wruntime.check_loaded_commit(prepared, M()) + Cfg._commit_hash = REVISION + assert wruntime.check_loaded_commit(prepared, M()) == REVISION + + +def test_prepare_patch_refuses_wrong_pinned_spec_sha(tmp_path, ckpt_dir): + spec_path = _std_spec(tmp_path, ckpt_dir) + with refusal("binding"): + wruntime.prepare_patch(spec_path, "0" * 64) + + +# -------------------------------------------------------------------------- +# Export + readback +# -------------------------------------------------------------------------- + + +def test_validate_writes_nothing_then_export_is_exact(tmp_path, ckpt_dir): + root, tensors = ckpt_dir + out = tmp_path / "exported" + spec_path = _std_spec(tmp_path, ckpt_dir, export_dir=out) + snapshot = {p.name: file_sha(p) for p in root.iterdir()} + + report = validate_patch_config(spec_path) + assert report["written"] is False and not out.exists() + assert not [p for p in tmp_path.iterdir() if ".partial-" in p.name] + + result = export_patch_config(spec_path) + assert out.is_dir() and result["written"] + assert not [p for p in tmp_path.iterdir() if ".partial-" in p.name] + assert {p.name: file_sha(p) for p in root.iterdir()} == snapshot # base untouched + + plan_modified = {t["name"]: t for t in result["manifest"]["tensors"] if t["entries_changed"]} + assert set(plan_modified) == {DOWN0, GATE0} + for shard in ("model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors"): + got = load_file(str(out / shard)) # readback with the independent library + base = load_file(str(root / shard)) + assert set(got) == set(base) + for name, tensor in got.items(): + assert tensor.dtype == base[name].dtype and tensor.shape == base[name].shape + if name in plan_modified: + assert raw_sha(tensor) == plan_modified[name]["after_sha256"] + assert raw_sha(tensor) != raw_sha(base[name]) + else: + assert torch.equal(tensor.view(torch.uint8), base[name].view(torch.uint8)) + # untouched shard is byte-identical; header (incl. __metadata__) preserved + assert file_sha(out / "model-00002-of-00002.safetensors") == file_sha(root / "model-00002-of-00002.safetensors") + assert read_header(out / "model-00001-of-00002.safetensors").metadata == {"format": "pt"} + # index + sidecar copied verbatim + assert file_sha(out / "model.safetensors.index.json") == file_sha(root / "model.safetensors.index.json") + assert (out / "config.json").read_text() == (root / "config.json").read_text() + + manifest = json.loads((out / "mechinterp-weight-export.manifest.json").read_text()) + assert manifest["schema_version"] == "mechinterp-weight-export/v1" + assert manifest["patch_digest"] == result["patch_digest"] + assert manifest["base"]["revision"] == REVISION + assert manifest["spec"]["sha256"] == file_sha(spec_path) + for fname, info in manifest["output"]["weight_files"].items(): + assert info["sha256"] == file_sha(out / fname) + assert manifest["base"]["files"]["model-00001-of-00002.safetensors"]["sha256"] == file_sha( + root / "model-00001-of-00002.safetensors" + ) + assert manifest["totals"]["tensors_modified"] == 2 + + +def test_export_refuses_existing_destination_and_preserves_it(tmp_path, ckpt_dir): + out = tmp_path / "exported" + out.mkdir() + (out / "keep.txt").write_text("precious") + spec_path = _std_spec(tmp_path, ckpt_dir, export_dir=out) + with refusal("output_exists"): + export_patch_config(spec_path) + assert (out / "keep.txt").read_text() == "precious" and len(list(out.iterdir())) == 1 + # a second export into a freshly exported dir is refused too + spec_path2 = _std_spec(tmp_path / "n", ckpt_dir, export_dir=tmp_path / "fresh") + export_patch_config(spec_path2) + with refusal("output_exists"): + export_patch_config(spec_path2) + + +def test_failed_export_leaves_no_output_or_staging(tmp_path, ckpt_dir): + out = tmp_path / "exported" + spec_path = _std_spec(tmp_path, ckpt_dir, export_dir=out, budget={"max_relative_frobenius": 1e-9}) + with refusal("budget"): + export_patch_config(spec_path) + assert not out.exists() + assert not [p for p in tmp_path.iterdir() if ".partial-" in p.name] + + +def test_export_midway_failure_cleans_staging(tmp_path, ckpt_dir, monkeypatch): + out = tmp_path / "exported" + spec_path = _std_spec(tmp_path, ckpt_dir, export_dir=out) + from MechInterp.weights import export as wexport + + def boom(*a, **k): + raise OSError("disk full") + + monkeypatch.setattr(wexport, "_copy_file", boom) + with pytest.raises(OSError): + export_patch_config(spec_path) + assert not out.exists() + assert not [p for p in tmp_path.iterdir() if ".partial-" in p.name] + + +def test_export_requires_export_block_and_checkpoint(tmp_path, ckpt_dir): + spec_path = _std_spec(tmp_path, ckpt_dir) + with refusal("schema"): + export_patch_config(spec_path) + root, tensors = ckpt_dir + ops, arrays = standard_ops_and_arrays() + no_ckpt = make_spec(tmp_path / "nc", tensors, ops, arrays, export_dir=tmp_path / "o") + with refusal("schema"): + validate_patch_config(no_ckpt) + + +def test_single_file_checkpoint_export_roundtrip(tmp_path): + tensors = base_tensors() + root = tmp_path / "ck" + write_checkpoint(root, tensors, sharded=False) + ops, arrays = standard_ops_and_arrays() + spec_path = make_spec( + tmp_path / "s", tensors, ops, arrays, checkpoint=root / "model.safetensors", + base_extra={"index_sha256": file_sha(root / "model.safetensors")}, + export_dir=tmp_path / "out", + ) + result = export_patch_config(spec_path) + got = load_file(str(tmp_path / "out" / "model.safetensors")) + for tp in result["manifest"]["tensors"]: + assert raw_sha(got[tp["name"]]) == tp["after_sha256"] + assert raw_sha(got[EMBED]) == raw_sha(tensors[EMBED]) + + +def test_runtime_refuses_shared_storage_before_any_write(tmp_path, ckpt_dir): + _, tensors = ckpt_dir + model = TinyModule(tensors) + prepared, _, _ = _prepared(tmp_path, ckpt_dir) + target = prepared.spec.targeted_tensors()[0] + model._names["unbudgeted_alias"] = model._names[target] + before = {name: raw_sha(param) for name, param in model.named_parameters()} + with pytest.raises(WeightPatchError, match="shares storage"): + wruntime.apply_patch(model, prepared) + assert {name: raw_sha(param) for name, param in model.named_parameters()} == before + + +def test_export_racing_empty_destination_is_never_replaced(tmp_path): + from MechInterp.weights.export import _rename_create_only + + source, destination = tmp_path / "staged", tmp_path / "destination" + source.mkdir() + (source / "payload").write_text("preserve") + destination.mkdir() + with pytest.raises((WeightPatchError, FileExistsError)): + _rename_create_only(source, destination) + assert not list(destination.iterdir()) + assert (source / "payload").read_text() == "preserve" + + +def test_export_without_exclusive_rename_verifies_files_and_publishes_manifest_last(tmp_path, ckpt_dir, monkeypatch): + from MechInterp.weights import export as module + def unsupported(*args): + raise OSError(errno.EINVAL, "filesystem does not support rename flags") + monkeypatch.setattr(module, "_rename_create_only", unsupported) + out = tmp_path / "exported" + result = export_patch_config(_std_spec(tmp_path, ckpt_dir, export_dir=out)) + manifest = json.loads((out / module.MANIFEST_NAME).read_text()) + assert result["written"] and manifest == result["manifest"] + assert manifest["publication"] == {"method": "exclusive_directory_manifest_last", "atomic_directory_rename": False} + for name, info in {**manifest["output"]["weight_files"], **manifest["output"]["copied_files"]}.items(): + assert file_sha(out / name) == info["sha256"] + assert not [p for p in tmp_path.iterdir() if ".partial-" in p.name] + + +def test_export_fallback_refuses_a_racing_destination(tmp_path, ckpt_dir, monkeypatch): + from MechInterp.weights import export as module + out = tmp_path / "exported" + def racing(source, destination): + destination.mkdir() + (destination / "keep.txt").write_text("precious") + raise OSError(errno.EINVAL, "unsupported rename flags") + monkeypatch.setattr(module, "_rename_create_only", racing) + with refusal("output_exists"): + export_patch_config(_std_spec(tmp_path, ckpt_dir, export_dir=out)) + assert (out / "keep.txt").read_text() == "precious" + assert len(list(out.iterdir())) == 1 + + +def test_failed_fallback_never_publishes_manifest_or_deletes_foreign_files(tmp_path, ckpt_dir, monkeypatch): + from MechInterp.weights import export as module + out = tmp_path / "exported" + original_copy = module.shutil.copyfileobj + def unsupported(*args): + raise OSError(errno.EINVAL, "unsupported rename flags") + def fail_during_publication(source, sink, *args, **kwargs): + if ".partial-" in Path(source.name).parent.name: + (out / "keep.txt").write_text("precious") + sink.write(b"partial") + raise OSError(errno.EIO, "planted publication failure") + return original_copy(source, sink, *args, **kwargs) + monkeypatch.setattr(module, "_rename_create_only", unsupported) + monkeypatch.setattr(module.shutil, "copyfileobj", fail_during_publication) + with pytest.raises(OSError, match="planted publication failure"): + export_patch_config(_std_spec(tmp_path, ckpt_dir, export_dir=out)) + assert not (out / module.MANIFEST_NAME).exists() + assert (out / "keep.txt").read_text() == "precious" + assert len(list(out.iterdir())) == 1 + + +def test_fallback_rejects_corrupted_copies(tmp_path, ckpt_dir, monkeypatch): + from MechInterp.weights import export as module + out = tmp_path / "exported" + original_copy = module.shutil.copyfileobj + def unsupported(*args): + raise OSError(errno.EOPNOTSUPP, "unsupported rename flags") + def corrupt(source, sink, *args, **kwargs): + if ".partial-" in Path(source.name).parent.name: + sink.write(b"corrupt") + return None + return original_copy(source, sink, *args, **kwargs) + monkeypatch.setattr(module, "_rename_create_only", unsupported) + monkeypatch.setattr(module.shutil, "copyfileobj", corrupt) + with refusal("apply"): + export_patch_config(_std_spec(tmp_path, ckpt_dir, export_dir=out)) + assert not out.exists() + + +def test_export_does_not_fallback_on_permission_failure(tmp_path, ckpt_dir, monkeypatch): + from MechInterp.weights import export as module + out = tmp_path / "exported" + def denied(*args): + raise OSError(errno.EACCES, "permission denied") + monkeypatch.setattr(module, "_rename_create_only", denied) + with pytest.raises(OSError) as exc: + export_patch_config(_std_spec(tmp_path, ckpt_dir, export_dir=out)) + assert exc.value.errno == errno.EACCES and not out.exists() diff --git a/tests/mech_interp/test_weight_patch_runtime.py b/tests/mech_interp/test_weight_patch_runtime.py new file mode 100644 index 000000000..9b9448594 --- /dev/null +++ b/tests/mech_interp/test_weight_patch_runtime.py @@ -0,0 +1,610 @@ +"""CPU tests for the loader/config/lineage wiring of ``surface.weight_patch``, +the dose-calibrate revision fix, pipeline module-form commands and CLI surface.""" + +from __future__ import annotations + +import json +import os +from argparse import Namespace +from pathlib import Path + +import pytest +import torch +import yaml + +from MechInterp import cell as cell_mod +from MechInterp import cli as mi_cli +from MechInterp.config import ( + DoseCalibrationConfig, + ExtractConfig, + SteerCellConfig, + load_dose_calibration_config, + load_extract_config, + load_steer_config, +) +from MechInterp.pipeline import ( + PipelineConfig, + _env_for_stage, + build_pipeline_plan, +) +from tests.mech_interp.test_batched_generation import _build_tiny_model, _build_tiny_tokenizer +from tests.mech_interp.weight_patch_fixtures import ( + OTHER_REVISION, + REVISION, + file_sha, + make_spec, + write_checkpoint, +) + +# Golden config shas computed from the BASE commit (11e8da19) before weight_patch +# existed; an absent patch must keep hashing exactly the same. +GOLDEN_STEER_SHA = "cdb718c556dfa0f765683d05d1d4bd0b9f71ae141a45be312f9c765853a0f329" +GOLDEN_DOSE_SHA = "b042dd7cefa36c27e154b973c68b0fe57f497e58aafd475fc99e47f6183d77dc" + + +def render_row(row: dict) -> str: # referenced by "module:callable" specs + return row["prompt"] + + +def _steer_cfg(**surface_extra): + return SteerCellConfig( + surface={ + "rows_path": "rows.jsonl", + "generation": {"max_new_tokens": 8}, + "seed": 3, + **surface_extra, + }, + readouts=[{"name": "axis", "path": "axis.json"}], + law={"kind": "erase_write", "readout": "axis", "position": "final"}, + arms=[{"name": "baseline", "strength": 0.0}, {"name": "dose", "strength": 1.5}], + execution={"output_path": "out.jsonl", "render_fn": "m:r"}, + ) + + +def _dose_cfg(**surface_extra): + return DoseCalibrationConfig( + surface={"rows_path": "rows.jsonl", **surface_extra}, + readouts=[{"name": "axis", "path": "axis.json"}], + law={"kind": "additive", "readout": "axis"}, + calibration={"doses": [0.0, 1.0]}, + execution={"output_path": "o.jsonl", "summary_path": "s.json"}, + ) + + +# -------------------------------------------------------------------------- +# Config + fingerprint +# -------------------------------------------------------------------------- + + +def test_absent_weight_patch_keeps_historical_config_shas(): + assert cell_mod.compute_config_sha(_steer_cfg()) == GOLDEN_STEER_SHA + assert cell_mod.compute_config_sha(_dose_cfg()) == GOLDEN_DOSE_SHA + + +def test_weight_patch_changes_config_sha_and_pins_content(): + ref_a = {"path": "p.yaml", "sha256": "a" * 64} + ref_b = {"path": "p.yaml", "sha256": "b" * 64} + sha_none = cell_mod.compute_config_sha(_steer_cfg()) + sha_a = cell_mod.compute_config_sha(_steer_cfg(weight_patch=ref_a)) + sha_b = cell_mod.compute_config_sha(_steer_cfg(weight_patch=ref_b)) + assert len({sha_none, sha_a, sha_b}) == 3 + assert cell_mod.compute_config_sha(_dose_cfg(weight_patch=ref_a)) != GOLDEN_DOSE_SHA + + +@pytest.mark.parametrize( + "bad", + [{"path": "p.yaml"}, {"path": "p.yaml", "sha256": "short"}, {"path": "p.yaml", "sha256": "A" * 64}, + {"path": "p.yaml", "sha256": "a" * 64, "extra": 1}], +) +def test_weight_patch_ref_requires_exact_sha(bad): + with pytest.raises(Exception): + _steer_cfg(weight_patch=bad) + + +def test_extract_config_capture_sites_validation(): + base = dict(rows_path="r.jsonl", output_dir="out", render_fn="m:r", content_end_fn="m:c") + cfg = ExtractConfig(**base, capture_sites=[{"layer": 20, "module": "mlp.down_proj", "tensor": "input"}]) + assert cfg.capture_sites[0].layer == 20 + assert ExtractConfig(**base).capture_sites is None and ExtractConfig(**base).weight_patch is None + for bad in ( + [], + [{"layer": -1, "module": "mlp.down_proj", "tensor": "input"}], + [{"layer": 1, "module": "mlp..down", "tensor": "input"}], + [{"layer": 1, "module": "mlp.down_proj", "tensor": "weights"}], + [{"layer": 1, "module": "mlp.down_proj", "tensor": "input", "x": 1}], + [{"layer": 1, "module": "m", "tensor": "input"}] * 2, + ): + with pytest.raises(Exception): + ExtractConfig(**base, capture_sites=bad) + + +def test_loaders_accept_and_resolve_weight_patch(tmp_path): + p = tmp_path / "steer.yaml" + data = _steer_cfg(weight_patch={"path": "patch.yaml", "sha256": "c" * 64}).model_dump(mode="json") + p.write_text(yaml.safe_dump(data)) + assert load_steer_config(p).surface.weight_patch.sha256 == "c" * 64 + d = tmp_path / "dose.yaml" + d.write_text(yaml.safe_dump(_dose_cfg(weight_patch={"path": "patch.yaml", "sha256": "c" * 64}).model_dump(mode="json"))) + assert load_dose_calibration_config(d).surface.weight_patch.path == "patch.yaml" + e = tmp_path / "ex.yaml" + e.write_text(yaml.safe_dump({ + "rows_path": "r.jsonl", "output_dir": "o", "render_fn": "m:r", "content_end_fn": "m:c", + "weight_patch": {"path": "patch.yaml", "sha256": "c" * 64}, + "capture_sites": [{"layer": 3, "module": "mlp.down_proj", "tensor": "input"}], + })) + cfg = load_extract_config(e) + assert cfg.weight_patch.sha256 == "c" * 64 and cfg.capture_sites[0].module == "mlp.down_proj" + + +# -------------------------------------------------------------------------- +# Smoke state + resume lineage +# -------------------------------------------------------------------------- + + +def test_smoke_state_binds_patch_digest_and_legacy_states_still_match(tmp_path): + out = tmp_path / "o.jsonl" + cell_mod.record_smoke(out, "sha1", {"passed": True}) + assert "weight_patch_digest" not in json.loads(cell_mod.smoke_state_path(out).read_text()) + assert cell_mod.smoke_passed(out, "sha1") # unchanged legacy behavior + assert not cell_mod.smoke_passed(out, "sha1", "d" * 64) # a patched run needs its own smoke + cell_mod.record_smoke(out, "sha1", {"passed": True}, patch_digest="d" * 64) + assert cell_mod.smoke_passed(out, "sha1", "d" * 64) + assert not cell_mod.smoke_passed(out, "sha1", "e" * 64) + assert not cell_mod.smoke_passed(out, "sha1") # patch removed -> smoke not reusable + assert not cell_mod.smoke_passed(out, "sha2", "d" * 64) + + +def _receipt(digest="d" * 64): + return {"patch_digest": digest, "spec_sha256": "1" * 64, "payload_sha256": "2" * 64, "revision": REVISION} + + +def test_lineage_creates_then_enforces_and_never_rewrites(tmp_path): + out = tmp_path / "rows.jsonl" + cell_mod.enforce_weight_patch_lineage(out, None) # no patch, no file: no-op + assert not cell_mod.weight_patch_lineage_path(out).exists() + + cell_mod.enforce_weight_patch_lineage(out, _receipt()) + lineage = cell_mod.weight_patch_lineage_path(out) + assert json.loads(lineage.read_text())["patch_digest"] == "d" * 64 + cell_mod.enforce_weight_patch_lineage(out, _receipt()) # same digest resumes + with pytest.raises(cell_mod.WeightPatchLineageError): + cell_mod.enforce_weight_patch_lineage(out, _receipt("e" * 64)) # patch changed + with pytest.raises(cell_mod.WeightPatchLineageError): + cell_mod.enforce_weight_patch_lineage(out, None) # patch removed + assert json.loads(lineage.read_text())["patch_digest"] == "d" * 64 + + +def test_lineage_refuses_patch_over_pre_existing_unbound_rows(tmp_path): + out = tmp_path / "rows.jsonl" + out.write_text('{"row_key": "a"}\n') + with pytest.raises(cell_mod.WeightPatchLineageError): + cell_mod.enforce_weight_patch_lineage(out, _receipt()) + cell_mod.enforce_weight_patch_lineage(out, None) # historical unpatched resume unchanged + + +def test_corrupt_lineage_record_refuses(tmp_path): + out = tmp_path / "rows.jsonl" + cell_mod.weight_patch_lineage_path(out).write_text("{not json") + with pytest.raises(cell_mod.WeightPatchLineageError): + cell_mod.enforce_weight_patch_lineage(out, _receipt()) + + +# -------------------------------------------------------------------------- +# Loader hook ordering (real _load_model_and_tokenizer, fake transformers) +# -------------------------------------------------------------------------- + + +def test_post_base_load_runs_after_base_load_and_before_adapter(monkeypatch): + import transformers + + events = [] + + class FakeConfig: + pass + + class FakeModel(torch.nn.Module): + def eval(self): + events.append("eval") + return self + + class FakeAuto: + _model_mapping = {FakeConfig: FakeModel} + @staticmethod + def from_pretrained(name, **kw): + events.append(("model", kw.get("revision"))) + return FakeModel() + + class FakeTok: + pad_token = "p" + eos_token = "e" + + @staticmethod + def from_pretrained(name, **kw): + return FakeTok() + + monkeypatch.setattr(transformers, "AutoModelForCausalLM", FakeAuto) + monkeypatch.setattr(transformers.AutoConfig, "from_pretrained", lambda *a, **k: FakeConfig()) + monkeypatch.setattr(transformers, "AutoTokenizer", FakeTok) + model, _ = mi_cli._load_model_and_tokenizer( + "m", None, REVISION, post_base_load=lambda m: events.append(("hook", type(m).__name__)) + ) + assert events == [("model", REVISION), ("hook", "FakeModel"), "eval"] + events.clear() + mi_cli._load_model_and_tokenizer("m", None, None) # no hook: unchanged path + assert events == [("model", None), "eval"] + + +# -------------------------------------------------------------------------- +# End-to-end steer with a tiny real GPT-2 (patch applied before generation) +# -------------------------------------------------------------------------- + +TARGET = "transformer.h.0.mlp.c_proj.weight" + + +def _write_rows_and_axis(tmp: Path): + tmp.mkdir(parents=True, exist_ok=True) + rows = [{"row_key": f"r{i}", "prompt": p} for i, p in enumerate( + ["w1 w2 w3", "w4 w5 w6 w7", "w9 w10"] + )] + (tmp / "rows.jsonl").write_text("".join(json.dumps(r) + "\n" for r in rows)) + g = torch.Generator().manual_seed(2) + v = torch.randn(32, generator=g) + v = (v / v.norm()).tolist() + (tmp / "axis.json").write_text(json.dumps({"layer": 0, "hidden_dim": 32, "vector": v, "sigma": 1.0})) + + +def _patch_spec(tmp: Path, scale: float, name: str = "patch") -> tuple[Path, str]: + model = _build_tiny_model() + w = dict(model.named_parameters())[TARGET].detach() + g = torch.Generator().manual_seed(11) + spec = make_spec( + tmp, + {TARGET: w}, + [{"id": "edit", "tensor": TARGET, "op": "add_rank_one", "scale": scale, "arrays": {"u": "u", "v": "v"}}], + {"u": torch.randn(w.shape[0], generator=g), "v": torch.randn(w.shape[1], generator=g)}, + budget={"allowed_tensors": ["transformer.h.*"], "max_relative_frobenius": 1000.0}, + name=name, + ) + return spec, file_sha(spec) + + +def _write_steer_config(tmp: Path, out_name: str, patch=None) -> Path: + surface = { + "rows_path": str(tmp / "rows.jsonl"), + "generation": {"max_new_tokens": 5, "do_sample": False}, + } + if patch is not None: + surface["weight_patch"] = {"path": str(patch[0]), "sha256": patch[1]} + cfg = { + "surface": surface, + "readouts": [{"name": "axis", "path": str(tmp / "axis.json")}], + "law": {"kind": "additive", "readout": "axis", "position": "anchor"}, + "arms": [{"name": "baseline", "strength": 0.0}, {"name": "dose", "strength": 1.0}], + "execution": {"output_path": str(tmp / out_name), "render_fn": f"{__name__}:render_row"}, + } + p = tmp / f"{out_name}.cfg.yaml" + p.write_text(yaml.safe_dump(cfg)) + return p + + +@pytest.fixture +def steer_env(tmp_path, monkeypatch): + _write_rows_and_axis(tmp_path) + seen = {"loads": []} + + def fake_load(model_name, adapter=None, revision=None, post_base_load=None): + model = _build_tiny_model() + seen["loads"].append({"revision": revision, "hook": post_base_load is not None}) + if post_base_load is not None: + post_base_load(model) + return model, _build_tiny_tokenizer() + + monkeypatch.setattr(mi_cli, "_load_model_and_tokenizer", fake_load) + return tmp_path, seen + + +def _run(tmp, cfg_path, revision=REVISION): + cfg = load_steer_config(cfg_path) + return mi_cli.run_steer(cfg, "tiny", revision, None, f"{__name__}:render_row", True) + + +def _texts(path: Path, arm: str): + rows = [json.loads(line) for line in path.read_text().splitlines()] + return [r["answer_text"] for r in rows if r["arm"] == arm] + + +def test_steer_applies_patch_before_generation_and_binds_lineage(steer_env, capsys): + tmp, seen = steer_env + assert _run(tmp, _write_steer_config(tmp, "plain.jsonl"), None) == 0 + patch = _patch_spec(tmp / "p", scale=0.05) + cfg_path = _write_steer_config(tmp, "patched.jsonl", patch) + assert _run(tmp, cfg_path) == 0 + assert seen["loads"][-1] == {"revision": REVISION, "hook": True} + + plain = _texts(tmp / "plain.jsonl", "baseline") + patched = _texts(tmp / "patched.jsonl", "baseline") + assert patched != plain # the edited weights were in place for generation + + rows = [json.loads(l) for l in (tmp / "patched.jsonl").read_text().splitlines()] + digest = rows[0]["weight_patch_digest"] + assert all(r["weight_patch_digest"] == digest for r in rows) + assert not any("weight_patch_digest" in json.loads(l) for l in (tmp / "plain.jsonl").read_text().splitlines()) + manifest = json.loads((tmp / "patched.jsonl.manifest.json").read_text()) + assert manifest["weight_patch"]["patch_digest"] == digest + assert manifest["surface"]["weight_patch"]["sha256"] == patch[1] + assert "weight_patch" not in json.loads((tmp / "plain.jsonl.manifest.json").read_text())["surface"] + assert json.loads(cell_mod.weight_patch_lineage_path(tmp / "patched.jsonl").read_text())["patch_digest"] == digest + assert json.loads(cell_mod.smoke_state_path(tmp / "patched.jsonl").read_text())["weight_patch_digest"] == digest + + before = (tmp / "patched.jsonl").read_text() + assert _run(tmp, cfg_path) == 0 # same patch resumes: nothing pending, nothing rewritten + assert (tmp / "patched.jsonl").read_text() == before + + +def test_zero_patch_run_matches_unpatched_outputs(steer_env): + tmp, _ = steer_env + assert _run(tmp, _write_steer_config(tmp, "plain.jsonl"), None) == 0 + zero = _patch_spec(tmp / "z", scale=0.0) + assert _run(tmp, _write_steer_config(tmp, "zero.jsonl", zero)) == 0 + for arm in ("baseline", "dose"): + assert _texts(tmp / "zero.jsonl", arm) == _texts(tmp / "plain.jsonl", arm) + manifest = json.loads((tmp / "zero.jsonl.manifest.json").read_text()) + assert manifest["weight_patch"]["noop"] is True + + +def test_stale_resume_is_refused_when_patch_changes_or_disappears(steer_env, capsys): + tmp, _ = steer_env + first = _patch_spec(tmp / "a", scale=0.05) + assert _run(tmp, _write_steer_config(tmp, "rows_out.jsonl", first)) == 0 + rows_before = (tmp / "rows_out.jsonl").read_text() + + second = _patch_spec(tmp / "b", scale=0.025) + assert _run(tmp, _write_steer_config(tmp, "rows_out.jsonl", second)) == mi_cli.EXIT_PATCH_LINEAGE + assert _run(tmp, _write_steer_config(tmp, "rows_out.jsonl", None)) == mi_cli.EXIT_PATCH_LINEAGE + assert (tmp / "rows_out.jsonl").read_text() == rows_before # nothing spliced in + + +def test_patch_refusals_return_7_before_any_row_is_written(steer_env, capsys): + tmp, seen = steer_env + spec, sha = _patch_spec(tmp / "p", scale=0.01) + # wrong pinned sha in the config + assert _run(tmp, _write_steer_config(tmp, "a.jsonl", (spec, "0" * 64))) == mi_cli.EXIT_PATCH_REFUSED + # spec edited on disk after pinning + spec.write_text(spec.read_text() + "\n# edited\n") + assert _run(tmp, _write_steer_config(tmp, "b.jsonl", (spec, sha))) == mi_cli.EXIT_PATCH_REFUSED + # missing / wrong declared model revision + spec2, sha2 = _patch_spec(tmp / "q", scale=0.01) + cfg = _write_steer_config(tmp, "c.jsonl", (spec2, sha2)) + assert _run(tmp, cfg, None) == mi_cli.EXIT_PATCH_REFUSED + assert _run(tmp, cfg, OTHER_REVISION) == mi_cli.EXIT_PATCH_REFUSED + assert not seen["loads"] # all refused before the model was even loaded + # payload tampered + payload = next((tmp / "q").glob("*.payload.safetensors")) + payload.write_bytes(payload.read_bytes()[:-1] + b"\x00") + assert _run(tmp, cfg) == mi_cli.EXIT_PATCH_REFUSED + for name in "abc": + assert not (tmp / f"{name}.jsonl").exists() + out = capsys.readouterr().out + assert "Weight patch refused" in out + + +def test_wrong_loaded_base_is_refused_after_load(steer_env, monkeypatch): + tmp, _ = steer_env + spec, sha = _patch_spec(tmp / "p", scale=0.01) + + def other_base(model_name, adapter=None, revision=None, post_base_load=None): + model = _build_tiny_model() + with torch.no_grad(): + dict(model.named_parameters())[TARGET].add_(1.0) + post_base_load(model) + return model, _build_tiny_tokenizer() + + monkeypatch.setattr(mi_cli, "_load_model_and_tokenizer", other_base) + assert _run(tmp, _write_steer_config(tmp, "x.jsonl", (spec, sha))) == mi_cli.EXIT_PATCH_REFUSED + assert not (tmp / "x.jsonl").exists() + + +# -------------------------------------------------------------------------- +# dose-calibrate revision + pipeline module form +# -------------------------------------------------------------------------- + + +class _Stop(Exception): + pass + + +def test_run_dose_calibration_propagates_exact_revision(tmp_path, monkeypatch): + _write_rows_and_axis(tmp_path) + cfg = DoseCalibrationConfig( + surface={"rows_path": str(tmp_path / "rows.jsonl")}, + readouts=[{"name": "axis", "path": str(tmp_path / "axis.json")}], + law={"kind": "additive", "readout": "axis", "layer": 0}, + calibration={"doses": [1.0]}, + execution={"output_path": str(tmp_path / "o.jsonl"), "summary_path": str(tmp_path / "s.json")}, + ) + captured = {} + + def fake_load(model_name, adapter=None, revision=None, post_base_load=None): + captured.update(model=model_name, adapter=adapter, revision=revision, hook=post_base_load) + raise _Stop + + monkeypatch.setattr(mi_cli, "_load_model_and_tokenizer", fake_load) + with pytest.raises(_Stop): + mi_cli.run_dose_calibration(cfg, "m", None, f"{__name__}:render_row", True, revision=REVISION) + assert captured["revision"] == REVISION and captured["hook"] is None + with pytest.raises(_Stop): + mi_cli.run_dose_calibration(cfg, "m", None, f"{__name__}:render_row", True) + assert captured["revision"] is None # absent revision behaves as before + + +def _write_dose_yaml(tmp: Path) -> Path: + p = tmp / "dose.yaml" + p.write_text(yaml.safe_dump(_dose_cfg().model_dump(mode="json"))) + return p + + +def test_pipeline_dose_stage_passes_stage_and_global_revision(tmp_path): + cfg_path = _write_dose_yaml(tmp_path) + for stage_rev, global_rev, expect in ((None, REVISION, REVISION), (OTHER_REVISION, REVISION, OTHER_REVISION), (None, None, None)): + cfg = PipelineConfig( + name="d", model="Tiny/Model", model_revision=global_rev, runtime={"python": "python"}, + stages=[{"name": "dose", "kind": "mechinterp.dose-calibrate", "config": str(cfg_path), "model_revision": stage_rev}], + ) + cmd = build_pipeline_plan(cfg, repo_root=tmp_path, provider="local")["stages"][0]["command"] + if expect is None: + assert "--model-revision" not in cmd + else: + assert cmd[cmd.index("--model-revision") + 1] == expect + + +def test_pipeline_commands_use_installed_module_form_for_every_verb(tmp_path): + cfg_path = _write_dose_yaml(tmp_path) + cfg = PipelineConfig( + name="all", model="M", runtime={"python": "pyx"}, + stages=[ + {"name": "e", "kind": "mechinterp.extract", "config": "e.yaml"}, + {"name": "p", "kind": "mechinterp.probe-fit", "config": "p.yaml"}, + {"name": "s", "kind": "mechinterp.steer", "config": "s.yaml", "render_fn": "m:r"}, + {"name": "d", "kind": "mechinterp.dose-calibrate", "config": str(cfg_path)}, + {"name": "g", "kind": "mechinterp.score-gates", "gates_config": "g.yaml", "rows_path": "r.jsonl"}, + ], + ) + for stage in build_pipeline_plan(cfg, repo_root=tmp_path, provider="local")["stages"]: + assert stage["command"][:4] == ["pyx", "-m", "tuner", "mechinterp"], stage["name"] + assert not any(str(a).endswith("tuner.py") for a in stage["command"]) + + +def test_stage_env_puts_source_checkout_engine_on_pythonpath_only_when_present(tmp_path): + cfg = PipelineConfig(name="x", stages=[{"name": "e", "kind": "mechinterp.extract", "config": "e.yaml"}]) + stage = cfg.stages[0] + engine = tmp_path / "engine" + (engine / "tuner").mkdir(parents=True) + (engine / "tuner" / "__main__.py").write_text("") + (engine / "tuner.py").write_text("") + (engine / "pyproject.toml").write_text("") + env = _env_for_stage(cfg, stage, engine) + assert env["PYTHONPATH"].split(os.pathsep)[0] == str(engine) + bare = tmp_path / "wheel_like" + (bare / "tuner").mkdir(parents=True) + (bare / "tuner" / "__main__.py").write_text("") + assert str(bare) not in _env_for_stage(cfg, stage, bare).get("PYTHONPATH", "") + command = PipelineConfig(name="c", stages=[{"name": "c", "kind": "command", "command": ["true"]}]) + assert str(engine) not in _env_for_stage(command, command.stages[0], engine).get("PYTHONPATH", "") + + +# -------------------------------------------------------------------------- +# CLI surface (parser + handler) +# -------------------------------------------------------------------------- + + +def test_parser_accepts_weights_flags_and_keeps_export_config(): + from tuner.cli.parser import create_parser + + parser = create_parser() + args = parser.parse_args(["mechinterp", "weights-patch", "--weights-config", "w.yaml", "--validate"]) + assert (args.command, args.subcommand, args.weights_config) == ("mechinterp", "weights-patch", "w.yaml") + assert args.weights_validate is True and args.weights_export is False + args = parser.parse_args(["mechinterp", "weights-patch", "--weights-config", "w.yaml", "--export"]) + assert args.weights_export is True and args.weights_validate is False + args = parser.parse_args(["mechinterp", "weights-inspect", "--weights-config", "i.yaml"]) + assert args.subcommand == "weights-inspect" and args.weights_validate is False + args = parser.parse_args(["flywheel", "export-fixtures", "--export-config", "e.yaml"]) + assert args.export_config == "e.yaml" and args.weights_export is False + args = parser.parse_args(["mechinterp", "dose-calibrate", "--mi-config", "d.yaml", "--model", "m", "--model-revision", REVISION]) + assert args.model_revision == REVISION + + +def _handler(**kw): + from tuner.handlers.mechinterp_handler import MechInterpHandler + + base = dict(json=True, weights_validate=False, weights_export=False) + base.update(kw) + return MechInterpHandler(args=Namespace(**base)) + + +@pytest.fixture +def cli_ckpt(tmp_path): + root = tmp_path / "ck" + tensors = write_checkpoint(root) + from tests.mech_interp.weight_patch_fixtures import standard_ops_and_arrays + + ops, arrays = standard_ops_and_arrays() + spec = make_spec( + tmp_path / "s", tensors, ops, arrays, checkpoint=root, + base_extra={"index_sha256": file_sha(root / "model.safetensors.index.json")}, + export_dir=tmp_path / "exp", + ) + return tmp_path, root, spec + + +def test_handler_inspect_validate_export_and_flag_exclusivity(cli_ckpt, capsys): + tmp, root, spec = cli_ckpt + inspect_cfg = tmp / "inspect.yaml" + inspect_cfg.write_text(yaml.safe_dump({ + "schema_version": "mechinterp-weights-inspect/v1", "checkpoint": str(root), + "tensors": ["blk.0.*"], "hash_tensors": True, + })) + assert _handler(subcommand="weights-inspect", weights_config=str(inspect_cfg)).handle() == 0 + out = json.loads(capsys.readouterr().out) + assert out["success"] and out["data"]["n_tensors"] == 5 and len(out["data"]["tensors"]) == 3 + + h = lambda **kw: _handler(subcommand="weights-patch", weights_config=str(spec), **kw) # noqa: E731 + assert h().handle() == 1 # neither flag + assert h(weights_validate=True, weights_export=True).handle() == 1 # both + capsys.readouterr() + assert h(weights_validate=True).handle() == 0 + out = json.loads(capsys.readouterr().out) + assert out["data"]["written"] is False and not (tmp / "exp").exists() + assert out["data"]["receipt"]["patch_digest"] + + assert h(weights_export=True).handle() == 0 + exported = json.loads(capsys.readouterr().out)["data"] + assert (tmp / "exp" / "mechinterp-weight-export.manifest.json").is_file() + assert exported["patch_digest"] == out["data"]["receipt"]["patch_digest"] + + assert h(weights_export=True).handle() == 1 # second export refused + err = capsys.readouterr().out + assert "WEIGHTS_OUTPUT_EXISTS" in err + + +def test_handler_refusal_codes_surface(cli_ckpt, capsys): + tmp, root, spec = cli_ckpt + data = yaml.safe_load(spec.read_text()) + data["budget"]["max_relative_frobenius"] = 1e-9 + spec.write_text(yaml.safe_dump(data)) + h = _handler(subcommand="weights-patch", weights_config=str(spec), weights_validate=True) + assert h.handle() == 1 + assert "WEIGHTS_BUDGET" in capsys.readouterr().out + missing = _handler(subcommand="weights-inspect", weights_config=str(tmp / "nope.yaml")) + assert missing.handle() == 1 + + +def test_handler_dose_calibrate_forwards_model_revision(tmp_path, monkeypatch): + seen = {} + + def fake_run(config, **kw): + seen.update(kw) + return 0 + + monkeypatch.setattr(mi_cli, "run_dose_calibration", fake_run) + d = tmp_path / "dose.yaml" + cfg = _dose_cfg().model_dump(mode="json") + cfg["execution"]["render_fn"] = f"{__name__}:render_row" + d.write_text(yaml.safe_dump(cfg)) + h = _handler( + subcommand="dose-calibrate", mechinterp_config=str(d), model="Org/Model", + model_revision=REVISION, adapter=None, render_fn=None, i_know_this_runs_on_gpu=True, + ) + assert h.handle() == 0 + assert seen["revision"] == REVISION and seen["model_name"] == "Org/Model" + + +def test_handler_extract_forwards_project_context(tmp_path, monkeypatch): + seen = {} + monkeypatch.setattr(mi_cli, "run_extract", lambda config, **kw: seen.update(kw) or 0) + e = tmp_path / "ex.yaml" + e.write_text(yaml.safe_dump({"rows_path": "r", "output_dir": "o", "render_fn": "m:r", "content_end_fn": "m:c"})) + h = _handler(subcommand="extract", mechinterp_config=str(e), model="M", model_revision=REVISION, + adapter=None, i_know_this_runs_on_gpu=True) + assert h.handle() == 0 + assert seen["project_context"] is h.context and seen["revision"] == REVISION diff --git a/tests/mech_interp/test_weights_projection.py b/tests/mech_interp/test_weights_projection.py new file mode 100644 index 000000000..4002c689d --- /dev/null +++ b/tests/mech_interp/test_weights_projection.py @@ -0,0 +1,215 @@ +"""CPU tests for bounded numeric reads in ``weights-inspect`` (projections).""" + +from __future__ import annotations + +import json +from argparse import Namespace + +import pytest +import torch +import yaml +from safetensors.torch import save_file + +from MechInterp.weights.errors import WeightPatchError +from MechInterp.weights.spec import parse_inspect_request +from MechInterp.weights.workflow import inspect_from_config +from tests.mech_interp.weight_patch_fixtures import ( + DOWN0, + GATE0, + NORM, + base_tensors, + file_sha, + write_checkpoint, +) + + +def refusal(code): + return pytest.raises(WeightPatchError, match=rf"^\[{code}\]") + + +@pytest.fixture +def env(tmp_path): + tensors = base_tensors() + tensors[DOWN0][:, 5] = 0.0 # a zero column for the cosine-null case + root = tmp_path / "ck" + write_checkpoint(root, tensors) + vec = torch.randn(8, generator=torch.Generator().manual_seed(3)) + save_file({"axis": vec}, str(tmp_path / "vec.safetensors")) + (tmp_path / "dir.json").write_text( + json.dumps({"schema_version": "mechinterp-direction/v1", "vector": vec.tolist()}) + ) + return tmp_path, root, tensors, vec + + +def _inspect(tmp, root, projections, **extra): + doc = { + "schema_version": "mechinterp-weights-inspect/v1", + "checkpoint": str(root), + "projections": projections, + **extra, + } + p = tmp / "inspect.yaml" + p.write_text(yaml.safe_dump(doc)) + return inspect_from_config(p) + + +def _vec_ref(tmp): + return {"safetensors": {"path": str(tmp / "vec.safetensors"), "key": "axis", "sha256": file_sha(tmp / "vec.safetensors")}} + + +def test_selected_column_dots_match_manual_float64_reference(env): + tmp, root, tensors, vec = env + idx = [0, 3, 9, 15] + report = _inspect(tmp, root, [{"id": "d", "tensor": DOWN0, "axis": "cols", "indices": idx, "vector": _vec_ref(tmp), "include_norms": True}]) + (p,) = report["projections"] + w = tensors[DOWN0].double() # [8, 16] + expected = [float(w[:, j] @ vec.double()) for j in idx] + assert p["values"] == pytest.approx(expected, rel=1e-12, abs=1e-12) + assert p["line_norms"] == pytest.approx([float(w[:, j].norm()) for j in idx], rel=1e-12) + assert p["indices"] == idx and p["n_values"] == 8 and p["kind"] == "dot" + assert p["shape"] == [8, 16] and p["dtype"] == "bfloat16" + from tests.mech_interp.weight_patch_fixtures import raw_sha + assert p["tensor_sha256"] == raw_sha(tensors[DOWN0]) + assert p["vector"]["source"] == "safetensors" and p["vector"]["length"] == 8 + assert p["vector"]["l2_norm"] == pytest.approx(float(vec.double().norm())) + json.dumps(report, allow_nan=False) # strictly JSON-able + + +def test_all_lines_rows_axis_and_other_indices(env): + tmp, root, tensors, vec = env + sub = [1, 4, 6] + report = _inspect(tmp, root, [ + {"id": "all", "tensor": DOWN0, "axis": "cols", "vector": _vec_ref(tmp)}, + {"id": "rows", "tensor": GATE0, "axis": "rows", "indices": [2, 7], "other_indices": sub, + "vector": {"inline": [0.5, -1.0, 2.0]}}, + ]) + allp, rows = report["projections"] + assert allp["indices"] == "all" and len(allp["values"]) == 16 + w = tensors[DOWN0].double() + assert allp["values"] == pytest.approx([float(w[:, j] @ vec.double()) for j in range(16)], abs=1e-12) + g = tensors[GATE0].double() # [16, 8] + v = torch.tensor([0.5, -1.0, 2.0], dtype=torch.float64) + assert rows["values"] == pytest.approx([float(g[i, sub] @ v) for i in (2, 7)], abs=1e-12) + assert rows["other_indices"] == sub and rows["vector"]["source"] == "inline" + + +def test_cosine_and_zero_line_is_null(env): + tmp, root, tensors, vec = env + report = _inspect(tmp, root, [{"id": "c", "tensor": DOWN0, "kind": "cosine", "axis": "cols", "indices": [5, 2], "vector": _vec_ref(tmp)}]) + zero, other = report["projections"][0]["values"] + assert zero is None + w = tensors[DOWN0].double() + assert other == pytest.approx(float(w[:, 2] @ vec.double() / (w[:, 2].norm() * vec.double().norm())), abs=1e-12) + + +def test_slice_returns_exact_selected_values(env): + tmp, root, tensors, _ = env + report = _inspect(tmp, root, [{"id": "s", "tensor": GATE0, "kind": "slice", "axis": "rows", "indices": [3, 4], "other_indices": [0, 7]}]) + (p,) = report["projections"] + g = tensors[GATE0].double() + assert p["values"] == [[float(g[3, 0]), float(g[3, 7])], [float(g[4, 0]), float(g[4, 7])]] + assert p["n_values"] == 4 and "vector" not in p + + +def test_direction_json_vector_source(env): + tmp, root, tensors, vec = env + ref = {"direction_json": {"path": str(tmp / "dir.json"), "sha256": file_sha(tmp / "dir.json")}} + a = _inspect(tmp, root, [{"id": "a", "tensor": DOWN0, "axis": "cols", "indices": [1, 2], "vector": ref}]) + b = _inspect(tmp, root, [{"id": "a", "tensor": DOWN0, "axis": "cols", "indices": [1, 2], "vector": _vec_ref(tmp)}]) + assert a["projections"][0]["values"] == pytest.approx(b["projections"][0]["values"], abs=1e-6) + assert a["projections"][0]["vector"]["source"] == "direction_json" + (tmp / "dir.json").write_text(json.dumps({"schema_version": "other/v1", "vector": [1.0] * 8})) + ref["direction_json"]["sha256"] = file_sha(tmp / "dir.json") + with refusal("payload"): + _inspect(tmp, root, [{"id": "a", "tensor": DOWN0, "axis": "cols", "vector": ref}]) + + +def test_unsafe_or_unbounded_requests_are_refused(env): + tmp, root, tensors, _ = env + base = {"id": "p", "tensor": DOWN0, "axis": "cols", "vector": _vec_ref(tmp)} + + def run(**kw): + extra = kw.pop("extra", {}) + return _inspect(tmp, root, [{**base, **kw}], **extra) + + with refusal("payload"): + run(indices=[16]) # out of range + with refusal("payload"): + run(indices=[1, 1]) # not distinct + with refusal("payload"): + run(other_indices=[0, 1]) # vector length mismatch + with refusal("payload"): + run(tensor=NORM) # 1-D tensor + with refusal("binding"): + run(tensor="missing.weight") + with refusal("budget"): + run(extra={"max_output_values": 8}) # 16 lines > 8 + with refusal("budget"): + run(indices=[0, 1, 2], include_norms=True, extra={"max_output_values": 5}) + with refusal("budget"): + run(extra={"max_tensor_bytes": 16}) + with refusal("budget"): # slice size = lines * positions + _inspect(tmp, root, [{"id": "s", "tensor": GATE0, "kind": "slice", "axis": "rows"}], max_output_values=100) + # the total across requests is what is capped + with refusal("budget"): + _inspect(tmp, root, [ + {"id": "a", "tensor": DOWN0, "axis": "cols", "indices": [0, 1, 2], "vector": _vec_ref(tmp)}, + {"id": "b", "tensor": DOWN0, "axis": "cols", "indices": [3, 4, 5], "vector": _vec_ref(tmp)}, + ], max_output_values=5) + # pinned vector file must match its hash + bad = _vec_ref(tmp) + bad["safetensors"]["sha256"] = "0" * 64 + with refusal("payload"): + run(vector=bad) + + +def test_nonfinite_checkpoint_values_and_vectors_are_refused(env): + tmp, root, tensors, _ = env + inf = {k: v.clone() for k, v in tensors.items()} + inf[DOWN0][0, 0] = float("inf") + bad_root = tmp / "bad" + write_checkpoint(bad_root, inf) + with refusal("nonfinite"): + _inspect(tmp, bad_root, [{"id": "p", "tensor": DOWN0, "axis": "cols", "indices": [0], "vector": _vec_ref(tmp)}]) + with pytest.raises(WeightPatchError) as exc: # NaN inline is rejected by the schema + _inspect(tmp, root, [{"id": "p", "tensor": DOWN0, "axis": "cols", "vector": {"inline": [float("nan")] * 8}}]) + assert exc.value.code == "schema" + + +def test_schema_rules_for_projection_requests(env): + tmp, root, *_ = env + ok = {"schema_version": "mechinterp-weights-inspect/v1", "checkpoint": str(root)} + for bad in ( + {"id": "a", "tensor": DOWN0, "axis": "cols"}, # dot needs vector + {"id": "a", "tensor": DOWN0, "kind": "slice", "axis": "cols", "vector": {"inline": [1.0]}}, + {"id": "a", "tensor": DOWN0, "axis": "cols", "vector": {"inline": [1.0], "safetensors": {"path": "x", "key": "k", "sha256": "0" * 64}}}, + {"id": "a", "tensor": DOWN0, "axis": "diag", "vector": {"inline": [1.0]}}, + {"id": "a", "tensor": DOWN0, "axis": "cols", "vector": {"inline": [1.0]}, "surprise": 1}, + ): + with refusal("schema"): + parse_inspect_request({**ok, "projections": [bad]}) + twin = {"id": "a", "tensor": DOWN0, "axis": "cols", "vector": {"inline": [1.0]}} + with refusal("schema"): + parse_inspect_request({**ok, "projections": [twin, twin]}) + + +def test_inspect_without_projections_is_unchanged(env): + tmp, root, *_ = env + report = _inspect(tmp, root, []) + assert "projections" not in report + + +def test_cli_inspect_runs_projections_through_handler(env, capsys): + from tuner.handlers.mechinterp_handler import MechInterpHandler + + tmp, root, tensors, vec = env + cfg = tmp / "inspect.yaml" + cfg.write_text(yaml.safe_dump({ + "schema_version": "mechinterp-weights-inspect/v1", "checkpoint": "ck", + "projections": [{"id": "d", "tensor": DOWN0, "axis": "cols", "indices": [0], + "vector": {"safetensors": {"path": "vec.safetensors", "key": "axis", "sha256": file_sha(tmp / "vec.safetensors")}}}], + })) + h = MechInterpHandler(args=Namespace(json=True, subcommand="weights-inspect", weights_config=str(cfg))) + assert h.handle() == 0 + out = json.loads(capsys.readouterr().out) + assert out["data"]["projections"][0]["n_values"] == 1 # relative paths resolve against the document diff --git a/tests/mech_interp/weight_patch_fixtures.py b/tests/mech_interp/weight_patch_fixtures.py new file mode 100644 index 000000000..4ea9dafed --- /dev/null +++ b/tests/mech_interp/weight_patch_fixtures.py @@ -0,0 +1,162 @@ +"""Tiny local checkpoints and patch specs for CPU weight-patch tests. + +Hashes here are computed independently of the engine (raw dtype bytes via +``view(torch.uint8)``), so a bug in the engine's hashing cannot hide itself. +Nothing is downloaded; tensor names are arbitrary fixture names. +""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import torch +import yaml +from safetensors.torch import save_file + +REVISION = "a" * 40 +OTHER_REVISION = "b" * 40 + +DOWN0 = "blk.0.ffn.down.weight" # [out=8, in=16] +GATE0 = "blk.0.ffn.gate.weight" # [out=16, in=8] +DOWN1 = "blk.1.ffn.down.weight" # [8, 16] +EMBED = "tok.embed.weight" # [32, 8] +NORM = "blk.0.norm.weight" # float32 [8] + + +def raw_sha(t: torch.Tensor) -> str: + flat = t.detach().contiguous().reshape(-1) + return hashlib.sha256(flat.view(torch.uint8).numpy().tobytes()).hexdigest() + + +def file_sha(path: Path) -> str: + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def base_tensors(dtype=torch.bfloat16, seed: int = 0) -> dict[str, torch.Tensor]: + g = torch.Generator().manual_seed(seed) + + def rnd(*shape, dt=dtype): + return torch.randn(*shape, generator=g).to(dt) + + return { + DOWN0: rnd(8, 16), + GATE0: rnd(16, 8), + DOWN1: rnd(8, 16), + EMBED: rnd(32, 8), + NORM: rnd(8, dt=torch.float32), + } + + +def write_checkpoint(root: Path, tensors=None, *, sharded: bool = True) -> dict[str, torch.Tensor]: + """Write a checkpoint directory (sharded with an index, or one file).""" + tensors = tensors or base_tensors() + root.mkdir(parents=True, exist_ok=True) + (root / "config.json").write_text(json.dumps({"fixture": True})) + meta = {"format": "pt"} + if sharded: + shard_a = {k: tensors[k] for k in (DOWN0, GATE0, NORM)} + shard_b = {k: tensors[k] for k in (DOWN1, EMBED)} + save_file(shard_a, str(root / "model-00001-of-00002.safetensors"), metadata=meta) + save_file(shard_b, str(root / "model-00002-of-00002.safetensors"), metadata=meta) + weight_map = {k: "model-00001-of-00002.safetensors" for k in shard_a} + weight_map.update({k: "model-00002-of-00002.safetensors" for k in shard_b}) + total = sum(t.numel() * t.element_size() for t in tensors.values()) + (root / "model.safetensors.index.json").write_text( + json.dumps({"metadata": {"total_size": total}, "weight_map": weight_map}) + ) + else: + save_file(dict(tensors), str(root / "model.safetensors"), metadata=meta) + return tensors + + +def pin(t: torch.Tensor) -> dict: + return { + "dtype": str(t.dtype).removeprefix("torch."), + "shape": list(t.shape), + "sha256": raw_sha(t), + } + + +def make_spec( + tmp: Path, + tensors: dict[str, torch.Tensor], + operations: list[dict], + arrays: dict[str, torch.Tensor], + *, + checkpoint: Path | None = None, + budget: dict | None = None, + base_extra: dict | None = None, + export_dir: Path | None = None, + revision: str = REVISION, + name: str = "patch", +) -> Path: + """Write payload + spec YAML; return the spec path. Pins every targeted tensor.""" + tmp.mkdir(parents=True, exist_ok=True) + payload_path = tmp / f"{name}.payload.safetensors" + save_file({k: v.contiguous() for k, v in arrays.items()}, str(payload_path)) + targeted = [] + for op in operations: + if op["tensor"] not in targeted: + targeted.append(op["tensor"]) + base = { + "model_id": "fixture/model", + "revision": revision, + "tensors": {n: pin(tensors[n]) for n in targeted}, + } + if checkpoint is not None: + base["checkpoint"] = str(checkpoint) + base.update(base_extra or {}) + spec = { + "schema_version": "mechinterp-weight-patch/v1", + "base": base, + "budget": { + "allowed_tensors": ["blk.*"], + "max_modified_tensors": 4, + "max_modified_entries": 10_000, + "max_relative_frobenius": 5.0, + **(budget or {}), + }, + "payload": {"path": payload_path.name, "sha256": file_sha(payload_path)}, + "operations": operations, + } + if export_dir is not None: + spec["export"] = {"output_dir": str(export_dir)} + spec_path = tmp / f"{name}.yaml" + spec_path.write_text(yaml.safe_dump(spec, sort_keys=False)) + return spec_path + + +def rewrite_spec(spec_path: Path, mutate) -> None: + data = yaml.safe_load(spec_path.read_text()) + mutate(data) + spec_path.write_text(yaml.safe_dump(data, sort_keys=False)) + + +def standard_ops_and_arrays(seed: int = 1): + """rank-one on selected columns of DOWN0 + replace_rows on GATE0.""" + g = torch.Generator().manual_seed(seed) + ops = [ + { + "id": "r1", + "tensor": DOWN0, + "op": "add_rank_one", + "scale": 0.05, + "cols": [1, 4, 9], + "arrays": {"u": "r1.u", "v": "r1.v"}, + }, + { + "id": "rows", + "tensor": GATE0, + "op": "replace_rows", + "rows": [2, 5], + "arrays": {"values": "rows.values"}, + }, + ] + arrays = { + "r1.u": torch.randn(8, generator=g), + "r1.v": torch.randn(3, generator=g), + "rows.values": torch.randn(2, 8, generator=g), + } + return ops, arrays diff --git a/tuner/batch/engines/hf_batched.py b/tuner/batch/engines/hf_batched.py index 223a67b23..6a2d33863 100644 --- a/tuner/batch/engines/hf_batched.py +++ b/tuner/batch/engines/hf_batched.py @@ -23,6 +23,7 @@ from __future__ import annotations import os +import json from typing import Any, Callable, Dict, List, Optional from tuner.batch.engines.base import ( @@ -68,7 +69,8 @@ def __init__( tokenizer: Any = None, ): import torch - from transformers import AutoModelForCausalLM, AutoTokenizer + from transformers import AutoTokenizer + from shared.utilities.text_model import load_text_generation_model self.torch = torch if device is None: @@ -88,7 +90,7 @@ def __init__( torch_dtype = ( getattr(torch, dtype) if dtype else _select_dtype(torch, device) ) - model = AutoModelForCausalLM.from_pretrained( + model = load_text_generation_model( model_name, revision=revision, token=os.environ.get("HF_TOKEN") or None, @@ -186,7 +188,25 @@ def __init__( trust_remote_code: bool = False, model: Any = None, tokenizer: Any = None, + json_schema: Optional[dict] = None, + structured_output_backend: str = "auto", ): + if structured_output_backend not in ("auto", "xgrammar"): + raise ValueError("HF structured output backend must be auto or xgrammar") + self._compiled_grammar = None + self._grammar_processor = None + self._xgrammar_version = None + if json_schema is not None: + if not isinstance(json_schema, dict): + raise ValueError("json_schema must be a JSON object") + try: + import xgrammar as xgr + from xgrammar.contrib.hf import LogitsProcessor + except ImportError as exc: + raise RuntimeError("HF JSON-schema decoding requires the optional xgrammar package") from exc + self._grammar_processor = LogitsProcessor + from importlib.metadata import version + self._xgrammar_version = version("xgrammar") self.bundle = _ModelBundle( model_name, device=device, @@ -205,6 +225,18 @@ def __init__( self.seed = seed self.extra_eos_tokens = list(extra_eos_tokens) if extra_eos_tokens else [] self.stop = list(stop) if stop else [] + if json_schema is not None: + vocab_size = int(self.bundle.model.get_output_embeddings().weight.shape[0]) + info = xgr.TokenizerInfo.from_huggingface(self.bundle.tokenizer, vocab_size=vocab_size) + self._compiled_grammar = xgr.GrammarCompiler(info).compile_json_schema(json.dumps(json_schema)) + + def provenance(self): + from importlib.metadata import version + return {"engine": "hf-batched", "transformers": version("transformers"), + "torch": self.bundle.torch.__version__, "device": self.bundle.device, + "model_class": type(self.bundle.model).__name__, + "structured_output_backend": "xgrammar" if self._compiled_grammar is not None else None, + "xgrammar": self._xgrammar_version} def generate( self, @@ -263,6 +295,10 @@ def _generate_chunk(self, chunk: List[GenerateItem]) -> List[GenerateResult]: if self.do_sample: gen_kwargs["temperature"] = self.temperature gen_kwargs["top_p"] = self.top_p + if self._compiled_grammar is not None: + # A matcher is stateful: start fresh for every independent batch, + # including an OOM retry. Never carry its state between requests. + gen_kwargs["logits_processor"] = [self._grammar_processor(self._compiled_grammar)] with torch.no_grad(): out = model.generate( diff --git a/tuner/batch/runner.py b/tuner/batch/runner.py index c4bffbe18..14a5c9c14 100644 --- a/tuner/batch/runner.py +++ b/tuner/batch/runner.py @@ -152,10 +152,14 @@ def run_batch_generate( prompt_by_id[row_id] = r["prompt"] if json_schema is not None and not isinstance(json_schema, dict): raise ValueError("json_schema must be a JSON object") - if json_schema is not None and engine != "vllm": - raise ValueError("json_schema structured outputs require engine='vllm'") - if engine != "vllm" and structured_output_backend != "auto": - raise ValueError("structured_output_backend requires engine='vllm'") + if json_schema is not None and engine not in {"vllm", "hf-batched"}: + raise ValueError("json_schema structured outputs require vllm or hf-batched") + if engine != "vllm" and structured_output_backend != "auto" and not ( + engine == "hf-batched" and json_schema is not None and structured_output_backend == "xgrammar" + ): + raise ValueError("structured_output_backend requires a supported schema-decoding engine") + if engine != "vllm" and structured_output_disable_any_whitespace: + raise ValueError("structured_output_disable_any_whitespace requires engine='vllm'") if suppress_tokens and engine != "vllm": raise ValueError("suppress_tokens require engine='vllm'") if engine != "vllm" and max_model_len is not None: @@ -215,7 +219,7 @@ def run_batch_generate( "trust_remote_code": trust_remote_code, "json_schema_sha256": schema_hash, "structured_output_backend": ( - structured_output_backend if engine == "vllm" else None + structured_output_backend if engine == "vllm" or json_schema is not None else None ), "structured_output_disable_any_whitespace": ( structured_output_disable_any_whitespace if engine == "vllm" else None @@ -307,6 +311,8 @@ def run_batch_generate( gpu_memory_utilization=gpu_memory_utilization, suppress_tokens=suppress_tokens, ) + elif engine == "hf-batched" and json_schema is not None: + engine_kwargs.update(json_schema=json_schema, structured_output_backend=structured_output_backend) gen_engine = get_generate_engine(engine, **engine_kwargs) provenance = { "version": 1, diff --git a/tuner/cli/parser.py b/tuner/cli/parser.py index e27f9b98a..ff7880722 100644 --- a/tuner/cli/parser.py +++ b/tuner/cli/parser.py @@ -376,6 +376,8 @@ def create_parser() -> argparse.ArgumentParser: python tuner.py cloud-run --job-config Trainers/recipes/job.yaml --yes python tuner.py local-run --job-config Trainers/recipes/job.yaml --yes python tuner.py mechinterp run --config MechInterp/configs/my_pipeline.yaml --provider local --yes + python tuner.py mechinterp weights-inspect --weights-config my_project/inspect.yaml --json + python tuner.py mechinterp weights-patch --weights-config my_project/patch.yaml --validate --json python tuner.py cloud-jobs list python tuner.py bucket analyze --path runs/hf_jobs/sft// python tuner.py bucket read --path runs/hf_jobs/sft//logs/training_latest.jsonl --jsonl-latest --pretty @@ -883,6 +885,26 @@ def create_parser() -> argparse.ArgumentParser: action="append", help="Skip a named stage from a mechinterp pipeline. May be repeated.", ) + parser.add_argument( + "--weights-config", + dest="weights_config", + help=( + "Path to a mechinterp-weights-inspect/v1 request (mechinterp weights-inspect) " + "or a mechinterp-weight-patch/v1 spec (mechinterp weights-patch). Experimental." + ), + ) + parser.add_argument( + "--validate", + dest="weights_validate", + action="store_true", + help="mechinterp weights-patch: verify binding, payload and budget against the local checkpoint; write nothing.", + ) + parser.add_argument( + "--export", + dest="weights_export", + action="store_true", + help="mechinterp weights-patch: validate, then create-only export the modified checkpoint to the spec's export.output_dir.", + ) # Experiment loop flags parser.add_argument( @@ -1044,13 +1066,13 @@ def create_parser() -> argparse.ArgumentParser: "may be repeated. Each value must encode to exactly one token." ), ) - parser.add_argument("--json-schema", dest="json_schema", help="Path to a JSON Schema enforced by vLLM structured outputs (batch-generate).") + parser.add_argument("--json-schema", dest="json_schema", help="Path to a JSON Schema enforced by vLLM or HF + XGrammar (batch-generate).") parser.add_argument( "--structured-output-backend", choices=["auto", "xgrammar"], default="auto", dest="structured_output_backend", - help="Pinned vLLM structured-output backend (default: auto).", + help="Structured-output backend; HF schema decoding uses XGrammar (default: auto).", ) parser.add_argument( "--structured-output-disable-any-whitespace", diff --git a/tuner/handlers/mechinterp_handler.py b/tuner/handlers/mechinterp_handler.py index 6ec0d7b3e..c5fe24025 100644 --- a/tuner/handlers/mechinterp_handler.py +++ b/tuner/handlers/mechinterp_handler.py @@ -17,9 +17,12 @@ steer run the six-block steer cell (smoke-gated) dose-calibrate resumable dose ladder over one or more frozen readouts score-gates evaluate a gates.yaml against a per-row output JSONL + weights-inspect inspect a LOCAL safetensors checkpoint (experimental) + weights-patch validate (--validate) or export (--export) a weight patch (experimental) list-configs show bundled example recipes """ +import json import logging import os import subprocess @@ -70,10 +73,14 @@ def handle(self) -> int: return self._handle_dose_calibrate() if sub == "score-gates": return self._handle_score_gates() + if sub == "weights-inspect": + return self._handle_weights_inspect() + if sub == "weights-patch": + return self._handle_weights_patch() msg = ( "mechinterp requires a sub-command: run, extract, probe-fit, steer, " - "dose-calibrate, score-gates, list-configs" + "dose-calibrate, score-gates, weights-inspect, weights-patch, list-configs" ) if self.json_mode: self.output_error(msg, code="SUBCOMMAND_REQUIRED") @@ -277,6 +284,7 @@ def _handle_extract(self) -> int: revision=self._arg("model_revision"), adapter=self._arg("adapter"), gpu_ack=bool(self._arg("i_know_this_runs_on_gpu", False)), + project_context=self.context, ) def _handle_probe_fit(self) -> int: @@ -345,7 +353,55 @@ def _handle_dose_calibrate(self) -> int: render_fn_spec=render_fn, gpu_ack=bool(self._arg("i_know_this_runs_on_gpu", False)), project_context=self.context, + revision=self._arg("model_revision"), + ) + + def _weights_refusal(self, exc) -> int: + self.output_error( + exc.message, code=f"WEIGHTS_{exc.code.upper()}", details={"refusal": exc.code} ) + return 1 + + def _handle_weights_inspect(self) -> int: + from MechInterp.weights.errors import WeightPatchError + from MechInterp.weights.workflow import inspect_from_config + + config_path = self._require("weights_config", "--weights-config") + if not config_path: + return 1 + try: + report = inspect_from_config(self._input_path(config_path), context=self.context) + except WeightPatchError as exc: + return self._weights_refusal(exc) + self.output(report, json.dumps(report, indent=2)) + return 0 + + def _handle_weights_patch(self) -> int: + from MechInterp.weights.errors import WeightPatchError + from MechInterp.weights.workflow import export_patch_config, validate_patch_config + + config_path = self._require("weights_config", "--weights-config") + if not config_path: + return 1 + validate = bool(self._arg("weights_validate", False)) + export = bool(self._arg("weights_export", False)) + if validate == export: + self.output_error( + "weights-patch requires exactly one of --validate or --export", + code="ARG_REQUIRED", + ) + return 1 + try: + path = self._input_path(config_path) + result = ( + validate_patch_config(path, context=self.context) + if validate + else export_patch_config(path, context=self.context) + ) + except WeightPatchError as exc: + return self._weights_refusal(exc) + self.output(result, json.dumps(result, indent=2)) + return 0 def _handle_score_gates(self) -> int: from MechInterp.cli import run_score_gates