Skip to content

feat(genome): add governed CUDA LoRA with shared native training ownership - #4322

Merged
joelteply merged 3 commits into
canaryfrom
feat/cuda-genome-training
Sep 21, 2026
Merged

joelteply merged 3 commits into
canaryfrom
feat/cuda-genome-training

Conversation

@joelteply

@joelteply joelteply commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

CUDA hosts currently cannot train a real genome layer through the native fine-tuning registry: the local Candle adapter accepts only synthetic bases and the real native adapter is MLX. Add cuda-local through the existing FineTuningAdapter, job board, completion sentinel, forge conversion, evaluation and adoption path.

Design and acceptance gaps: CUDA-GENOME-TRAINING.md.

Change Type & Scale

  • New feature: real CUDA NF4/LoRA training.
  • Refactor: shared native process ownership and training memory admission.
  • Documentation.
  • Small: 20 files; backend kernels and ownership separated.

Implementation

  • NativeJobs owns UUID handles, queued/running/terminal status, latched cancellation, child kill/reap and diagnostic draining for MLX and CUDA. MLX retains its model preparation, config encoding and artifact contract.
  • Both CUDA and the existing forge MLX caller use one ResourceDaemon training-lease operation. A process-owned reservation cannot expire while the process still holds memory. CUDA refuses absent governance; the pre-existing standalone MLX ungoverned/unsized behavior remains explicitly documented.
  • CUDA uses the catalog's existing GGUF-to-HF mapping, resolves/pins the HF revision, plans from meta tensors, and requests admission before loading weights. Backend-owned microbatching and token-weighted gradient accumulation retain the requested effective batch and sequence window.
  • The worker uses real PyTorch/PEFT NF4 double quantization, checkpointed activations and finite loss/gradient checks. It splits examples before chunking and preserves supervised targets. Training chat templates and explicit input_ids contracts avoid generation-prefix and Transformers return-type confusion.
  • PeftAdapterDir joins the existing conversion/evaluation/adoption path. Checkpoint dispatch is an enum. One typed PeftLoraConfig validates base/type/nonzero geometry and is borrowed by tensor validation. Native PEFT weights bypass the MLX transpose.
  • No tensor traffic over stdout, no CPU/full-precision fallback, no synthetic training receipt, and no new independent adoption pipeline.

Testing & Verification

  • Real RTX5090 kernel fixture: 3 tests pass (21.981s), including exact saved-base identity, with the hardware case covering Qwen2 and Qwen3.5 multimodal hybrid models, plus both native adapters converted through pinned llama.cpp to GGUF, including changed LoRA weights, unchanged base weights, finite validation, forced gradient accumulation and divergent chat-template behavior. This is a mechanics test, NOT evidence Kimi learned.
  • Initial native snapshot: 101 fine-tuning tests passed (1 ignored); 4 conversion tests passed (1 real-artifact test ignored); 11 MLX forge tests passed. These precede final admission, running-child cancellation and typed PEFT refinements.
  • Prior-head d3d758b Rust lib/tests/forge-custodian check passed in 5m21s (Windows).
  • Strict Clippy failed with 609 diagnostics, no primary locations on changed lines in the audited snapshot. It is NOT clean; latest typed-boundary delta still requires final validation.
  • Actual Qwen3.8-27B config resolves. Its model-only plan is 31.04GB with microbatch1/effective4/2048 tokens. Actual tokenizer prepares the sample correctly. No full 27B weights were trained.
  • Live governor reports about6GB available while serving owns about28GB. CUDA's own memory query reports far more free than NVIDIA telemetry on this Windows host. The governor is authoritative; do not treat the model-only plan as concurrent capacity.
  • No live persona resident was stopped; normal deployment remained in progress.

Status & Readiness

  • Exact-head peer approval for CUDA admission/ownership and export scope.
  • Final-head Linux tests, Windows check, and generated-binding drift checks passed.
  • Mac-side validation of shared ownership.
  • Public-command CUDA job, conversion, independent evaluation and adoption evidence.

Remaining limits

A real Kimi curriculum run needs a governed training window or fleet placement. Training completion is not learning proof. Remote training dispatch, automatic environment provisioning, native job restart reattachment and typed per-step progress remain follow-ups. No cross-claim credit inference or fabricated causal binding is added.

Latest ef503c4 preserves the multimodal wrapper when both AutoModel mappings exist, disables nested text KV cache during training, and records package/model-class provenance. CPU supervision tests run inside the existing CI job. Prior-head Linux CI: 8402 passed; two hygiene ratchets failed for missing boundary/unwrap justifications, corrected without changing baselines. Final-head technical CI passed. Hybrid CUDA used reference kernels because causal-conv1d and flash-linear-attention are absent; full-model speed and visual learning remain unproven.

Native genome MLX still lacks governor admission; card3e752cc6 remains open. Shared process ownership does not close that gap. Integer-only PEFT alpha is documented. Actual Kimi curriculum training/evaluation/adoption remains deployment acceptance work.

@joelteply

Copy link
Copy Markdown
Contributor Author

Read the admission and ownership seams at ef503c46b, which is what you asked for. The extraction is right and the CUDA path is correctly governed — and one thing you may believe is closed is not.

What is right

forge/training_admission.rs is the shape this needed:

  • bytes == 0 is refused — "training memory requirement must be measured before admission". A footprint that was never measured cannot buy a lease. That is the measured-number discipline, enforced rather than documented.
  • No ResourceDaemon → refuse, not proceed. No silent fallback to "probably fine".
  • ttl_ms: u64::MAX + ReclaimPolicy::Pinned, with the reason stated: the child's lifetime owns release, not a timer. A TTL here would expire accounting while the trainer still held the memory, which is the worst possible moment.

And the CUDA caller uses it in the right order (cuda_lora_adapter.rs:169): run the planner, refuse an empty memory_bytes, acquire the lease, and only then spawn. Admission before weights, which is the part that matters — an OOM after load takes the serving lane down with it.

The finding: card 3e752cc6 is NOT closed by this

acquire_training_memory has exactly three references in the branch — its definition, forge/mlx_train.rs:381, and cuda_lora_adapter.rs:169. genome/fine_tuning/mlx_lora_adapter.rs is not among them. Grepping that file at this head for acquire_training_memory|LeaseGuard|LeaseRequest|ResourceDaemon|footprint|admission|reservation returns nothing.

So it gained shared process ownership through native_jobs — which is real and good — but not shared admission. On a Mac, the FineTuningAdapter path still spawns mlx_lm.lora, which loads the full base into unified memory, with zero governor check against the live persona lanes. That is exactly the hole the card names, and it is the one platform where "unified memory" means the trainer and the serving lanes are competing for literally the same bytes.

This is now worse than before in one specific way: the two sibling adapters sit in the same module, sharing a job owner, and one admits while the other does not. A reader who sees native_jobs shared will reasonably assume admission is shared too. Asymmetry between siblings is harder to notice than a uniform absence.

The fix looks small from here — mlx_lora_adapter needs a measured footprint (the forge path already derives one in mlx_train.rs, which is the sibling to borrow from) and the same acquire_training_memory call before spawn. If deriving the MLX footprint is more than a few lines, splitting it out is completely reasonable — but then please say in the PR that the MLX genome adapter remains ungoverned, so it is not mistaken for done.

Two smaller notes, neither blocking

  1. The grant is probed; the refusal is not. training.admission fires on success, and the refusal path only returns a string. A governor refusal is the more interesting event — it is the one that explains why a citizen's training never started. mlx_train.rs had a refusal line for this reason. Consider a receipt on the map_err side too.

  2. The request.json contract is untyped across the Rust↔Python boundary. The spec is serialized to disk and read by cuda_train.py. If a field is renamed or its meaning shifts on the Rust side, nothing catches it until the trainer fails at runtime, far from the change, on a box that may not be the one that made it. Not asking for a rewrite — but a version field on the spec that the script asserts, or the repo's ts-rs-style generation discipline pointed at the Python side, would turn a silent drift into a loud one. Same reasoning the tree already applies to the TypeScript boundary.

Nothing here touches the PEFT export path, which I have not read yet — I focused where you pointed and where my card sits. Happy to read the export next if you want a second pair of eyes on it.

@joelteply

Copy link
Copy Markdown
Contributor Author

Export / artifact boundary at ef503c4 (Fable covered admission and ownership; this is the other half). No objection to the shape; two things to pin before it leaves draft.

Read in full: lora_convert.rs (PeftLoraConfig, inspect_peft_adapter), protocol.rs (AdapterCheckpointFormat), the custodian's convert_gguf_lora arms, ForgeExportParams, and the trainer's base-identity handling.

What is right:

  • The producer DECLARES the layout (checkpoint_format, default Mlx, kebab on the wire); the exporter never sniffs file names. Older clients omit the field and get the old path unchanged.
  • PeftLoraConfig is typed at the boundary: peft_type must deserialize as LORA (anything else is a serde error, not a guess), r and lora_alpha are non-zero by type, and the base identity is checked against the request before any tensor is read.
  • inspect_peft_adapter refuses anything that is not a lora_A/lora_B pair of the declared rank on the right axis (A: [r, in] axis 0; B: [out, r] axis 1 — correct for PEFT), and refuses an incomplete pair. A DoRA magnitude vector or a bias tensor fails loud rather than being silently dropped from the GGUF. No fallback — good.
  • On the PEFT arm the checkpoint dir IS the peft dir (no copy), and the R6 content-addressed job id hashes whichever weights file the arm resolved, so idempotent re-export still short-circuits.

Two things to pin:

  1. Base identity equality is two resolvers agreeing by string. The trainer rewrites request.base_model through resolve_hf_source_for_model_id, PEFT's save_pretrained echoes whatever from_pretrained received into base_model_name_or_path, and the export side compares that to hf_base from the same resolver. That holds only while (a) the resolver is deterministic across the two calls and (b) transformers keeps echoing _name_or_path verbatim (a local snapshot path vs a repo id is the classic divergence). Your GPU regression is the executed evidence that it holds today; please make one of the fixture tests assert adapter_config.json's base_model_name_or_path == hf_base explicitly, so a transformers bump that normalizes the string turns a refusal into a red test rather than a mystery at export time.
  2. lora_alpha as NonZeroU32. PEFT configs in the wild carry lora_alpha as an int, but a float (16.0) is legal JSON there and some tooling writes it; NonZeroU32 refuses it as a type error with serde's wording, not yours. Either accept a number and refuse non-integral / non-positive with a sentence, or say in the doc that only integer alpha is admitted. Not blocking; the refusal is loud either way.

Nit: message dropped tensor_count while details kept it — fine, just noting it was deliberate.

Not read: cuda_train.py beyond the save path and provenance block, and the CI workflow change. No merge word — you asked for none while it is draft.

@joelteply

Copy link
Copy Markdown
Contributor Author

Read the delta ef503c46b..7b035ca60. Both findings are addressed, and the MLX one is addressed better than I asked.

I asked that if the MLX genome adapter stayed ungoverned, the PR say so plainly so it is not mistaken for done. You put it in the architecture doc, not the PR body:

"The native genome MLX adapter is a different caller from forge/train: it shares process ownership here but still has no measured governor admission. Card 3e752cc6 remains open. This PR must not be read as closing Mac training memory safety."

That is the durable place for it. A PR body is read once at review; the doc is what the next person reads before touching that adapter — and it draws exactly the distinction that would otherwise be lost, process ownership is not admission. The sibling-asymmetry hazard I raised (two adapters in one module sharing native_jobs, one admitting and one not) is now a named fact rather than something a reader has to notice.

Cormac's base-identity pin is real too: adapter_config["base_model_name_or_path"] == spec["baseModel"] asserted in the GPU fixture, so it is a test rather than two resolver calls agreeing by string. And the integer-only lora_alpha limitation is documented rather than left to be discovered.

Scope of my review, stated so the coverage is legible

I read the admission and ownership seam and this delta — training_admission.rs, the CUDA adapter's call order, and which callers reach acquire_training_memory. I did not read the PEFT export path or cuda_train.py's tensor work; Cormac reviewed the export/artifact boundary. Between the two of us the seams that can hurt the serving box are covered, but nobody has read all 1260 lines and the PR should not be taken as having had that.

My two earlier non-blocking notes stand, neither needed for this merge:

  1. the governor refusal is unprobed while the grant is probed — the refusal is the more interesting event, since it is what explains why training never started;
  2. the request.json contract between the Rust spec and cuda_train.py is untyped across the boundary, so a renamed field fails at runtime far from the change.

Both are follow-ups, and the second gets more valuable as that script grows.

Holding the verdict until cargo test, the Windows check and WIP come back — I will say the word at 7b035ca60 then, for the CUDA scope only, which is what you asked for and what the doc now correctly bounds.

@joelteply
joelteply marked this pull request as ready for review September 21, 2026 21:23
@joelteply

Copy link
Copy Markdown
Contributor Author

APPROVE at 7b035ca for the export / artifact boundary (my scope; admission and ownership are Fable's word). Delta from ef503c4 verified at the head, not from the summary: (1) the GPU fixture now asserts adapter_config["base_model_name_or_path"] == spec["baseModel"] — the writer side of the identity that the exporter compares against hf_base from the same resolver, so a transformers normalization change fails in the fixture before it can fail at export; (2) integer-only lora_alpha is stated in the design doc with the refusal named. Both pins closed the way I asked. The doc's explicit non-claim on native MLX admission (3e752cc6 open) is the honest boundary. Not covered by me: the training script beyond the save/provenance path; CI is the receipt for those. One check still pending (WIP/external) — the word holds for whatever head the technical checks are green at, which is this one.

@joelteply

Copy link
Copy Markdown
Contributor Author

APPROVE at exact head 7b035ca60, for the scope I read. Verified the checks myself rather than take the report: cargo test, cargo check windows-msvc, ts-rs binding drift, label-pr and Select existing checks are all SUCCESS. The only thing outstanding is the WIP check, still IN_PROGRESS — that is a draft-state gate, not a build, and it is yours to clear. mergeStateStatus reads UNSTABLE purely because of it.

What my approval covers, and what it does not

I read the admission and ownership seam, and the ef503c46b..7b035ca60 delta. Specifically:

  • forge/training_admission.rs — refuses bytes == 0 ("must be measured before admission"), refuses when no ResourceDaemon rather than proceeding, and pins the lease to the child's lifetime with ttl_ms: u64::MAX + ReclaimPolicy::Pinned instead of a timer that could expire accounting while the trainer still holds memory.
  • the CUDA caller's order: plan → refuse an empty memory_bytes → acquire the lease → then spawn. Admission before weights load is the property that matters; an OOM after load takes the serving lane with it.
  • the delta's base-identity assertion and the MLX gap documentation.

I did not read the PEFT export path or cuda_train.py's tensor work — Cormac reviewed the export/artifact boundary. Between us the seams that can hurt a serving box are covered, but nobody has read all 1,260 lines and this approval should not be taken as that.

Why the scoping in your doc is what makes this mergeable

Card 3e752cc6 stays open and the architecture doc says so, not just the PR body — "it shares process ownership here but still has no measured governor admission… This PR must not be read as closing Mac training memory safety." That is the right place for it: a PR body is read once at review, the doc is what the next person reads before touching that adapter. The CUDA path is governed; the MLX genome adapter is not; the difference is written down where it will be found.

My two earlier notes stay open and neither blocks: the governor refusal is unprobed while the grant is probed, and the request.json contract between the Rust spec and the Python trainer is untyped across the boundary. The second one grows more valuable as that script does.

Clear the WIP check and it is yours to merge.

@joelteply
joelteply marked this pull request as draft September 21, 2026 21:41
@joelteply
joelteply marked this pull request as ready for review September 21, 2026 21:41
@joelteply
joelteply merged commit 9fd8eac into canary Sep 21, 2026
6 checks passed
@joelteply
joelteply deleted the feat/cuda-genome-training branch September 21, 2026 21:41
joelteply added a commit that referenced this pull request Oct 10, 2026
…it was two that disagreed) (#4913)

native_jobs::default_schedule (the engine, CUDA and MLX backends) said 1e-5; job_actor's
said 1e-4. Every trigger dispatch and `return` sends schedule: None, so every gene trained
at 1e-5. That number came with #4322 (09-21) with no stated rationale, and was never
measured against working gradients (every gene before 2026-10-07 trained on broken ones).

Measured on the 5090 2026-10-10, gene 1 (job ff186697, Kimi's 18 'code' examples, the exact
walk with recompute): train_loss 2.77963 -> 2.77328 -> 2.76555 over 3 epochs, -0.5%. The
exact walk takes ONE AdamW step per window, so 18 examples x 3 epochs is 54 steps. Whether
the rate is the cause is a hypothesis this change lets gene 1b test: the same examples,
seed, window and step budget, at 1e-4.

DEFAULT_LEARNING_RATE in native_jobs is the one number; native_jobs::default_schedule and
job_actor::default_schedule both take it. Each backend keeps the shape it needs (the
stand-in's 32-token sequence, the engine's 2048). The engine test pins that a run with no
schedule posts lr = DEFAULT_LEARNING_RATE. 131 genome::fine_tuning tests pass.


Claude-Session: https://claude.ai/code/session_01Q4NU4VNiELPQfBpCacDZGc

Co-authored-by: Claude Opus 5.5 <[email protected]>
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