Skip to content

feat(genome): LocalCandleFineTuner end-to-end — job actor + safetensors output (task #233) - #1577

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

joelteply merged 1 commit into
canaryfrom
feat/local-candle-job-actor

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

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_job spawns a real tokio actor that runs the optimizer loop end-to-end and writes a safetensors artifact at completion.

create_job
    ↓ (validates synchronously)
spawn_job
    ↓ (tokio::task::spawn_blocking)
JobActor                ── publishes ──►  watch::Sender<TrainingStatus>
  ↓ train_epoch × N                         (Queued → Running → terminal)
  ↓ write_lora_safetensors
  ↓ publish Completed { artifact }

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 — 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.

local_candle_adapter.rs — LocalCandleFineTuner no longer the skeleton:

  • 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.

Error taxonomy (per [[no-fallbacks-ever]])

Failure FineTuningError variant
EmptyDataset / InvalidEpochs / MissingOutputPath InvalidRequest (caller's fault, retry won't help)
LoRA / Training / Safetensors / Candle errors LocalTrainerFailed (substrate-side problem)
Foreign provider_id on poll/cancel UnknownHandle

The 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)

File Test What it catches
byte_tokenizer encodes_byte_offset_by_one_pad_is_zero Pad/offset convention pinned — no silent mask-flip
byte_tokenizer vocab_constant_covers_all_emitted_ids Vocab range invariant — no out-of-range ids at runtime
byte_tokenizer encoding_is_deterministic Reproducibility of training data on retry
safetensors_io round_trips_lora_tensors A/B bit-exact round-trip; key names match inference/lora.rs
safetensors_io creates_parent_dir_if_missing Producers don't have to pre-mkdir
job_actor empty_dataset_rejected_synchronously No doomed actor spawn
job_actor zero_epochs_rejected_synchronously Loop body actually runs
job_actor happy_path_writes_artifact_and_publishes_completed End-to-end
job_actor terminal_state_is_sticky Repeated poll after terminal returns same payload
job_actor cancel_before_first_epoch_yields_cancelled File NOT written on cancel — no lying about completion
local_candle_adapter create_job_reaches_completed_and_writes_safetensors Adapter-level end-to-end
local_candle_adapter empty_dataset_maps_to_invalid_request Error category correct
local_candle_adapter poll_rejects_foreign_provider_id_as_unknown_handle Cross-adapter routing safe
local_candle_adapter terminal_entry_stays_tracked Reputation/lineage subsystem can read final metrics
local_candle_adapter sanitize_segment_neutralizes_traversal Caller-controlled name can't escape genome dir
test result: ok. 63 passed; 0 failed

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.
  • [[no-fallbacks-ever]] — every actor entry returns a typed error; cancel-before-write does NOT lie about completion.
  • 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.

Follow-ups

  • Real base-model loading + per-architecture tokenizer (Qwen / Llama / Mistral). At that point supported_base_model_prefixes narrows from wildcard to actual coverage, and request.base_model validation lights up.
  • Phase 4: Rust Workers, Daemon Infrastructure, and System Improvements #228: Substrate-native LoRA training trigger — teacher synthesis pipeline calls into the FineTuningAdapter contract.

Reference docs

  • docs/architecture/CBAR-SUBSTRATE-ARCHITECTURE.md — RTOS-style runtime contract the actor honors
  • docs/architecture/GENOME-FOUNDRY-SENTINEL.md — artifact-sharing economy this safetensors output feeds into
  • docs/architecture/CONCURRENCY-STYLE-GUIDE.md — actor pattern follows the spawn_blocking + watch + AtomicBool shape

…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]>
@joelteply
joelteply merged commit dc09e81 into canary Jun 9, 2026
2 checks passed
@joelteply
joelteply deleted the feat/local-candle-job-actor branch June 9, 2026 15:47
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