Skip to content

feat(genome): LoRA training loop — DataLoader + AdamW + cross-entropy (task #232) - #1576

Merged
joelteply merged 1 commit into
canaryfrom
feat/local-candle-training-loop
Jun 9, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/local-candle-training-loop

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Task #232 — LocalCandleFineTuner math layer 2/3

Builds the trainable pipeline on top of #231's LoRAModule. The substrate now has:

DataLoader        (typed dataset → padded batches)
    ↓
LoRATrainer       (forward + cross-entropy + AdamW backward)
    ↓
TrainingMetrics   (steps/epochs counters, last loss)

Math layer 3/3 (#233) is the job lifecycle actor + safetensors writeout, which wires this into the FineTuningAdapter::create_job / poll contract.

What's in

genome/fine_tuning/training_loop.rs (new, ~470 LOC including tests):

  • Tokenizer trait — substrate-side abstraction; deterministic-output contract. Real HF tokenizer wiring lands in Docs/readme collaborative society focus #233 next to the model loader (they share the safetensors path).
  • TrainingError taxonomy — EmptyDataset / InvalidBatchSize / InvalidSequenceLength / TokenizerFailed / Candle. Mirrors FineTuningError::LocalTrainerFailed so Docs/readme collaborative society focus #233 can propagate each variant intact per [[no-fallbacks-ever]].
  • TokenizedExample + TokenizedBatch — typed tokenization output. Batches carry input_ids + target_ids + attention_mask in fixed [batch_size, sequence_length] shape.
  • DataLoader — pre-tokenizes the full dataset, pads/truncates to sequence_length + 1, builds [batch_size, seq_len] tensors, drops partial last batch. The dead channel.rs trigger we deleted in refactor(channel): delete dead genome/job-create training trigger (task #227, Stage B PR 3/3) #1572 used to fire training on insufficiently-validated input; this constructor catches all empty/zero conditions at the boundary.
  • LoRATrainer — wraps LoRAModule + candle_nn::AdamW + cross_entropy. Only A and B are passed to the optimizer — base weight stays frozen, its gradient is never computed (saves memory + compute).
  • TrainingMetrics — steps/epochs counters + last loss. Cheap to clone; Docs/readme collaborative society focus #233's lifecycle actor reads this periodically to publish TrainingStatus::Running { progress_pct, current_epoch } via a watch channel.

Stand-in vs production (deferred to #233)

This trainer's train_step is a stand-in that exercises the gradient path through LoRAModule's A and B Vars end-to-end. Production wiring (#233) swaps:

  • the U32→F32 cast → embedding-table lookup
  • first-column-per-sample targets → flattened [batch * seq] over [batch * seq, vocab] logits

The optimizer + cross-entropy + backward shape stays identical across both — the swap is local to forward shaping and target shaping, so the trained Vars loop back through inference/lora.rs with no glue.

Tests (8 total, all passing)

Test What it catches
empty_dataset_rejected Typed EmptyDataset at boundary — no opaque tensor errors later
zero_batch_size_rejected Typed InvalidBatchSize(0) — refactor can't silently set batch=1
zero_seq_length_rejected Typed InvalidSequenceLength(0)
batches_have_shape_batch_size_x_seq_len Tensor shape contract — refactor can't axis-swap silently
attention_mask_is_1_for_real_0_for_pad Polarity invariant — flipping it would silently inject pad gradient
partial_last_batch_is_dropped Batch-size invariant for loss aggregation
adamw_step_moves_lora_parameters The load-bearing test. Verifies gradient flows through A. A refactor that mis-collects Vars (e.g. passes base_weight to AdamW) would silently freeze the LoRA — this catches it immediately.
metrics_count_steps_and_epochs Counter advancement contract — wrong counters would surface as stuck status in operator dashboards
running 8 tests
test genome::fine_tuning::training_loop::tests::empty_dataset_rejected ... ok
test genome::fine_tuning::training_loop::tests::zero_batch_size_rejected ... ok
test genome::fine_tuning::training_loop::tests::zero_seq_length_rejected ... ok
test genome::fine_tuning::training_loop::tests::partial_last_batch_is_dropped ... ok
test genome::fine_tuning::training_loop::tests::attention_mask_is_1_for_real_0_for_pad ... ok
test genome::fine_tuning::training_loop::tests::batches_have_shape_batch_size_x_seq_len ... ok
test genome::fine_tuning::training_loop::tests::adamw_step_moves_lora_parameters ... ok
test genome::fine_tuning::training_loop::tests::metrics_count_steps_and_epochs ... ok

test result: ok. 8 passed; 0 failed

Full genome::fine_tuning::* suite: 50/50 passing.

Doctrinal alignment

Follow-ups

Reference docs

  • docs/architecture/CBAR-SUBSTRATE-ARCHITECTURE.md — RTOS-style runtime contract
  • docs/architecture/GENOME-FOUNDRY-SENTINEL.md — artifact-sharing economy that Docs/readme collaborative society focus #233's safetensors output feeds into

… (task #232)

Math layer 2/3 of LocalCandleFineTuner. Sits on top of #231's LoRAModule
and gives the substrate the trainable pipeline that #233's lifecycle
actor wires into the FineTuningAdapter contract.

Adds:
- Tokenizer trait — substrate-side abstraction; real HF wiring lands
  in #233 next to the model loader. Trait isolates the data loader so
  it tests against a deterministic fake.
- TrainingError taxonomy — EmptyDataset / InvalidBatchSize /
  InvalidSequenceLength / TokenizerFailed / Candle. Mirrors the
  FineTuningError::LocalTrainerFailed shape so #233 propagates each
  variant intact (per [[no-fallbacks-ever]]).
- TokenizedExample + TokenizedBatch — typed tokenization output;
  batches carry inputs + targets + attention_mask in fixed
  [batch_size, sequence_length] shape.
- DataLoader — pre-tokenizes the full dataset, pads / truncates to
  sequence_length + 1, builds [batch_size, seq_len] tensors, drops
  partial last batch. The dead channel.rs trigger #1572 deleted used
  to fire with insufficient validation; the loader's constructor is
  the contract that catches "no examples" / "0 batch_size" /
  "0 seq_length" at the boundary instead of as opaque tensor errors.
- LoRATrainer — wraps the LoRAModule + candle_nn::AdamW + cross_entropy.
  Only A and B are passed to the optimizer (base weight stays frozen
  — its gradient is never computed, saving memory + compute).
- TrainingMetrics — steps_completed / epochs_completed / last_train_loss
  / last_epoch_avg_loss. Cheap to clone; #233's lifecycle actor reads
  this periodically to publish TrainingStatus::Running via a watch
  channel.

Stand-in vs production wiring (deferred to #233):
- Inputs cast U32 to F32 instead of going through an embedding table
- Targets use first-column-per-sample for cross-entropy instead of
  flattened [batch * seq] over a [batch * seq, vocab] logits tensor
- The optimizer + cross-entropy + backward shape stays identical; the
  swap is local to forward shaping + target shaping, so the layer
  loops back through inference/lora.rs without glue.

Tests (8 in genome::fine_tuning::training_loop):
- empty_dataset_rejected — typed EmptyDataset at boundary
- zero_batch_size_rejected — typed InvalidBatchSize
- zero_seq_length_rejected — typed InvalidSequenceLength
- batches_have_shape_batch_size_x_seq_len — tensor shape contract
- attention_mask_is_1_for_real_0_for_pad — polarity invariant
- partial_last_batch_is_dropped — batch-size invariant for loss
  aggregation
- adamw_step_moves_lora_parameters — the load-bearing test; verifies
  gradient signal flows through A. A future refactor that mis-collects
  Vars (e.g. passes base_weight to AdamW) would silently freeze the
  LoRA — this catches it immediately.
- metrics_count_steps_and_epochs — counter advancement contract

Doctrinal alignment:
- [[no-fallbacks-ever]] — every loader / trainer entry returns a
  typed error; no silent rejection
- [[matrix-dojo-layer-loading-as-substrate-primitive]] — output Vars
  stay in the same layout as the inference-side LoRAWeights, so
  trained layers loop back through inference/lora.rs unmodified

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 18b2092 into canary Jun 9, 2026
2 checks passed
@joelteply
joelteply deleted the feat/local-candle-training-loop branch June 9, 2026 15:36
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