Skip to content

Add native per-request LoRA adapters to the DeepSeek-V4.1 CUDA engine - #47

Draft
GoatInAHat wants to merge 31 commits into
Elevatormusic:deepseek-v41-tp2from
GoatInAHat:openclaw/ds41-native-adapters
Draft

GoatInAHat wants to merge 31 commits into
Elevatormusic:deepseek-v41-tp2from
GoatInAHat:openclaw/ds41-native-adapters

Conversation

@GoatInAHat

@GoatInAHat GoatInAHat commented Oct 27, 2026 •

Copy link
Copy Markdown

What this changes

Adds per-request LoRA selection to the DeepSeek-V4.1 CUDA engine. --adapter NAME=FOLDER registers an adapter model ID; --adapter-strength sets its strength. A request selects it by model ID or the adapter field. Stock and adapter requests use the existing lane rounds, base weights and KV pool.

The supported writers are attention wo_b and shared-expert w2. Unsupported writers and MTP edits are refused at startup. Adapters are fixed for the engine lifetime. Prompt reuse, kept rows and disk spills are scoped by adapter identity. Each rank checks the same registry and request selection. Single-stream --parallel 1 and dynamic loading are not supported.

Draft: GPU correctness, two-node model exactness, memory headroom and performance remain unqualified. This feature is useful for serving several adapters from one base allocation, but CPU proof does not establish those hardware results. It does not change checkpoint bytes or prove equivalence to a separately merged and requantized checkpoint.

The attention delta is added in float32 before the existing reduction. The packed shared-expert path uses the existing rounded float16 hidden scratch and folds A to that representation. Hardware comparison with the intended activation-domain reference remains required. The stock drafter is unchanged.

Repairs and integration

The contributor commits are preserved. Separate maintainer commits repair:

  • Weight identity: all runtime and checker factor reads use a private temporary copy whose copied bytes match the reported hash. A changed path cannot replace those reads. This needs temporary storage for the adapter files and an extra read/write pass; TMPDIR can use RAM.
  • Restore identity: follower admission checks the requested adapter before restoring rows.
  • Arithmetic validation: reject non-finite folded factors and combined scales that cannot fit finite float32. Validate serialized factors, then omit modules whose stored scale is zero. This avoids overflow followed by multiplication by zero. The offline checker validates and reports default strength 1.0.
  • Offline accounting: validate TP geometry and count table metadata as well as factor bytes.
  • PEFT paths: keep the original model path for rank and alpha patterns after one wrapper removal. Reject duplicate normalized writer targets and A/B halves from different paths before accepting an adapter.
  • Current-base integration: retain native-image templates, safe prompt-piece caching, prefill rotation, cancellation, and opt-in reduce-scatter. Startup compares all nine words: five engine settings, including RS, plus four adapter digest words, before model warm-up.

The final integration also repairs a CPU fixture race. Expected configuration rejection must not abort a shared barrier while a peer leaves the completed all-gather. Unexpected errors still abort and reap peers. The separate baseline repair is merged in #60. Both fixture guards retain all 41 original assertion expressions and their time limits.

See docs/adapters.md for the contract and limits. The target repository has issues disabled; this draft also holds the design discussion required for the arithmetic extension.

Type

  • type: fix: a bug fix
  • type: feature: new code
  • type: docs: docs only
  • type: results: run results
  • type: research: a study
  • type: spec: a plan

Current validation

Head a40d7b30631adfb7c37d5a8a2723d66d129aeef9; base bcbbcbbc6e1f876c8d30ab83cf6441a6f99480dc. Tests use isolated read-only source exports, pinned CPU images, no credentials, no host services and no GPU.

  • Full CPU plan with approved private local HTTP fixtures: 4,022 passed, 758 skipped, 138 existing exclusions, 37 subtests passed.
  • Complete adapter scope with Torch 2.9.1+cpu, Triton 3.8.0 and xgrammar 0.2.8: 346 passed under IP-socket denial; its 14 local HTTP cases failed at denied socket creation and all 14 passed in a separate approved replay. Thus all 360 adapter cases have passing coverage. The raw strict run remains a failure.
  • Format repair: 69 passed, including anchored rank/alpha patterns, duplicate writers, mixed paths and valid manifests. Both reported defects fail on the previous commit before the repair.
  • New startup and reduction integration: 36 passed. Existing reducer and tool cases: 31 passed, with all prior assertions retained.
  • Native image, plain text and prompt cache: 113 passed. Cancellation, rotation, spill and grammar: 52 passed. Additional hostile-input and arithmetic probes: 13 passed. Focused scopes overlap; do not add their counts.
  • Controlled startup cleanup schedules: 18 passed across both fixtures. Delayed peers keep the intended configuration errors; pre-gather and unexpected errors still abort and reap peers.
  • Fatal-error Python lint and default-only full-history secret scan passed. Independent source review found no actionable defect in the reviewed scope.
  • The full run with the extra IP-socket-denial filter remains raw exit 1: 3,128 passed, 797 failed, 97 errors, with the same 758 skips, 138 exclusions and 37 passing subtests. The separate full private-fixture replay above passes. No assertion or exclusion was weakened.

The post-review repeat on the prior b80 head exposed the fixture race described above. That failure is retained in the record. These new exact-head receipts cover the repaired integration. Full-suite runs also record and compare all private Git metadata before and after execution. Historical contributor results remain in the commit and conversation history.

Open qualification gates

Not run: native MLX/Apple hardware checks, compiled GPU kernels and graph replay, real-checkpoint stock/adapted token hashes, TP2/NCCL behavior, mixed concurrent requests, fresh versus resumed prompts, drafted versus draft-off output, memory headroom, drafter acceptance, cold-prefill/TTFT and alternating decode benchmarks. The current two-node service is occupied and the reviewed Python image is absent on the head node. No serving model was stopped or replaced.

CPU collectives and Triton interpreter checks do not supply this proof. Keep this PR draft until the required hardware and performance receipts pass.

GoatInAHat and others added 10 commits October 26, 2026 22:25
…a rank

A folder of PEFT files (and an optional tensorfold_adapter.json that must agree
with them) is checked against the checkpoint's sizes. It may edit attention
wo_b and the shared expert's w2 of a backbone layer, at any rank and scale per
module. Every other module, MTP blocks included, and anything that is not a
plain LoRA pair is refused by name instead of dropped.

The registry is fixed at start and gives each adapter an identity key that
follows the weights' bytes, the module set and every module's scale. Placement
cuts A by columns and keeps B whole, which is what both modules need under
tensor parallelism; the packed shared expert's A is rewritten once to read the
rotated hidden state the expert kernels leave for its down projection.

tools/dsv41/adapter_check.py runs the same checks offline and prints the memory
a rank would hold.
--adapter NAME=FOLDER (repeatable) and --adapter-strength NAME=NUMBER are
checked before any weight is downloaded: the CUDA backend, a family that serves
adapters, --parallel 2 or more, and names that do not take --name or an --alias.
Each adapter is listed in /v1/models as a model id of its own with the base
model as parent. A request picks one by its model id or its "adapter" field; an
unknown or contradictory choice is a 400 before a stream opens, never the base
model's answer. A server started without --adapter, and every other family,
behave exactly as before.

The choice rides on the request (PreparedRequest, Scheduler.submit, Stream) as
an opaque reference and reaches the engine as a generate() argument that is sent
only for an adapter.
…nd ranks

The delta scale * B @ (A @ x) is added to the fp32 partial sum of attention
wo_b and of the shared expert's w2, before the cross-rank reduction the layer
already makes. A concurrent round's input buffer gets a sixth row holding each
row's adapter slot, read at replay by two Triton kernels, so one captured graph
serves any mixture of adapters and padded rows copy their original's slot.
Prompt chunks run one slot for all their rows. The kernels take one program a
row and tile with fp32 sums in a fixed order and one tile shape for every
table, so a row's bits depend on its own input and its adapter's factors only;
a row of slot 0 is not read or written, and a layer no adapter edits launches
nothing. The packed shared expert's w2 reads the rotated, scaled fp16 hidden
state still in the expert scratch (factors folded at load); an expert outside
the pack reads its bf16 hidden state. The drafter always runs the base model.

A kept prompt and a spilled manifest carry the identity key of the adapter that
made their rows, and a prompt continues only a prompt of the same key. The
spill's prefix hashes start with the key (the base model's are unchanged), and
a manifest naming something that is not a hex digest is dropped at start.

Ranks: engine start gathers a digest of the base config and every adapter's
slot, name and key, and refuses to serve if two ranks differ. An admission
names the adapter's slot and key after the grammar, a follower checks that it
holds the same adapter, and every step's agreement check includes the slots of
the live streams, so a rank that disagrees fails the step on every rank before
a collective.

Without --adapter nothing here runs: every new argument defaults to the stock
path, the round input buffer keeps five rows, and the ops between ranks and the
spill's manifests and hashes are what they were.
docs/adapters.md: what an adapter may edit and what is refused, the folder
format and manifest, tensor-parallel placement and the shared-expert form, graphs
and rows, cache identity, memory and the limits. README option row and the API
page's adapter selection.
tools/dsv41/adapter_mix.py rotates a list of model ids (the base model's and the
adapters') over a burst of concurrent streams and checks each stream's token hash
against its own solo run, and each solo run against "draft": false. Standard
library only; its tests run it against a stand-in server.
What start refuses (one stream at a time, the torch path, the exact-matmul test
mode), that it loads, warms and returns the registry, how a name resolves to a
reference, and what generate does with an adapter with and without a
concurrent scheduler.
… traceback

A manifest whose files, files["adapter_model.safetensors"], base or
provenance is not an object, a safetensors header that is not an object (or
whose dtype is not a string, or whose shape or offsets hold Infinity), an
rank_pattern or alpha_pattern of the wrong type, and a lora_alpha or alpha_pattern
value that is not a finite number now raise AdapterError, so the server and
tools/dsv41/adapter_check.py give the reason. A non-object "files" was skipped
without checking the weights' hash; it is refused now.

adapter_config.json with alora_invocation_tokens set (PEFT's activated LoRA,
which edits only after its invocation tokens) is refused instead of being
served as an always-on LoRA. The null PEFT writes for a plain LoRA is accepted.
…er must match across ranks

docs/api.md and docs/adapters.md no longer state that a request without an
adapter runs "bit for bit as without the flag" and that a row's bits never
depend on its neighbours as results. Both follow from the kernels' construction
(a slot-0 row is not read or written; one program per row, fixed sum order).
The CPU tests check them under Triton's interpreter; the compiled kernels,
graph replay, prompt chunks and a larger rank beside an adapter, and a server
with the flag against one without, are the GPU tests' and the running-server
checks' to show.

The start-up check that every rank holds the same adapters now says "files,
names, strengths and order" and is a function the CPU tests call: a swapped
--adapter order was already refused through the slot digest, without saying
why. docs/adapters.md states the rule.
@Elevatormusic

Copy link
Copy Markdown
Owner

I am keeping this feature in draft while I validate the repair. The review found three related scale cases: a finite alpha and strength can produce an invalid float32 scale; a zero stored scale can still produce NaN if factor multiplication overflows; and the offline checker could report success for a scale the server refuses. The repair checks the combined scale before runtime allocation, omits zero-effect modules after factor validation, and makes the checker state and validate its default strength.

The review also covers immutable weight snapshots, adapter identity on follower restore, and finite packed factors. The contributor commits are preserved, with repairs in separate maintainer commits. The final source review is clean; CPU and Triton interpreter regressions are passing. This repair is still local and has not yet been pushed to this PR.

Two-node adapter exactness, concurrent streams, resume behavior, memory headroom, and speed remain unqualified. I will not treat CPU checks as that hardware proof.

@Elevatormusic Elevatormusic added the type: feature new code (feature, tool, add-on) label Nov 6, 2026 — with ChatGPT Codex Connector
@Elevatormusic

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-07T01:36:18.771504Z a40d7b3 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8de8243e3c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Elevatormusic

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: b80f1662f0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link
Copy Markdown
Owner

Fresh Codex review is clean for b80f1662, but the final test repeat found one additional CPU startup-test failure, so the final validation gate has not passed.

A controlled probe confirms that the fixture aborts its fake barrier after the first expected mismatch refusal. The peer can then receive BrokenBarrierError instead of its own expected ValueError. The same cleanup pattern exists in the baseline reducer test. I am preparing a separate baseline fixture fix, then will integrate it here. The repair will retain the existing exception, no-warmup and timeout assertions. The failed run is preserved; it is not waived as a socket-denial case.

The PR stays draft. Hardware qualification remains open.

@Elevatormusic

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: a40d7b3063

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Elevatormusic

Copy link
Copy Markdown
Owner

CPU correction and review work is complete for a40d7b30631adfb7c37d5a8a2723d66d129aeef9, based on bcbbcbbc6e1f876c8d30ab83cf6441a6f99480dc.

The final repeat after the fresh Codex signal passed the private HTTP full suite: 4,022 passed, 758 skipped, 138 existing exclusions, 37 subtests passed. All focused checks and the 18 controlled cleanup schedules passed. Source, inputs, and all private Git metadata remained unchanged; all 15 test containers were removed.

The separate strict run remains raw exit 1: 3,128 passed, 797 failed, and 97 errors. All 894 failed/error cases match the earlier IP-socket denials. They are retained as failures, with the separate private HTTP run supplying the passing test coverage. No assertion, timeout, or exclusion was weakened.

Codex completed the current-head review with no findings and a fresh thumbs-up. All three current CI checks pass. The contributor commits are preserved, and the two reported format defects and the CPU barrier cleanup race are repaired.

The per-request adapter feature has a useful purpose: several adapters can share one base allocation. Keep this PR draft until real-checkpoint output checks, TP2/GPU and graph checks, mixed requests, restore checks, memory headroom, and performance tests pass. The latest read-only capacity check still found both serving containers resident and the reviewed Python carrier absent on the head. No serving process was changed. CPU results do not establish those hardware results.

AI disclosure

AI: Codex Desktop, with GPT-6.1 Sol subagents.
Checked: Exact source and input hashes, the isolated final CPU plan, controlled failure schedules, complete native-review records, CI, and read-only node capacity. No model deployment or hardware qualification is claimed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feature new code (feature, tool, add-on)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants