Repository navigation
feat(genome): LoRA math foundation — trainable A/B module with paper-spec init + autograd (task #231) - #1575
Merged
Merged
Conversation
…spec init + autograd (task #231) First of three follow-ups (#231 + #232 + #233) that fill in the math layer of the LocalCandleFineTuner skeleton landed in PR #1574. This commit builds the trainable LoRA module — the substrate-native sibling to inference/lora.rs (which handles the load + merge path post-training). ## What lands core/continuum-core/src/genome/fine_tuning/lora_module.rs (~470 LOC) LoRAModule: one trainable LoRA layer wrapping a frozen base linear weight. Holds the base as a plain Tensor (no autograd) plus two trainable candle_core::Var matrices A and B. Math (matches inference/lora.rs::merge_lora_weight exactly): y = x · W^T + (alpha/rank) · (x · A^T) · B^T W: base weight [out_features, in_features] (frozen) A: down-project [rank, in_features] (trainable) B: up-project [out_features, rank] (trainable) Init policy per the LoRA paper (Hu et al. 2021): - A ~ Kaiming uniform, bound = √(1/in_features) - B = zeros This makes the initial delta exactly zero so the model behaves identically to the frozen base at step 0. Training perturbs A and B away from this fixed point. Any other init (B random, A zero) would either cause divergence from the base at init or eliminate gradient signal — the test suite pins both invariants. Typed LoRAError taxonomy: - InvalidRank(0) — would produce zero-sized A/B (no learning capacity) - InvalidAlpha(0) — would zero the scale factor (delta never affects forward) - BaseWeightShape{actual} — non-2-D base weight gets a typed error before the first forward, not an opaque Candle matmul error later ## Why a struct + forward, not impl candle_nn::Module candle_nn::Module forward signature does not carry training-vs-eval state. The optimizer + training loop (#232) needs a forward_train distinction (dropout active during training). Cleaner to compose this as a plain struct with an explicit forward now; #232 adds the training/eval variants if dropout becomes needed. ## Verified cargo check -p continuum-core --lib --features metal,accelerate -> clean cargo test -p continuum-core --lib --features metal,accelerate genome::fine_tuning::lora_module -> 8/8 The 8 tests pin every load-bearing invariant: - rank_zero_rejected: typed InvalidRank - alpha_zero_rejected: typed InvalidAlpha - non_2d_base_weight_rejected: typed BaseWeightShape - b_is_zero_initialized_so_initial_delta_is_zero: forward at init == base forward - a_init_is_non_trivial: A has non-zero values so gradient signal flows through B - forward_preserves_leading_dims_and_maps_in_to_out: shape contract on [batch, seq, in_features] -> [batch, seq, out_features] - scale_factor_matches_inference_side_convention: scale == alpha/rank, same as inference/lora.rs - forward_with_perturbed_ab_diverges_from_base_by_scaled_delta: end-to-end math integration with known A,B values producing exact expected output The shape contract test is load-bearing for the matrix-dojo doctrine: A future refactor that swaps in/out axes would silently produce wrong-shaped activations that crash downstream layers in the training loop (#232) and corrupt the safetensors output (#233). Pinning shape at the module boundary catches this at the unit-test level, not at integration-test time. The init-zero-delta test is load-bearing for convergence: the LoRA paper specifically calls out that B=0 init is what makes training stable. A future refactor that initializes B with noise would silently regress training quality. The math integration test forces A and B to known non-zero values and computes the expected output by hand — proves the implementation matches the paper formula exactly. This is the contract with inference/lora.rs::merge_lora_weight; if either side drifts, layers trained here would behave differently at inference time. ## Doctrinal alignment - [[matrix-dojo-layer-loading-as-substrate-primitive]]: the tensors produced here use the SAME layout as inference/lora.rs consumes (A: [rank, in_features], B: [out_features, rank], scale: alpha/rank). After #233 wires safetensors output, layers trained by this module load unchanged into the existing inference + paging path. - [[no-fallbacks-ever]]: rank=0, alpha=0, non-2-D base weight all return typed errors at construction. No opaque tensor errors surfacing at the first forward pass. - [[every-error-is-an-opportunity-to-battle-harden]]: the init-zero-delta test catches a class of regression (silent changes to B init policy) that would otherwise only show up as poor convergence in production training runs. ## What is next (#232 + #233) - #232: data loader (TrainingExample -> tokenized batches) + AdamW optimizer + epoch-major training loop with gradient accumulation and validation pass. Consumes LoRAModule from this PR. - #233: job lifecycle actor (in-process DashMap + watch channel) + safetensors writeout to TrainingArtifact.local_path. Closes the LocalCandleFineTuner so create_job actually starts a training run instead of returning LocalTrainerFailed. 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.
First of three follow-ups to the LocalCandleFineTuner skeleton landed in #1574.
Builds the trainable LoRA module — substrate-native sibling to inference/lora.rs. Math matches the paper + the inference-side merge convention exactly so layers trained here load unchanged into the existing inference pipeline.
Math
y = x · W^T + (alpha/rank) · (x · A^T) · B^TTyped errors
LoRAError::InvalidRank,InvalidAlpha,BaseWeightShape{actual}— fail at construction, not at first forward.Verified
cargo test genome::fine_tuning::lora_module→ 8/8Tests pin every load-bearing invariant: typed-error construction (3), init shape contract (B=0, A non-trivial), forward shape contract, scale factor matches inference convention, and an end-to-end integration test that forces A and B to known values and verifies exact arithmetic output.
What is next
See commit body for full doctrine notes.
🤖 Generated with Claude Code