Repository navigation
feat(genome): LocalCandleFineTuner end-to-end — job actor + safetensors output (task #233) - #1577
Merged
Merged
Conversation
…rs output (task #233) Math layer 3/3 of LocalCandleFineTuner. With this slice the substrate-native LoRA trainer is no longer a skeleton: create_job spawns a real tokio actor that runs the optimizer loop, publishes status via a watch channel, honors cancel, and writes the trained A/B tensors to a safetensors file at terminal Completed. Adds: - byte_tokenizer.rs (ByteTokenizer): substrate-side deterministic byte-level tokenizer. Vocab=257 (pad=0, bytes 1..256). Real tokenizer (not a test fake) so the trainer can run against arbitrary text without model-specific assets. Production wiring for HF tokenizers lands next slice; ByteTokenizer stays as the default any-text path. - safetensors_io.rs (write_lora_safetensors): writes LoRAModule's A + B Vars to a safetensors file with keys 'lora_a' / 'lora_b'. These match what inference/lora.rs reads at merge time — pinned in const so a rename becomes a compile-time mismatch, not a silent zero-init-B merge at inference. Auto-creates parent dir. - job_actor.rs (JobController + spawn_job): per-job actor that runs the LoRATrainer in tokio::task::spawn_blocking (training is CPU-bound; main runtime stays responsive). Cancel is an Arc<AtomicBool> checked at every epoch boundary. Status flows through tokio::sync::watch — terminal states (Completed / Failed / Cancelled) are sticky. Wires LocalCandleFineTuner end-to-end: - create_job validates synchronously, spawns the actor, stores the JobController in an Arc<DashMap<Uuid, JobController>>, returns a JobHandle. - poll reads the actor's current TrainingStatus. - cancel flips the actor's cancel flag. - Default output path is ~/.continuum/genome/<persona>/<trait>/ <uuid>.safetensors per [[use-continuum-dir-not-tmp]]. Path segments are sanitized — caller-controlled persona / trait names can't escape the genome dir via '..'. What's honest about this slice: - The training math runs against a synthetic Tensor::rand base weight, NOT a loaded model. The gradient path through A and B is exercised end-to-end (forward + cross-entropy + backward + AdamW + safetensors write) but request.base_model isn't yet validated against an on-disk model. - Capabilities advertise supported_base_model_prefixes: vec![] — wildcard, caller responsibility. The next slice wires real base-model loading + per-architecture tokenizer (Qwen / Llama / Mistral), at which point the prefix list narrows. Per [[no-fallbacks-ever]]: every actor entry returns a typed error. EmptyDataset / InvalidEpochs / MissingOutputPath map to FineTuningError::InvalidRequest (caller's fault, retry won't help). LoRA / Training / Safetensors / Candle errors map to FineTuningError::LocalTrainerFailed (substrate-side problem). The coordinator can branch on the category to decide whether to retry locally or fall through to a cloud peer. Tests (13 new, 63 total in genome::fine_tuning): - byte_tokenizer: - encodes_byte_offset_by_one_pad_is_zero - vocab_constant_covers_all_emitted_ids - encoding_is_deterministic - safetensors_io: - round_trips_lora_tensors (A/B bit-exact round-trip) - creates_parent_dir_if_missing - job_actor: - empty_dataset_rejected_synchronously (no doomed actor spawn) - zero_epochs_rejected_synchronously - happy_path_writes_artifact_and_publishes_completed - terminal_state_is_sticky - cancel_before_first_epoch_yields_cancelled (file NOT written) - local_candle_adapter (replacing skeleton tests): - create_job_reaches_completed_and_writes_safetensors (end-to-end) - empty_dataset_maps_to_invalid_request - poll_rejects_foreign_provider_id_as_unknown_handle - terminal_entry_stays_tracked - sanitize_segment_neutralizes_traversal Doctrinal alignment: - [[matrix-dojo-layer-loading-as-substrate-primitive]] — the loop closes: dataset → trainer → safetensors → genome paging, all local. No cloud hop. - [[teacher-synthesizes-in-academy-like-dreaming]] — when arc-3 lands, the teacher's synthesized datasets flow into THIS adapter via the FineTuningAdapter contract. No special-casing needed; the trait surface is the seam. - [[rust-is-the-core-node-is-the-shell]] — entire pipeline is substrate-side. Zero TS round-trip. - CONCURRENCY-STYLE-GUIDE — actor uses spawn_blocking for CPU work, watch channel for status snapshots, AtomicBool for cancel. No locks across await; no synchronous probe on main thread. 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 #233 — LocalCandleFineTuner end-to-end
Math layer 3/3 of LocalCandleFineTuner. With this slice the substrate-native LoRA trainer is no longer a skeleton —
create_jobspawns a real tokio actor that runs the optimizer loop end-to-end and writes a safetensors artifact at completion.The full doctrine loop closes: noteworthy engrams → teacher synthesis → THIS adapter → safetensors → genome paging, all inside one continuum. No cloud hop.
What's in
byte_tokenizer.rs— substrate-side deterministic byte-level tokenizer. Vocab=257 (pad=0, bytes 1..256). Real tokenizer (not a test fake) so the trainer can run against arbitrary text without model-specific assets. Production wiring for HF tokenizers lands next slice; ByteTokenizer stays as the default any-text path.safetensors_io.rs— writesLoRAModule's A + B Vars to a safetensors file with keyslora_a/lora_b. These match whatinference/lora.rsreads at merge time — pinned inconstso a rename becomes a compile-time mismatch, not a silent zero-init-B merge at inference. Auto-creates parent dir.job_actor.rs—JobController+spawn_job. Per-job actor that runs theLoRATrainerintokio::task::spawn_blocking(training is CPU-bound; main runtime stays responsive). Cancel is anArc<AtomicBool>checked at every epoch boundary. Status flows throughtokio::sync::watch— terminal states (Completed / Failed / Cancelled) are sticky.local_candle_adapter.rs—LocalCandleFineTunerno longer the skeleton:create_jobvalidates synchronously, spawns the actor, stores theJobControllerin anArc<DashMap<Uuid, JobController>>, returns aJobHandle.pollreads the actor's currentTrainingStatus.cancelflips the actor's cancel flag.~/.continuum/genome/<persona>/<trait>/<uuid>.safetensorsper[[use-continuum-dir-not-tmp]]. Path segments are sanitized — caller-controlled persona / trait names can't escape the genome dir via...What's honest about this slice
Tensor::randbase weight, NOT a loaded model. The gradient path through A and B is exercised end-to-end (forward + cross-entropy + backward + AdamW + safetensors write) butrequest.base_modelisn't yet validated against an on-disk model.supported_base_model_prefixes: vec![]— wildcard, caller responsibility. The next slice wires real base-model loading + per-architecture tokenizer (Qwen / Llama / Mistral), at which point the prefix list narrows.Error taxonomy (per
[[no-fallbacks-ever]])FineTuningErrorvariantEmptyDataset/InvalidEpochs/MissingOutputPathInvalidRequest(caller's fault, retry won't help)LocalTrainerFailed(substrate-side problem)provider_idon poll/cancelUnknownHandleThe coordinator branches on the category to decide whether to retry locally or fall through to a cloud peer.
Tests (13 new, 63 total in
genome::fine_tuning)encodes_byte_offset_by_one_pad_is_zerovocab_constant_covers_all_emitted_idsencoding_is_deterministicround_trips_lora_tensorsinference/lora.rscreates_parent_dir_if_missingempty_dataset_rejected_synchronouslyzero_epochs_rejected_synchronouslyhappy_path_writes_artifact_and_publishes_completedterminal_state_is_stickycancel_before_first_epoch_yields_cancelledcreate_job_reaches_completed_and_writes_safetensorsempty_dataset_maps_to_invalid_requestpoll_rejects_foreign_provider_id_as_unknown_handleterminal_entry_stays_trackedsanitize_segment_neutralizes_traversalDoctrinal alignment
[[matrix-dojo-layer-loading-as-substrate-primitive]]— the loop closes: dataset → trainer → safetensors → genome paging, all local. No cloud hop.[[teacher-synthesizes-in-academy-like-dreaming]]— when arc-3 lands, the teacher's synthesized datasets flow into THIS adapter via theFineTuningAdaptercontract. No special-casing needed; the trait surface is the seam.[[rust-is-the-core-node-is-the-shell]]— entire pipeline is substrate-side. Zero TS round-trip.[[no-fallbacks-ever]]— every actor entry returns a typed error; cancel-before-write does NOT lie about completion.CONCURRENCY-STYLE-GUIDE— actor usesspawn_blockingfor CPU work, watch channel for status snapshots,AtomicBoolfor cancel. No locks across await; no synchronous probe on main thread.Follow-ups
supported_base_model_prefixesnarrows from wildcard to actual coverage, andrequest.base_modelvalidation lights up.FineTuningAdaptercontract.Reference docs
docs/architecture/CBAR-SUBSTRATE-ARCHITECTURE.md— RTOS-style runtime contract the actor honorsdocs/architecture/GENOME-FOUNDRY-SENTINEL.md— artifact-sharing economy this safetensors output feeds intodocs/architecture/CONCURRENCY-STYLE-GUIDE.md— actor pattern follows the spawn_blocking + watch + AtomicBool shape