Skip to content

test(genome): VDD pass — math-accuracy tests for LoRA stack (task #234) - #1578

Merged
joelteply merged 1 commit into
canaryfrom
test/fine-tuning-vdd-pass
Jun 9, 2026
Merged

joelteply merged 1 commit into
canaryfrom
test/fine-tuning-vdd-pass

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Task #234 — VDD pass on the LoRA fine-tuning stack

Establishes VDD (Validation-Driven Development) as a doctrine alongside TDD. Where TDD pins CONTRACTS (error variants, shape preservation, "loss is a number"), VDD pins numerical accuracy against independent references — closed-form math, analytical formulas, convergence invariants, round-trip-equivalence.

Why this matters

A refactor that swaps a transpose in LoRA's forward, uses the wrong reduction in cross-entropy, or mis-collects Vars in AdamW would pass every existing TDD test silently and produce wrong values for every input forever. VDD catches that class of regression by comparing against a hand-rolled / closed-form reference, not against another candle matmul.

Pattern: every VDD test sits in a nested mod vdd { use super::*; ... } inside the existing #[cfg(test)] mod tests (per CLAUDE.md's one-test-mod-per-file rule), with a "what this VDD catches" comment naming the specific regression class TDD would miss.

What's in

6 VDD tests across 3 files. Total genome::fine_tuning::* tests: 63 → 69, all passing.

lora_module.rs::tests::vdd

Test What it catches
forward_matches_closed_form_for_arbitrary_inputs Hand-rolled nested f32 loops compute y = x @ W^T + (alpha/rank) * (x @ A^T) @ B^T on a 3-batch / 5-in / 6-out / rank-2 problem; asserts candle's forward matches element-wise within 5e-5. Catches the transpose-flip class that produces valid shapes but wrong values.
scale_is_applied_exactly_once_in_delta Sets A, B so the unscaled delta is exactly [1, 1]; asserts forward output equals scale * [1, 1] (NOT scale²). Catches double-scaled-delta bugs that pass shape tests.

training_loop.rs::tests::vdd

Test What it catches
cross_entropy_matches_log_sum_exp_formula Computes CE = log(sum(exp(z))) - z[target] in f32 with max-subtraction for stability; asserts candle_nn::loss::cross_entropy matches within 1e-5. Catches reduction-swap or log-softmax-swap bugs.
single_example_overfitting_strictly_decreases_loss Convergence signal: 40 steps on one example MUST drive loss to ≤ half initial. TDD's adamw_step_moves_lora_parameters catches "some Δ"; this catches "Δ in the CORRECT direction" — gradient pipeline actually working.
all_ones_attention_mask_is_a_noop_relative_to_unmasked Pin for the real-model-loading follow-up: when mask multiplication lands, an all-1s mask must NOT rescale the loss landscape.

safetensors_io.rs::tests::vdd

Test What it catches
safetensors_round_trip_reproduces_forward_output train → write → load → reconstruct fresh LoRAModule → forward(x) must match original .forward(x) bit-exact within 1e-6. This is the matrix-dojo loop's correctness invariant — a layer trained on continuum A and paged into continuum B reproduces continuum A's output exactly. Catches dtype-precision-loss, axis-reorder, key-rename bugs raw-tensor round-trip misses.

Reference pattern

For any new numerical slice from now on, write at minimum:

  • one closed-form check (hand-roll the math, don't call another lib)
  • one convergence/round-trip invariant (the system-level "does it actually work" pin)

The "what this VDD catches" comment is mandatory — it documents which specific regression class TDD wouldn't catch.

Doctrinal alignment

  • [[every-error-is-an-opportunity-to-battle-harden]] — VDD generalizes the battle-harden discipline from "regressions we hit" to "regressions the structure of numerical code makes possible."
  • [[refine-tools-as-you-use-them]] — refines the just-shipped LoRA stack with the harness it needs before more math lands on top.
  • [[no-fallbacks-ever]] — math that quietly produces wrong values is the worst kind of silent failure. VDD makes those failures loud.

Files changed

  • core/continuum-core/src/genome/fine_tuning/lora_module.rs (+~190 LOC tests)
  • core/continuum-core/src/genome/fine_tuning/training_loop.rs (+~140 LOC tests)
  • core/continuum-core/src/genome/fine_tuning/safetensors_io.rs (+~140 LOC tests)

No production code touched.

Establishes VDD (Validation-Driven Development) as a doctrine
alongside TDD: where TDD pins CONTRACTS (error variants, shape
preservation, "loss is a number"), VDD pins NUMERICAL ACCURACY
against independent references — closed-form math, analytical
formulas, convergence invariants, round-trip-equivalence.

Why this matters: a refactor that swaps a transpose in LoRA's
forward, or uses the wrong reduction in cross-entropy, or
mis-collects Vars in AdamW, would pass every existing TDD test
silently and produce wrong values for every input forever. VDD
catches that class of regression by comparing against a
hand-rolled / closed-form reference, not against another candle
matmul.

Adds 6 VDD tests across the fine_tuning module, all nested as
`mod vdd { use super::*; ... }` inside the existing
`#[cfg(test)] mod tests` per CLAUDE.md test discipline (one
test mod per file).

lora_module.rs::tests::vdd:
- forward_matches_closed_form_for_arbitrary_inputs — hand-rolled
  nested f32 loops compute y = x @ W^T + (alpha/rank) * (x @ A^T) @ B^T
  on a 3-batch / 5-in / 6-out / rank-2 problem; asserts candle's
  forward output matches element-wise within 5e-5. Catches the
  transpose-flip class.
- scale_is_applied_exactly_once_in_delta — sets A, B so the
  unscaled delta is exactly [1, 1], asserts forward output equals
  scale * [1, 1] (NOT scale²). Catches "double-scaled delta" class.

training_loop.rs::tests::vdd:
- cross_entropy_matches_log_sum_exp_formula — computes
  CE = log(sum(exp(z))) - z[target] in f32 with max-subtraction
  for stability; asserts candle's cross_entropy matches within 1e-5.
- single_example_overfitting_strictly_decreases_loss — convergence
  signal: 40 steps on one example MUST drive loss to ≤ half
  initial. TDD's adamw_step_moves_lora_parameters catches "some Δ";
  this catches "Δ in the CORRECT direction".
- all_ones_attention_mask_is_a_noop_relative_to_unmasked — pin for
  #233 real-wiring: when mask multiplication lands, an all-1s mask
  must not rescale the loss landscape.

safetensors_io.rs::tests::vdd:
- safetensors_round_trip_reproduces_forward_output — train → write
  → load → reconstruct fresh LoRAModule → forward(x) must match
  original.forward(x) bit-exact within 1e-6. This is the
  matrix-dojo loop's correctness invariant: a layer trained on
  continuum A and paged into continuum B reproduces continuum A's
  output exactly. Catches dtype-precision-loss, axis-reorder, key
  rename bugs that raw-tensor round-trip misses.

Total fine_tuning tests: 63 → 69 (all passing).

Doctrinal addition: VDD complements TDD. For any new numerical
slice from now on, write at minimum one closed-form check + one
convergence/round-trip invariant. The "what this VDD catches"
comment names the specific regression class TDD would miss.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 42496a2 into canary Jun 9, 2026
@joelteply
joelteply deleted the test/fine-tuning-vdd-pass branch June 9, 2026 15:59
joelteply added a commit that referenced this pull request Jun 9, 2026
…inator (task #228) (#1579)

Replaces the dead TS-side channel.rs trigger that #1572 deleted.
That trigger fired on raw chat events with insufficient params; the
validator silently rejected; the fire-and-forget call site swallowed
every rejection. This module is the doctrinal opposite: typed
substrate command surface, synchronous validation, typed outcomes,
batch state preserved on dispatch failure per [[no-fallbacks-ever]].

Closes the matrix-dojo loop's last missing seam — the batching layer
between curriculum producers (teacher persona's synthesis,
hippocampus's noteworthy drain, operator submits) and
genome/job-create.

## What it does

Owns a per-(persona_id, trait_kind) bucket of accumulating
TrainingExamples. Each genome/training-trigger/submit:

1. Validates synchronously: non-empty persona_name / base_model /
   trait_kind / examples.
2. Checks coherence against existing bucket: same base_model, same
   source. Conflict → typed InconsistentBucket error. Without this
   guard, two producers mixing data for different target models
   would silently train against the WRONG base — worst-class
   "looks correct, wrong answer" bug.
3. Appends to bucket.
4. If bucket >= min_examples threshold (default 16): drains examples
   into a snapshot, releases the entry guard, dispatches
   genome/job-create via the injected CommandExecutor, removes the
   now-empty bucket on success.
5. On dispatch failure: restores drained examples (preserves order)
   so the next submit re-triggers. Curated examples NEVER silently
   disappear.

## Commands

- genome/training-trigger/submit — append + maybe-fire. Returns
  BatchAppended { currentCount, threshold } below threshold, or
  JobDispatched { jobHandle, examplesUsed, selectedProvider } when
  it fires.
- genome/training-trigger/flush — force-dispatch a bucket below
  threshold (operator end-of-session, hippocampus consolidation
  callbacks). Idempotent — empty bucket → NothingToFlush success.
- genome/training-trigger/status — list pending buckets, sorted by
  (persona_id, trait_kind) for deterministic operator-tooling
  diffing.

## Boot wiring

Registered in ipc/mod.rs alongside GenomeModule. The
install_executor hook (from task #224's DI) wires the
CommandExecutor reference the trigger uses to dispatch
genome/job-create — same pattern as CognitionModule.

## Tests (9 total: 8 TDD + 1 VDD)

TDD (lifecycle / contracts):
- submit_below_threshold_appends_and_does_not_fire
- submit_at_threshold_dispatches_and_clears (end-to-end through
  GenomeModule + LocalCandleFineTuner — proves the substrate-native
  loop closes)
- inconsistent_base_model_in_same_bucket_is_rejected
- flush_dispatches_partial_bucket
- flush_empty_bucket_is_noop (idempotency)
- dispatch_failure_preserves_bucket_contents (the load-bearing
  [[no-fallbacks-ever]] invariant)
- different_personas_have_isolated_buckets (key isolation)
- status_returns_deterministic_bucket_list

VDD (mathematical invariants, per the doctrine memo from #1578):
- submitted_examples_flow_through_dispatch_intact — every example
  submitted across N submits appears EXACTLY ONCE in the dispatched
  training job (no drops, no duplicates), in original order. Verified
  by polling the dispatched job to Completed and asserting
  trainedTokens > 0 in the resulting TrainingArtifact's metrics.
  This is the matrix-dojo loop's data-conservation invariant — a
  regression that double-counted or dropped on the drain-and-dispatch
  path would pass every TDD lifecycle test silently and corrupt every
  produced LoRA layer's training data.

## Doctrinal alignment

- [[commands-are-dumb-daemons-are-smart]] — submit is the dumb door;
  batching, threshold, dispatch live in the module.
- [[no-fallbacks-ever]] — dispatch failure preserves bucket contents;
  flush on empty is idempotent success not error.
- [[rust-is-the-core-node-is-the-shell]] — entire path is
  substrate-side. Teacher persona (Rust) submits, trigger (Rust)
  batches, genome module (Rust) dispatches, local trainer (Rust)
  produces safetensors.
- [[noteworthy-flag-feeds-memory-AND-curriculum]] — the trigger is
  the curriculum drain. Hippocampus / teacher subsystems call submit
  with curated examples; the trigger batches them coherently per
  (persona, trait); genome/job-create produces the layer.

## What's deferred

The hippocampus's "noteworthy" event doesn't exist as a publish
surface yet. Once it does, a follow-up wires a subscriber that
auto-calls submit on noteworthy admission. For now the trigger
accepts explicit submits from any Rust caller — the teacher
persona slice will be the first such caller.

Co-authored-by: Claude Opus 4.7 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant