Repository navigation
feat(engine): --adapter, LoRA adapters merged at load - #52
Conversation
…u; vLLM / SGLang natively; basal-fuse-adapter)
Reviewer's GuideAdds end-to-end LoRA adapter support: adapters can be validated and merged at load across in-process engines, served natively by vLLM/SGLang, or fused into checkpoints for unsupported engines, with adapter identity, calibration matching, provenance, CLI wiring, documentation, and comprehensive framework-level tests. Sequence diagram for adapter-aware model startupsequenceDiagram
participant CLI
participant Server
participant Adapter as adapter.read
participant Backend
participant Model
CLI->>Server: start with --adapter DIR
Server->>Adapter: read(DIR)
Adapter-->>Server: validated Adapter identity and deltas
Server->>Backend: construct backend with adapter
alt in-process engine
Backend->>Model: from_pretrained
Backend->>Model: merge_torch / merge_mlx / merge_numpy
else vLLM or SGLang
Backend->>Backend: peft_dir(adapter)
Backend->>Backend: generate with LoRA request
Backend->>Backend: probe with and without adapter
end
Server->>Server: load_calibration(adapter)
Server-->>CLI: serve adapter-qualified model
Entity relationship diagram for adapter calibration identityerDiagram
ADAPTER {
string name
string identity
int rank
float scale
}
CALIBRATION {
string fitted_on_model
string fitted_on_adapter
string fused_from
}
SERVED_MODEL {
string name
string adapter_identity
}
ADAPTER ||--o{ CALIBRATION : fits
ADAPTER ||--o| SERVED_MODEL : identifies
SERVED_MODEL ||--o{ CALIBRATION : validates
Flow diagram for fusing an adapter into an unsupported checkpointflowchart TD
Start["basal-fuse-adapter --model M --adapter DIR --out FUSED"] --> Read["read and validate adapter"]
Read --> Load["load base model"]
Load --> Merge["merge_torch into decoder linear layers"]
Merge --> Save["save merged checkpoint and copy tokenizer/template metadata"]
Save --> Calibration["copy compatible CALIBRATION files with fused provenance"]
Calibration --> Export["basal-export-gguf"]
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
Thank you, Paweł! This is a really useful feature. It also fits well with basal-finetune, which is coming in 2.5: it writes its LoRA to --out/lora, so with --adapter people could serve their fine-tune without keeping a merged copy. The adapter identity in the calibration file, the refusals and basal-fuse-adapter for GGUF / llama.cpp are exactly what I'd want. When 2.5 is out, could you rebase on it? Two things are new there and need to work with adapters:
It would also be good to have a test that --adapter /lora on a basal-finetune output answers the same as the merged model. The check I'll run for 2.5.1, set in advance:
I'll come back here with the results. Thanks again! |
|
Thanks, @rkinas. 2.5.1 makes sense, and having the check fixed in advance is very helpful. Once 2.5 is out I'll rebase on it and add:
I'll also fix two things I found myself. Exit heads and the evidence head were trained on the base model's hidden states:
Your check covers what I couldn't run here: the vLLM / SGLang paths have only been tested against fake engines (no CUDA on my side), and Gemma 4 hasn't run at all. If the vLLM start-up probe or the PEFT conversion causes problems with the Gemma 4 rsLoRA adapter, post the message and I'll fix it. One question about your third criterion: for the PEFT |
…oder keys only, rsLoRA copy for SGLang; PEFT and Gemma 4 parity tests
…ore .cuda()), so --adapter equals basal-fuse-adapter bit for bit; MLX Gemma 4 parity test
|
A follow-up on my earlier comment, now that the advance work is in (commits
Also in these commits:
|
|
Thank you, Paweł, for the follow-up. As agreed, |
|
Thank you, Paweł: What we changed on top: |
… its cost, and what was measured
… version CONTRIBUTING.md credits the 2.5 pull requests as the release notes' community line lists them (Paweł Kiszczak #52, #62, #64, #66, #68, #71, #73, #75; Marcin Brzeżański #56; Grzegorz Brzezinka #76, #78) and adds Dariusz Koryto (#53, #58, #59, #60 and #55); the README's list names him too. docs/changes/README.md and the changelog.py help use 2.5.1, the next release, as the example.
What
--adapter DIRonbasal-serve,basal-calibrate(in process; with--urlit records the server's adapter) andbasal-bench: a LoRA adapter loaded with the model.basal-fuse-adapter --model M --adapter DIR --out FUSEDwrites the merged checkpoint for the engines that cannot take--adapter(thenbasal-export-ggufas usual). Tokenizer, template andbasal.jsonare copied. The adapter'sCALIBRATION*.jsonfiles are copied withfitted_onnaming the merged model andfused_fromkeeping the origin; files fitted with another adapter, and the base model's own files, are left out.basal/adapter.py: reading, canonical keys, merges for torch / MLX / numpy, PEFT export, and the fuse CLI.Formats
adapter_config.json(fine_tune_typelora or absent) +adapters.safetensors(<path>.lora_a[in, r],.lora_b[r, out])lora_parameters.scaleadapter_config.json(peft_typeLORA) +adapter_model.safetensors(…lora_A.weight[r, in],…lora_B.weight[out, r])lora_alpha / r, or/ sqrt(r)withuse_rsloraThese are refused with
--adapter <name>: <reason>:full, and PEFT types other than LORArank_pattern/alpha_pattern,fan_in_fan_outThe merge is mlx-lm's
LoRALinear.fuseon every framework:(scale * B) @ Ain fp32, cast to the weight's dtype, added in the weight's dtype. Modules are looked up only under the decoder'slayers, so vision towers never match.Per engine
eager,mps,fast,fast-nocompile,fast-exit,fp8/nvfp4via--quant, Qwen3.5 graph,strixfrom_pretrained, before the projection merge, PLE offload and torchao quantisationmlx,mlx-q8load_model, before q8; on the lazy q8 load only the adapter's layers are materialised-MLX-8bitexportsfuse(dequantize=False))tpuvllmenable_lora,max_loras=1,max_lora_rank= next power of two ≥ rank (min 8, ranks > 512 refused),LoRARequeston everygeneratesglangenable_lora,lora_paths={"adapter": <peft dir>},max_loras_per_batch=2,lora_pathon everygenerategguf,ollama,llamacppbasal-fuse-adapter+basal-export-gguf--quant fp8)vLLM and SGLang get the adapter's own PEFT directory. An mlx-lm adapter is converted to a PEFT copy in
$TMPDIR, which is removed at exit. For a multimodal model an mlx-lm adapter is refused, because its module names wouldn't match. At start-up one probe prompt runs with and without the LoRA; identical log-probabilities refuse to start rather than serve the base model under the adapter's name.Serving and calibration
<model>+<adapter>unless--name.GET /v1/modelsadds"adapter": "<name>@<sha256(adapter_config.json + weights)[:12]>", so a rescaled adapter is a different adapter.adapter <name> (<n> layers)and the calibration file applied (oruncalibrated).basal-calibrate: writesfitted_on.adapterand adds--adapter <name>to theenginestring.calibration_mismatchcomparesfitted_on.adapterwith the served adapter; either side may be none. A mismatch warns, or exits with--strict-calibration.--calibration, anyCALIBRATION[.<engine>][.<layout>].jsonin the adapter directory comes first, and is checked as above. Otherwise the model's file belongs to the base model: it is loaded for its temperatures only (no thresholds /multi/ task thresholds), and answers are marked"calibration": "unvalidated", the same handling as a file of another layout or option order.Verification (Apple M4 Max, basal-2.0-mini bf16 and -MLX-8bit)
Adapter: a rank-16 LoRA (scale 2.0) on all 7 projections of layers 16–31, i.e. 112 linear layers, in mlx-lm format. 40 Polish documents were sent through
basal-run --concurrency 1.--mode mlx --adapter: merged weights vspython -m mlx_lm fusebasal-fuse-adapter(torch) vsmlx_lm fuse--mode mlx --adaptervs the mlx-lm-fused checkpoint, served (this branch)--mode mps --adapter(PyTorch) vs mlx-MLX-8bit --adaptervs bf16--adapter--adapter(the adapter is applied)basal-bench --adapter --modes mlx --n 44Under concurrent requests, adapter vs fused differed by max |Δp| 0.0043. That equals the fused server's own run-to-run difference under batching, so it comes from batching, not the adapter.
Calibration checks:
basal-calibrate --adapterwrote the same identity that/v1/modelsreports.--calibrationbut without--adapterwarns, and--strict-calibrationexits 1; a file with a stale identity is refused the same way.--strict-calibrationwithout a warning.Refusals:
--mode gguf|ollama|llamacpp --adapterandbasal-bench --modes gguf --adapterexit before loading, and a DoRA adapter exits with its reason.pytest tests/(without e2e) on this branch: 784 passed, 53 skipped. The newtests/test_adapter.pycovers:/v1/models, GGUF refusals,basal-fuse-adapter's calibration provenanceFollow-up (993d378), while waiting for 2.5
Changes:
--mode fast-exitrefuses--adapter: its exit heads and thresholds were trained on the base model's hidden states. An"evidence": truerequest under an adapter answers 422 for the same reason (the evidence head).[base_model|model|language_model.]*layers.N.…). Before this, a tensor of a vision or audio tower'slayers.Nwas mapped to the decoder's layer N; now it refuses the adapter (Gemma 4 multimodal test).use_rslora(it useslora_alpha / r,sglang/srt/lora/lora.py:64in 0.5.10). An rsLoRA PEFT adapter is therefore passed as a copy stating the same scale aslora_alpha / r, with its tensors linked unchanged.basal-calibrate --adapter.Checks run here:
--adapter: this branch vs 2.4.1 (b20f0f9), basal-2.0-mini, 84 requests,mlx/mps/eager--adaptervs PEFTmerge_and_unload()checkpoint, 1,066 readouts (1,022 human_pl/en documents + 44 bundled),mlxmps(PyTorch merge)mlxvsmpsmerge_and_unloadparity, tiny models (fp32, rsLoRA, all 7 projections)peftLoRARequestorder, rank set {1,8,…,512}, logprob structures, a partial-layer adapter accepted,max_loras_per_batch=2needed for the base probe)--mode vllm --adapteron vLLM 0.32 + vllm-metal 0.32 (Apple M4 Max)A note on the 99.5% bar of the PEFT criterion: on this data set, 20 of the 1,066 readouts are near-ties (margin < 0.005). Two engines serving identical weights already disagree on 7 of them, so 99.34% is the noise floor here, not a merge error. Counting the bar over readouts above a small margin, or against the same-engine floor, would separate the two.
Suite on this branch: 790 passed, 53 skipped (with
peftinstalled).Follow-up 2 (00fa51d):
--adapter=basal-fuse-adapteron every engineThe second criterion of the 2.5.1 check (
--adapter DIRvs thebasal-fuse-adaptercheckpoint, bit-identical probabilities) did not hold by construction on CUDA. The graph engines merged after.cuda(), so the update came from the GPU's fp32 GEMM, whilebasal-fuse-adaptercomputes it on the CPU; the two can round differently.Now the update
(scale · B) @ Ais computed once on the CPU for every merge: torch on any device, MLX, the TPU's numpy weights, andbasal-fuse-adapter. The graph engines andstrixmerge before.cuda(), which also avoids moving the deltas to the GPU. On the CPU it costs about 0.1 s for basal-2.0-mini's 112 modules (269 GFLOP/s); for a rank-16 adapter on every linear of a 31B model, roughly 1 TFLOP, a few seconds.--adaptervs thebasal-fuse-adaptercheckpoint, basal-2.0-mini, 84 requests one at a timemlx,mpsandeagerbasal-fuse-adaptervsmlx_lm fusemerge_and_unloadBit-identical probabilities need the same request order: concurrent requests are batched differently from run to run, which moves bf16 probabilities by ~1e-3 on any model (0.0043 on basal-2.0-mini between two runs of the same server). For the comparison, send the requests one at a time (
basal-run --concurrency 1) or use--deterministic.Suite: 791 passed, 53 skipped.
Not tested here
There is no CUDA here. vLLM ran through vllm-metal (above), SGLang did not run, and both were checked against their source. On CUDA,
basal-serve --mode vllm --adapter …should agree with the mlx run on the top answer for ≥ 38 of 40. The CUDA graph engines,strixandtpuuse the samemerge_torch/merge_numpyas the tested paths, but did not run here.Summary by Sourcery
Add end-to-end LoRA adapter support with consistent loading, serving, calibration, and checkpoint-fusion workflows.
New Features:
--adaptersupport for serving, calibration, and benchmarking with mlx-lm and PEFT LoRA adapters across supported engines.basal-fuse-adapterto produce merged checkpoints for engines that cannot load adapters directly.Bug Fixes:
Enhancements:
Build:
basal-fuse-adaptercommand-line entry point.Documentation:
Tests: