Skip to content

LoRA: runtime toggle and PEFT adapter loader - #316

Merged
davidkoski merged 9 commits into
ml-explore:mainfrom
smdesai:lora-toggle-and-peft
May 27, 2026
Merged

davidkoski merged 9 commits into
ml-explore:mainfrom
smdesai:lora-toggle-and-peft

Conversation

@smdesai

@smdesai smdesai commented May 27, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

This PR adds two related, backward-compatible improvements to the LoRA infrastructure in MLXLMCommon.

Runtime loraEnabled toggle on LoRALayer
A new loraEnabled: Bool property on the LoRALayer protocol lets callers enable or disable the LoRA term at runtime without unloading the adapter. When false, the layer behaves as the underlying base layer (no LoRA term added).

This is needed for inference patterns that interleave LoRA-on and LoRA-off forward passes against the same model — for example, speculative decoding schemes where a LoRA-tuned drafter feeds an un-tuned verifier with a shared KV cache. Today the only way to "disable" a loaded adapter is to unload and reload it, which is too expensive to do per inference step.

Backward compatibility: Strictly additive. The default value is true (LoRA always applied, matching pre-PR behavior). External LoRALayer conformers compile unchanged because the protocol-extension default satisfies the new requirement; their toggle is silently a no-op until they opt in by adding their own stored property.

LoRAContainer.fromPEFT(directory:) — load HuggingFace PEFT adapters
A new static loader on LoRAContainer reads adapter directories in the standard HuggingFace peft format:

  • adapter_config.json (PEFT schema: r, lora_alpha, target_modules, peft_type, …)
  • adapter_model.safetensors (with base_model.model..lora_A.weight / lora_B.weight keys)

These changes are extracted from PR #310 where the model's speculative-decoding mode requires per-phase LoRA toggling and the canonical adapter ships in PEFT format.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

@smdesai smdesai mentioned this pull request May 27, 2026
2 of 4 tasks
Comment on lines +114 to +115
if let bias { return y + bias }
return y

@davidkoski davidkoski May 27, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I wonder if this should call super? Linear is simple enough and unlikely to change, but since it is a subtype it might be better to call that way. It looks like LoRALinear does it that way -- I think that is the pattern to follow

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes you're right, it can and updated accordingly.

Comment on lines +27 to +30
// Conversion:
// - Strip the leading `base_model.model.` prefix.
// - Rename `.lora_A.weight` -> `.lora_a`, `.lora_B.weight` -> `.lora_b`.
// - Transpose both tensors to match MLX's [in, r] / [r, out] convention.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I wonder if this block comment should be on fromPEFT? As it is you can only see it in the code, not in the built docs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch. It's moved to fromPEFT.

// Match "<encoder|model>.layers.<n>." then return the rest. This
// matches the two common backbone layouts the project uses.
let parts = path.split(separator: ".", omittingEmptySubsequences: false)
for i in 0 ..< (parts.count - 2) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

if parts.count is 0 or 1 this will trap -- might want to guard vs that and return nil.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch. Yes a guard needs to be in place. It's added.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good, thank you!

@davidkoski
davidkoski merged commit 5626257 into ml-explore:main May 27, 2026
2 checks passed
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
* Add runtime LoRA enable/disable toggle and PEFT adapter loader
jeethu added a commit to numen-tech/mlx-swift-lm that referenced this pull request Nov 11, 2026
Qwen3.5: bench-only op-group probe for NumenOpCostBench (gemma4-qat ml-explore#316)
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…re#316)

Provider-staged complete-checkpoint imports build their destinations available from zeroed host bytes, so SSD staging no longer waits for the process-wide MLX eval lock held by another request's prefill chunk (Layr-Labs/d-inference#867). The largest host-zero source is charged as staging scratch. Native-bound imports keep device allocation.
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
Brings in ml-explore#316 (provider checkpoint imports staged from host zeros,
without the MLX eval lock).
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…MTP assistant and batched decode (ml-explore#312)

Native Nemotron 3.5 Super VL (ModelOpt NVFP4/FP8/BF16) for the SDK: calibrated loaders and a fenced, pin-verified installation; the RADIO tower and projector image path with bounded preprocessing; a graph-only execution path for the ModelOpt layers (device-side expert routing, calibration scalars as device constants, fused FP8 product, no per-call host syncs); the embedded MTP head with an exact stateful speculative assistant (rectangular verification); exact row-wise batched decode; and chunk-grid recurrent prefix checkpoints. Decode, row-exact batches and MTP verify windows are bitwise equal to the eager reference; default prefill uses tiled accumulation and grouped GEMMs within the documented bound. Everything new is Super-specific; other models' paths are unchanged. Includes main through c17693f (ml-explore#316). Review fixes for this code (load-time eval discipline, safetensors header and file-stamp hardening, grouped GEMM bounds, faulted-scope and media refusals, docs) land with the top of the Super stack (ml-explore#317).
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…nto the cluster SDK

ml-explore#314 carries the bitwise GLM speedups cherry-picked from ml-explore#308, with its own
resolutions and qualification fixes: the shared-expert bitwise gate, the MTP
charge per chunk, sampled-frame video decoding, step-scratch deferral, the
MTP charge test bounds and the strict pool-score tolerance. It also carries
main's Nemotron Super stack (ml-explore#312, ml-explore#315, ml-explore#316, ml-explore#317). Where both sides changed
the same speedup code, this merge takes ml-explore#314's version and re-applies the
cluster-only pieces on top:
- the tensor-parallel shard and reduce hooks (bf77bf2, 2cb5efc);
- whole-stage MTP verification windows (23db6fa);
- fenced HC inputs (624fd05);
- the text-stage and final-stage MTP APIs;
- the cluster image plans and the paged engine (ml-explore#307).
The mlx-swift pin stays at the cluster's 536ea22. The library keeps ml-explore#308's
final DSA state, without the absorbed-query overlap.

Resolutions:
- GLM5NextArtifactLoader: ml-explore#314 plus loadTextStage and loadMTP(stage:).
- GLM5NextHyperConnectionNormFusion: ml-explore#314's one-launch HC kernel plus the
  fenced-input wait and fencedInputs: ["output"] (624fd05).
- GLM5NextMTP: ml-explore#314 plus the stage-owned target reference, primeHistory,
  primeAndPropose and GLM5NextMTPCheckpoint.arrays.
- GLM5NextMoE: ml-explore#314's runsPlainQuantizedMatmul gate (0ceec3a). A TP rank
  builds its MLP from the local configuration, so the gate uses local widths.
- GLM5NextMoEPrefillKernel: ml-explore#314. The two sides differed only in formatting.
- GLM5NextTextCache: ml-explore#314 plus the KDA captured window (23db6fa).
- GLM5NextWeightInventory: ml-explore#314 plus the tensor-parallel shard slice.
- NemotronH: main's Super changes plus the ml-explore#307 layer-stage seam.
  cbv2Forward and cbv2Hidden take inputEmbedding, captureMTP and
  appliesFinalNorm, in that order: main's order first, then the seam's flag.
  appliesFinalNorm: false returns the residual before the fused final norm.
- MLXVLM GLM5NextProcessor: ml-explore#314's sampled-frame video decoding. It calls the
  cluster's shared GLM5NextRGBDecoder.render instead of the removed rgb().
- Package.swift: ml-explore#314 and main, with the cluster mlx-swift pin 536ea22.
- fork.yaml: ml-explore#314 and main, plus the cluster's GLM paragraph and its
  final-stage readout section.
- docs/glm5-next/README.md: the cluster's text, which contains all of
  ml-explore#314's.
- Tests:
  - From the cluster: FusedConstruction (stage entries) and
    HyperConnectionSiteRevision (fenced old source).
  - StageEntry: ml-explore#314's version (validity suite in KernelTests) plus the
    cluster's stage bitwise test.
  - From ml-explore#314: MTP, DSADecodeChain, KDALongConvolution, KDAPrefillKernel,
    KDAStepGraph, MoEDecodeKernel, RouterKernel and PrismMTPBinding.
  - PrefillPipelineTests from ml-explore#314. This drops GLM5NextDSAOverlapTests and
    the bench's overlap A/B, which both set the removed
    overlapsAbsorbedQueries.
  - Unit/Models/GLM5NextKernelConstantsTests is removed, because ml-explore#314 moved
    that suite to Kernel/Layers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…-zeroed pages (ml-explore#328)

* style(paged): format PagedKVSegments.swift

Format-only (`swift format`, repository `.swift-format`). The Lint workflow
formats every Swift file a pull request touches; two expressions added by
ml-explore#316 were not formatted on main, and the next commit edits this file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Retain free paged KV segments across requests; allocate new ones without a stream fence

Row release used to retire every fully free 64 MiB segment, so each
admission re-allocated, zero-filled, evaluated and stream-synchronized new
ones. A pool configured with retainedFreeSegmentBytes now parks those
evaluated backings outside the committed set (grant, floor and ledger
coverage released exactly as before) and reinstalls one of the same size
class, covered by the same admission, at the next growth without
allocating, filling or fencing. Retained backing is dropped on a refused
admission or allocation and after the engine idles.

hostZeroedSegments wraps zero-fill-on-demand host pages as the segment
buffer without a copy, so growth schedules no stream work, takes no MLX
eval lock and waits on no completion fence. It sits beside ml-explore#316's
hostMaterialized import path: cbv2HostZeros copies into a fresh allocator
buffer for an evaluator that skips available arrays, while the pool's
growth evaluator takes the eval lock unconditionally, so a wrapped segment
returns before evaluation. Both options default off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drop retained KV segments on a process-wide release request

Retained free segments are live allocator memory outside every grant, so
neither a cache flush nor another engine's refused charge could reclaim them.
CBv2RetainedKVSegments.requestRelease() advances a process epoch; each pool
drops its retained backing at its engine's next step (pools stay engine-queue
confined).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Gauge retained paged KV segment bytes process-wide

Retained free segments are allocator-active memory outside every grant.
Pools mirror their parked bytes into CBv2RetainedKVSegments.retainedBytes
(parking, reinstall, release and group teardown), so provider load
admission can count that backing as reclaimable and wait for engines to
drop it after a release request before evicting a resident model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants