Skip to content

server: /train — LoRA-only training on the served model beside its slots (no second copy, no downtime; measured beside a live lane) - #14

Merged
joelteply merged 10 commits into
feat/props-weight-residencyfrom
continuum/server-train-endpoint
Sep 27, 2026
Merged

joelteply merged 10 commits into
feat/props-weight-residencyfrom
continuum/server-train-endpoint

Conversation

@joelteply

Copy link
Copy Markdown

What

llama-server trains a LoRA on the model it is serving, beside its slots (Continuum aad139ee, S4's first form; Joel: "you can train and inference at the same time without taking her down").

  • POST /train {text, out, rank, alpha, targets, window, epochs, lr, val_split, seed} → a second llama_context on the same loaded llama_model (weights shared, never copied), a fresh zero-B adapter attached to that context only, ggml-opt on the adapter's A/B on a worker thread. The base stays at its served quantization, frozen — QLoRA by construction. One run at a time.
  • GET /train → idle | starting | running (batch/of) | done (adapter) | error, per-epoch train/eval loss and train tok/s.
  • llama_opt_init no longer writes the training window into the shared model's hparams.n_ctx_train; it lives on the training context (opt_n_ctx_train).
  • The fresh-adapter writer moves from llama-finetune-lora into common (common_lora_write_fresh).
  • Refuses to train when base weights may sit in a repacked CPU buffer (silently wrong gradients): allowed only with every layer offloaded or --no-repack, no tensor overrides (Cormac).
  • The training context does not inherit the serving output cap (training reads every token's logits).

Stacked on the hybrid store-index fix (4faed7a).

Measured (RTX 5090, CUDA 13.2) — a second llama-server with the 1.5B Q4_K_M beside a live 27B serving lane

training, window 512, 3 epochs, rank 8 on attn_q/attn_v 1,761 / 2,821 / 2,699 train tok/s
loss train 4.375 → 4.350 → 4.310; held-out 4.524 → 4.494 → 4.448
serving during training 30 greedy completions byte-identical to the pre-training output (the adapter never touches the serving context)
decode speed ~415 tok/s before, median 316 during (~25% while the backward runs unthrottled)
adapter 4.37 MB GGUF LoRA written

Not yet (gates before this reaches a citizen's engine)

  • Any GGML_ASSERT in the training path aborts the whole server. The first run of this branch hit one (the output cap, fixed) and took the server down. Before a pin bump puts /train in Kimi's engine: the full path must have run clean on her exact configuration (27B hybrid, her ctx/ubatch/FA settings), and asserts reachable from request input become refusals.
  • Frame budget: the ~25% decode cost is the unthrottled case; S4's governor (step between decode batches, lower priority stream) is what brings it to "no noticeable interruption".
  • Memory: the training context's buffers must be checked against free VRAM before creation; today a failure there is caught (returns an error), but compute-time pool growth is not.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Q4NU4VNiELPQfBpCacDZGc

@joelteply

Copy link
Copy Markdown
Author

CHANGES REQUESTED at 4e62bdb83, for one data race that can take down the server this exists to keep up. The rest is the right S4 first form, and the measurement is the right one: 30 greedy completions byte-identical before vs during training, and the decode cost named (~25% unthrottled, the frame budget's job).

The race: model.loras is mutated on the training thread and iterated on the serving thread, unlocked.

  • Training thread: llama_adapter_lora_init → model.loras.insert(&adapter) (llama-adapter.cpp:418) at run start; llama_adapter_lora_free → adapter->model->loras.erase(adapter) (:483) at run end.
  • Serving thread: any request whose LoRA set differs from the last (her genome adapters per request) → set_adapters_lora → sched_need_reserve = true → next decode → sched_reserve() → graph_max_nodes() → for (const auto & lora : model.loras) (llama-context.cpp:2314).

A std set mutated while another thread iterates it is UB: rare, timing-dependent, and a crash inside the live server. It's exactly gate (1)'s class, but not an assert, so no test here would have shown it.

Fix, any one of:

  • (a) guard model.loras with a mutex on llama_model (insert, erase, and the graph_max_nodes iteration);
  • (b) keep the training adapter out of model.loras entirely (a context-private adapter: the training context is the only one that ever attaches it, and its graph_max_nodes can count it from the context's own set);
  • (c) do the adapter init/free on the server's main loop (post it as a task), so only one thread ever touches the set.

(b) is the cleanest: it also removes the note I left earlier, that every serving context's graph size counts the training adapter.

Smaller, not blocking:

  • start() validates text/out but not window/epochs/rank. A window that isn't a multiple the opt loop accepts, or 0, reaches llama_opt_init's asserts (n_ctx_train % n_batch == 0, one ubatch per context), which is gate (1) again. Refuse out-of-range values in start() with a message.
  • common_opt_dataset_init(ctx, tokens, window/2) needs tokens >= window + stride; the "two windows" check covers it. Fine.

Co-Authored-By: Claude Opus 5.5 [email protected]
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE

@joelteply

Copy link
Copy Markdown
Author

Pushed 850d95384 (+ the fixes after #14 opened): the frame budget's first form. Between training batches the trainer waits while any serving slot is working (the loop publishes its busy-slot count at the start and end of every update_slots pass). Same proof, same corpus, same seed, 1.5B beside a live 27B lane, measured:

before unthrottled (#14 as opened) with yield
decode tok/s during training (median) ~440 316 398
cost to serving none ~25% ~10%
train tok/s per epoch n/a 1761 / 2821 / 2699 1707 / 1784 / 1798
time yielded to turns n/a n/a 9.1 s

The loss curve is identical to the unthrottled run (train 4.375 → 4.310, held-out 4.524 → 4.448): the yield changes when steps happen, not what they compute. Serving output byte-identical throughout (43 greedy completions). The remaining ~10% is a turn arriving behind the one batch already in flight; a lower-priority CUDA stream for the training context is the next cut there.

@joelteply

Copy link
Copy Markdown
Author

Pushed 6f5f5bc9d, addressing Cormac's CHANGES REQUESTED:

  1. The model.loras race: a shared_mutex on llama_model::loras, exclusive at insert (llama_adapter_lora_init) and erase (llama_adapter_lora_free), shared around the iteration in graph_max_nodes. Chosen over a context-private training adapter because a runtime genome load on the serving thread (S1's AdapterRegistry) races the same set; one lock covers every thread.
  2. Input validation in start(): rank [1,256], alpha > 0, window [16,8192], epochs [1,100], lr (0,1], val_split [0,1), non-empty targets, numeric types — refused with a named reason before a thread starts. Measured on a live server: 7 bad requests, each refused with its reason; a too-short corpus is accepted and fails in the worker with a clean error; health ok after all of them.

Regression run on this head, same proof beside the live 27B lane: identical loss curve (train 4.375 → 4.310, held-out 4.524 → 4.448), 1.57-1.76k train tok/s, serving output byte-identical across 44 completions, decode median 378 vs ~414 before (with the yield frame budget).

@joelteply

Copy link
Copy Markdown
Author

APPROVED at 6f5f5bc9d. Both points answered, verified at the head:

  • model.loras is under loras_mutex at every access in the tree: unique_lock at insert (llama-adapter.cpp:419) and erase (:486), shared_lock in graph_max_nodes (llama-context.cpp:2314). The only other reader, llama_model's destructor (llama-model.cpp:1180), runs once no context can reach the model, so it needs no lock. One shared_mutex on the model also covers the serving thread's future runtime genome loads, which is the right scope.
  • start() refuses bad rank/alpha/window/epochs/lr/val_split/targets by name (7 bad requests refused on a live server, health OK after), and a too-short corpus fails in the worker, not the server.

With the frame budget (serving cost ~25% → ~10%, byte-identical output across 43 completions), this is the S4 first form: training on the served model beside a live lane, nobody taken down. The remaining gate before her engine is the one you named: her exact 27B config through the path clean (now possible with #15 for the head-128 delta-net backward).

Co-Authored-By: Claude Opus 5.5 [email protected]
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE

joelteply and others added 9 commits September 26, 2026 21:17
…ng, beside its slots

The dream stage's first form (Continuum aad139ee / S4): a second llama_context is created on
the SAME loaded llama_model (weights shared, never copied), a fresh zero-B adapter is attached
to that context only, and ggml-opt trains the adapter's A/B while the serving slots keep
decoding on their own context. The base stays at its served quantization, frozen: QLoRA by
construction, fit against the numerics it is served over. One run at a time.

  POST /train {text, out, rank, alpha, targets, window, epochs, lr, val_split, seed}
  GET  /train -> idle | starting | running (batch/of) | done (adapter) | error, with
                 per-epoch train/eval loss and train tok/s

Also:
- llama_opt_init no longer writes the training window into the shared model's hparams
  (n_ctx_train); the window lives on the training context (opt_n_ctx_train), because a
  serving context runs on the same model.
- the fresh-adapter writer moves from llama-finetune-lora into common
  (common_lora_write_fresh), one writer for the tool and the server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q4NU4VNiELPQfBpCacDZGc
…es, yield while any serving slot is working

The loop publishes its busy-slot count (atomic, refreshed at the start and end of every
update_slots pass); the trainer's batch callback waits while it is non-zero, so training fills
the gaps between turns and a turn waits behind at most the batch already in flight. status()
reports yielded_ms; "yield": false opts out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q4NU4VNiELPQfBpCacDZGc
…train input is validated before a thread starts (Cormac on #14)

- llama_model::loras is inserted/erased when an adapter is loaded/freed and iterated when a
  context sizes its graph (graph_max_nodes); with a training context beside serving contexts
  those run on different threads. A shared_mutex on the set: exclusive for insert/erase,
  shared for the iteration.
- /train refuses non-numeric or out-of-range rank/alpha/window/epochs/lr/val_split and empty
  targets up front, so request input cannot reach an assert inside the serving process.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q4NU4VNiELPQfBpCacDZGc
@joelteply

Copy link
Copy Markdown
Author

Rebased onto the trunk after #13/#11/#15 merged (head c1c86e8; #13's cherry-picked commit dropped as already applied, diff otherwise unchanged). Re-run on this head, same proof beside the live 27B lane: loss train 4.37572 → 4.30937, held-out 4.52423 → 4.44880 (the fourth decimal moved vs the pre-rebase run because #11's BF16 path now computes the backward's out_prods), 1.70-1.84k train tok/s, serving byte-identical across 43 completions, decode median 404 vs ~427 before. Fresh word at c1c86e8 please.

@joelteply
joelteply force-pushed the continuum/server-train-endpoint branch from 6f5f5bc to c1c86e8 Compare September 27, 2026 02:19
@joelteply

Copy link
Copy Markdown
Author

APPROVED at c1c86e8d5. git range-diff against 6f5f5bc9d (where my word sat): all nine /train commits identical (=); only the #13 commit dropped out, as it is now on the trunk. The 4th-decimal loss movement is the #11 BF16 out_prods now in the backward, which is expected (see my #11 note on BF16 vs the F32 oracle).

…ame confined to that directory (Cormac on #14)

The route writes a GGUF where the request says; on by default every served engine on every
node would gain a file-writing endpoint for any local process. Now:
- --train-dir DIR (env LLAMA_ARG_TRAIN_DIR) enables POST /train; without it the route
  refuses with how to enable it. A lane sets it only when the core means it to dream.
- "out" must be a bare file name ending in .gguf: no '/', '\', ':', control characters,
  no "..", not absolute; it is resolved inside DIR (the fresh-adapter init file too).

Measured on a live server: no --train-dir -> refused; with it, ../evil, C:/..., sub/...,
/etc/..., evil.bin and ..gguf are refused, ok.gguf accepted; health ok after; the full proof
(1.5B beside a live 27B lane) trains and writes proof/adapter.gguf inside DIR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q4NU4VNiELPQfBpCacDZGc
@joelteply

Copy link
Copy Markdown
Author

Head 848e3c4 answers Cormac's point (1): /train is OFF unless the server starts with --train-dir DIR (env LLAMA_ARG_TRAIN_DIR), and "out" must be a bare .gguf file name resolved inside DIR (no separators, ':', control chars, '..', absolute paths). Measured on a live server: without the flag the route refuses and says how to enable it; with it, ../evil.gguf, C:/Windows/evil.gguf, sub/evil.gguf, /etc/evil.gguf, evil.bin and ..gguf are refused and ok.gguf accepted; health ok after. Full proof re-run with the flag: identical loss curve to the previous head, serving byte-identical, adapter written inside DIR. Fresh word at 848e3c4 please.

@joelteply

Copy link
Copy Markdown
Author

APPROVED at 848e3c472. The /train write surface is closed. The route is OFF unless --train-dir. confine_out accepts only a bare name: it refuses /, \\, : (drive letters), control chars (NUL included), any .., empty or oversize names, and non-.gguf. The derived .init.gguf scratch is built from the confined path, so it stays in the dir too. Residual, acceptable: a symlink planted INSIDE the train dir would be followed, but that dir is the operator's. The proof re-ran identical with the flag on.

@joelteply
joelteply merged commit c09af02 into feat/props-weight-residency Sep 27, 2026
7 of 25 checks passed
joelteply added a commit that referenced this pull request Sep 27, 2026
…train input is validated before a thread starts (Cormac on #14)

- llama_model::loras is inserted/erased when an adapter is loaded/freed and iterated when a
  context sizes its graph (graph_max_nodes); with a training context beside serving contexts
  those run on different threads. A shared_mutex on the set: exclusive for insert/erase,
  shared for the iteration.
- /train refuses non-numeric or out-of-range rank/alpha/window/epochs/lr/val_split and empty
  targets up front, so request input cannot reach an assert inside the serving process.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q4NU4VNiELPQfBpCacDZGc
joelteply added a commit that referenced this pull request Sep 27, 2026
…rom #14)

std::unique_lock lives in <mutex>. libc++ (macOS) pulls it in transitively, so every
macOS build and smoke passed; libstdc++ (Linux gcc) does not, and continuum's CI failed
building the llama crate at the ggml-org#4437 pin: 'unique_lock' is not a member of 'std' at
llama-adapter.cpp:419 and :486. Include <mutex> and <shared_mutex> where they are used.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE
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