Repository navigation
feat(genome): LoRA training loop — DataLoader + AdamW + cross-entropy (task #232) - #1576
Merged
Merged
Conversation
… (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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Task #232 — LocalCandleFineTuner math layer 2/3
Builds the trainable pipeline on top of #231's
LoRAModule. The substrate now has:Math layer 3/3 (#233) is the job lifecycle actor + safetensors writeout, which wires this into the
FineTuningAdapter::create_job/pollcontract.What's in
genome/fine_tuning/training_loop.rs(new, ~470 LOC including tests):Tokenizertrait — 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).TrainingErrortaxonomy —EmptyDataset/InvalidBatchSize/InvalidSequenceLength/TokenizerFailed/Candle. MirrorsFineTuningError::LocalTrainerFailedso 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 tosequence_length + 1, builds[batch_size, seq_len]tensors, drops partial last batch. The deadchannel.rstrigger 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— wrapsLoRAModule+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 publishTrainingStatus::Running { progress_pct, current_epoch }via a watch channel.Stand-in vs production (deferred to #233)
This trainer's
train_stepis a stand-in that exercises the gradient path throughLoRAModule's A and B Vars end-to-end. Production wiring (#233) swaps:[batch * seq]over[batch * seq, vocab]logitsThe 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.rswith no glue.Tests (8 total, all passing)
empty_dataset_rejectedEmptyDatasetat boundary — no opaque tensor errors laterzero_batch_size_rejectedInvalidBatchSize(0)— refactor can't silently set batch=1zero_seq_length_rejectedInvalidSequenceLength(0)batches_have_shape_batch_size_x_seq_lenattention_mask_is_1_for_real_0_for_padpartial_last_batch_is_droppedadamw_step_moves_lora_parametersmetrics_count_steps_and_epochsFull
genome::fine_tuning::*suite: 50/50 passing.Doctrinal alignment
[[no-fallbacks-ever]]— every loader / trainer entry returns a typed error; no silent rejection. The deadchannel.rstrigger refactor(channel): delete dead genome/job-create training trigger (task #227, Stage B PR 3/3) #1572 deleted is the cautionary tale this commit hardens against.[[matrix-dojo-layer-loading-as-substrate-primitive]]— output Vars stay in the same layout as the inference-sideLoRAWeights, so trained layers loop back throughinference/lora.rsunmodified.[[rust-is-the-core-node-is-the-shell]]— training pipeline is substrate-side; no TS round-trip; ready for Docs/readme collaborative society focus #233 to wire under theFineTuningAdaptercontract.Follow-ups
TrainingArtifact).FineTuningAdaptercontract once that surface is complete).Reference docs
docs/architecture/CBAR-SUBSTRATE-ARCHITECTURE.md— RTOS-style runtime contractdocs/architecture/GENOME-FOUNDRY-SENTINEL.md— artifact-sharing economy that Docs/readme collaborative society focus #233's safetensors output feeds into