Skip to content

LoRA adapters at run time (--lora) - #786

Open
mexxBf wants to merge 1 commit into
incoai:mainfrom
mexxBf:lora-adapters
Open

mexxBf wants to merge 1 commit into
incoai:mainfrom
mexxBf:lora-adapters

Conversation

@mexxBf

@mexxBf mexxBf commented Nov 19, 2026 •

Copy link
Copy Markdown

Closes #646. Rebased on main (1.7.3 and the two fixes after it).

What this adds

splash serve --model-dir PATH --lora DIR serves the target with the PEFT LoRA
adapter in DIR (adapter_config.json and adapter_model.safetensors as
peft saves them). The adapter is applied as the model runs, not merged: a
4-bit weight cannot take an update that is smaller than its own rounding, so an
adapted projection computes W x + (alpha / r) B (A x) with W as quantized
and A, B in BF16.

How it works

The adapter is part of the model, not a mode of the engine:

  • Frontend. --lora links the two PEFT files into the assembled model root
    (lora/), as --mmproj links a projector. Their digests are in the
    assembly's record, so a retrained adapter is another prepared model.
  • Model. inspectModelRoot reads the configuration into
    ModelDescriptor::lora and refuses what Splash does not apply (DoRA, a bias,
    modules_to_save, rank_pattern, alpha_pattern, fan_in_fan_out, ...);
    rsLoRA's scale is applied. runtime/model/LoraAdapter.cpp loads the tensors
    and attaches each module's update to its ops::Projection
    (ops::ProjectionLora): attention q/k/v/o and, on a dense FFN, gate/up/down.
    The adapter's digest goes into the weights' fingerprint, so the SSD cache
    never mixes states of different adapters, and its bytes go into the memory
    plan through streamableWeights().
  • Ops. Linear adds the update wherever it runs an updated projection;
    the model's steps and the engine do not know of it (QwenTarget.cpp and
    everything in runtime/engine/ are unchanged). t = A x is one extra
    dispatch per projection or gate/up pair. The staged BF16 decode tile adds
    B t as further steps of its own accumulation, so an update of zeros changes
    no bit of the output; a decode step of more than 64 rows adds it in each of
    the tile's two row groups. Any other tile writes its sums as before and a tile
    kernel adds B t where the value is rounded (lora_tile,
    lora_swiglu_tile). Scratch comes from the arenas, sized from the
    projections' shapes.
  • Neural Engine split. AneFfn takes updates of one rank on every layer's
    gate, up and down (or none), in one step and in two pipelined steps: gate's
    and up's B t run on the ANE as a small FP16 product beside the int8 one,
    down's rotated A as extra int8 rows, and the step's join adds down's
    B t. Each share holds its own parts of down's A, so two shares in one
    program compute what each computes alone, as without an adapter. Without
    this the split had to be switched off with an adapter, which cost about 20%
    of prefill speed on 1.7.0.

docs/models.md ("LoRA adapters") describes the option, docs/internals.md
("LoRA updates") the paths.

Measured

Qwen3.8-27B MLX 4-bit, 20-core M5 Pro, adapter of rank 32 on all seven modules
of every layer (about 300 MB at BF16), measured alternately with and without,
on 1.7.1 (the rebase onto 1.7.3 changed none of these paths):

without with adapter
decode cycle 71.2-71.3 ms 72.1-73.3 ms (+1% to +3%)
prefill, 9.3K tokens 915-945 tok/s 857-893 tok/s (-6%)
prefill, --disable-ane 770-786 tok/s 747-761 tok/s (-3%)

Both calibrate to the same split (share 0.29 in one step, 0.44 in two). The
memory plan grows by 471 MiB: 304 for the adapter, 71 of linear scratch and 96
for the split. On main, beside other GPU work on the Mac, a decode cycle took
1.4% to 2% longer with the adapter in three alternating runs.

How I tested it

On main at d40c250:

  • make check: check-source (architecture check included; no line added
    to runtime/engine), check-native-engine (CPU, Metal, sanitizers, build
    configurations) and check-python pass. check-app does not
    run on my machine: its test bundle does not find Sparkle.framework under
    my Xcode beta, as on the unchanged 1.7.0 tag, where with the framework
    linked in by hand the same nine tests failed on both trees, all on the
    number formats of my German system locale. This change does not touch
    app/.
  • New lora-projection test: every path (staged decode tile in one row group
    and in two, fused block, after-tile with and without residual, gate/up pair,
    a decode step's gate and up plans past 64 rows, int8 prefill tile) against
    the float product on the device, an update of zeros bit-identical to no
    update, and the loader's refusals.
  • ane-ffn test runs the split with a LoRA model as well: accuracy against
    the GPU alone in one step and in two, verify() of both program forms
    (gate and up whole and in blocks), two shares against each share alone, and
    the rule that a row is computed the same whatever the chunk's row count.
  • model-configuration test: adapter configurations accepted and refused,
    an Inkling-2-Mini root's adapter among the refused.
  • Python tests for --lora (linking, launcher, completions).
  • Real model, /v1/judgments option logits. On the decode path (prompts
    under 64 tokens) an adapter of zeros is bit-identical to no adapter. On the
    prefill path it is not, by design: rows stored as they are get rounded again
    with a dither, and the logits then differ by what any one-bit change does
    (RMS 0.14 on prompts of 1.5-1.9K tokens, the same as between the Neural
    Engine and the GPU with one adapter). The effect of a 4x-scaled adapter on
    those prompts matches an earlier standalone implementation of the same
    update with correlation 0.99 and slope 0.97 on the GPU alone, and the split
    in two steps at share 0.44 matches the GPU alone with 0.97 and 0.91 (1.7.0's
    one step at share 0.29: 0.97 and 0.92).
  • Real model, eight lanes (--max-concurrent-requests 8): eight requests at
    once, whose steps run up to 128 rows, answer correctly in 7.1-7.9 s, against
    8.0-8.3 s without the adapter.
  • Real model, an agent session: opencode with a harness adapter solved its
    tasks, 4 of 4, over 38 requests and 52 split commands, none rerun.

Open points

  • --lora needs --model-dir; adapters for catalog packages are not wired.
  • One adapter per served model; switching takes a restart.
  • Rotated and int8 decode tiles take the update through the after-tile route;
    that route is covered by the unit test but I have not run it on a real model.
  • The MoE and Flint families attach attention modules only; I have no adapters
    for them, so they are tested on synthetic weights alone. Inkling-2-Mini
    takes no adapter: its layers are not the Qwen layers the modules name, and a
    root with one is refused by name.
  • On one start with eight lanes, eight requests at once ran one after another
    (26.6 s, twice), with correct answers. Nine runs over seven later starts, two
    of them with step costs measured anew, ran at once as above; I have no log
    of that start and could not reproduce it.
  • The adapter's buffer is not part of the idle release of weights.

I did not open a separate issue first because #646 already asks for this; happy
to rework the approach if you would rather have it shaped differently.

🤖 Generated with Claude Code

@herlesupreeth

Copy link
Copy Markdown

This would be a nice addition in order to use https://huggingface.co/harness-hub/Qwen3.8-27B-super-adapter-GGUF

@mexxBf

mexxBf commented Nov 22, 2026

Copy link
Copy Markdown
Author

This would be a nice addition in order to use https://huggingface.co/harness-hub/Qwen3.8-27B-super-adapter-GGUF

That was my main motivation honestly 👍🏻 But it would also help to fine-tune a model

…, Linear applies its update

The adapter is part of the model instead of a mode of the engine.

- install: `splash serve --model-dir PATH --lora DIR` links
  adapter_config.json and adapter_model.safetensors into the assembled model
  root, as --mmproj links a projector.
- model: inspectModelRoot reads the configuration into ModelDescriptor::lora
  and refuses what is not applied (DoRA, bias, rank_pattern, ...);
  LoraAdapter attaches each module's update to its Projection. The adapter's
  digest is part of the weights' fingerprint, its bytes part of the memory
  plan.
- ops: Linear adds the update wherever it runs an updated projection. The
  staged BF16 decode tile adds B t in its own accumulation; any other tile
  writes its sums and lora_tile / lora_swiglu_tile add B t. The float tile of
  t and B t is that of a full chunk, so a row does not depend on its chunk's
  row count.
  A decode step past one tile's rows adds B t in each of the tile's two row
  groups.
- Neural Engine split: AneFfn takes updates of one rank on every layer's
  gate, up and down, in one step and in two; each share holds its own parts
  of down's A.

QwenTarget.cpp, Model.hpp and runtime/engine are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@mexxBf
mexxBf marked this pull request as ready for review November 25, 2026 11:50
@reneleonhardt

Copy link
Copy Markdown

Thank you for this very important feature! 🚀
What is needed to undraft and review it, are all open points blockers, can anyone help?

@mexxBf

mexxBf commented Nov 25, 2026

Copy link
Copy Markdown
Author

Thanks! It is out of draft now and rebased on current main (1.7.3).

None of the open points is a blocker from my side. They are limits of this first version: --lora needs --model-dir, one adapter per start, and I could only test real adapters on the dense Qwen3.8-27B on one Mac. What it needs now is a review by the maintainers, and their approval for CI to run on a fork PR.

If you want to help: try it with your own adapter and tell me what happens, especially on another Mac (M4 or M6), on a GGUF quant instead of MLX, or with a rank other than 32. Build the branch, then ./splash serve --model-dir PATH --lora ADAPTER_DIR.

@reneleonhardt

Copy link
Copy Markdown

Could you add a small script to iterate all those combinations you need?

unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_M passed with harness-hub/Qwen3.8-27B-opencode-adapted on M4 Max 128 GB.

  • Rank 32: Flash2 accepted 23 of 28 proposals, and decode measured 117 tokens/s on that request.
  • Rank 16 kept the first 16 components, and rank 64 used zero padding to preserve the original update (speed and acceptance were equal to rank 32).

@mexxBf

mexxBf commented Nov 25, 2026

Copy link
Copy Markdown
Author

Thanks for running it, that covers two of the three things I could not test here: another Mac and a GGUF quant.

Here is the script (below, collapsed). It starts each model with and without the Neural Engine and with four adapters made from yours: none, every B zeroed, B times 4, and the same at twice the rank with zero padding. Then it compares option logits from /v1/judgments. The padded adapter should match the given rank exactly, a zeroed adapter should stay close to no adapter, and the adapter's effect should agree between Neural Engine and GPU. That checks the result, not only that it runs.

.venv/bin/python lora-matrix.py --model-dir PATH --lora ADAPTER_DIR

Run it from the repository root of the branch. --model-dir can be given several times (an MLX directory or a GGUF file), and --draft-model is passed on to splash serve. It takes about 20 minutes per model, needs about 2.5 GB of temporary disk for the adapters, and nothing else should use the GPU meanwhile.

This is what it prints here (M5 Pro, 64 GB, MLX oQ4e of an abliterated Qwen3.8-27B, harness-hub/Qwen3.8-27B-opencode-adapted):

  none   ane | ready    11 s | split commands   17 |   81.8 tok/s  5.9 tok/cycle
  zero   ane | ready    25 s | split commands   17 |   79.5 tok/s  6.0 tok/cycle
  scaled ane | ready    26 s | split commands   17 |   80.9 tok/s  6.0 tok/cycle
  padded ane | ready    52 s | split commands   17 |   84.3 tok/s  6.1 tok/cycle
  none   gpu | ready    10 s | split commands    0 |   84.8 tok/s  6.0 tok/cycle
  zero   gpu | ready    10 s | split commands    0 |   80.7 tok/s  5.9 tok/cycle
  scaled gpu | ready    10 s | split commands    0 |   82.9 tok/s  6.0 tok/cycle
  padded gpu | ready    10 s | split commands    0 |   75.2 tok/s  5.9 tok/cycle
  Neural Engine | zero adapter - no adapter   | logit RMS short 0.160 long 0.120
  Neural Engine | twice the rank - given rank | logit RMS short 0.000 long 0.000
  Neural Engine | effect of the adapter x4    | logit RMS short 1.222 long 0.859
  GPU only      | zero adapter - no adapter   | logit RMS short 0.160 long 0.139
  GPU only      | twice the rank - given rank | logit RMS short 0.000 long 0.000
  GPU only      | effect of the adapter x4    | logit RMS short 1.222 long 0.917
  effect, Neural Engine against GPU only, short: correlation 1.000, slope 1.00
  effect, Neural Engine against GPU only, long : correlation 0.963, slope 0.90

The tok/s column is one request per start, so read it as "it decodes", not as a benchmark. If you run it, those report lines are what I would like to see, with the Mac and the model.

One note on your rank test: keeping the first 16 components changes the update, so it shows that rank 16 runs, not that it computes the same thing. The zero padding to rank 64 is the exact one, and the script does the same.

lora-matrix.py
#!/usr/bin/env python3
"""lora-matrix.py --model-dir PATH [--model-dir PATH ...] --lora ADAPTER_DIR [options]

Runs one PEFT LoRA adapter through the combinations of `splash serve --lora`: every model given (an MLX directory, a
GGUF file), with the Neural Engine and without it, and four adapters made from the one given:

  none     no adapter
  zero     the adapter with every B zeroed: the model's own output, through the LoRA kernels
  scaled   the adapter with every B times --scale (4: an update large enough to read against the quantization noise)
  padded   `scaled` at twice the rank, the added rows of A and columns of B zero: the same update

Each start answers /v1/judgments for 16 short prompts and 16 long ones (long enough for the Neural Engine split) and
one chat request. The report compares the option logits, centered per prompt: padded against scaled should be 0,
zero against none small beside the adapter's effect (the LoRA kernels round differently), and that effect
(scaled - zero) should agree between the Neural Engine and the GPU.
Run it from the repository root, with its Python: .venv/bin/python lora-matrix.py ...
Needs numpy. Nothing else may use the GPU meanwhile. About 2-3 minutes per start, 8 starts per model.
"""
import argparse, json, math, os, re, shutil, signal, struct, subprocess, sys, tempfile, time, urllib.request
from pathlib import Path

import numpy as np

CASES = [("exit code 127", "Meaning?", ["not found", "denied", "memory", "success"]),
         ("HTTP 401", "Cause?", ["credentials", "disk", "url", "size"]),
         ("Makefile src/ tests/", "Build with?", ["make", "npm", "cargo", "gradle"]),
         ("edit failed: old_string not found", "Next?", ["read file", "retry", "delete", "give up"]),
         ("supply 35 C, return 30 C", "Spread?", ["5 K", "35 K", "30 K", "65 K"]),
         ("tests pass, task done", "Final message?", ["short summary", "full files", "apology", "nothing"]),
         ("user: thanks, fixed", "Do?", ["confirm, stop", "refactor", "rerun tests", "revert"]),
         ("ImportError: requests", "Next?", ["pip install", "delete tests", "rewrite", "reboot"]),
         ("Killed after 60 GB alloc", "Why?", ["out of memory", "syntax", "network", "typo"]),
         ("grep found 250 TODO", "Count?", ["250", "0", "25", "unknown"]),
         ("typo fix in README only", "Commit?", ["README.md", "all files", "none", "history"]),
         ("port 8080 already in use", "Do?", ["find process", "reboot", "delete app", "ignore"]),
         ("permission denied: ./run.sh", "Fix?", ["chmod +x", "rm", "sudo rm -rf", "rename"]),
         ("merge conflict in main.py", "Do?", ["resolve markers", "force push", "delete repo", "ignore"]),
         ("disk 100% full", "First?", ["find large files", "format disk", "buy disk", "ignore"]),
         ("function returns None, expected list", "Bug?", ["missing return", "wrong import", "bad indent", "encoding"])]
SOURCE = Path(os.__file__).with_name("argparse.py").read_text()  # a long text every Python has


def read_adapter(folder):
    """The adapter's tensors as float32 arrays, by name."""
    with open(folder / "adapter_model.safetensors", "rb") as file:
        size = struct.unpack("<Q", file.read(8))[0]
        header = json.loads(file.read(size))
        tensors = {}
        for name, meta in header.items():
            if name == "__metadata__":
                continue
            file.seek(8 + size + meta["data_offsets"][0])
            raw = file.read(meta["data_offsets"][1] - meta["data_offsets"][0])
            if meta["dtype"] == "BF16":
                values = (np.frombuffer(raw, np.uint16).astype(np.uint32) << 16).view(np.float32)
            else:
                values = np.frombuffer(raw, {"F32": np.float32, "F16": np.float16}[meta["dtype"]]).astype(np.float32)
            tensors[name] = values.reshape(meta["shape"])
    return tensors


def write_adapter(folder, config, tensors):
    folder.mkdir(parents=True)
    (folder / "adapter_config.json").write_text(json.dumps(config, indent=2))
    header, offset = {"__metadata__": {"format": "pt"}}, 0
    for name, values in tensors.items():
        header[name] = {"dtype": "F32", "shape": list(values.shape), "data_offsets": [offset, offset + values.nbytes]}
        offset += values.nbytes
    head = json.dumps(header, separators=(",", ":")).encode()
    head += b" " * (-len(head) % 8)
    with open(folder / "adapter_model.safetensors", "wb") as file:
        file.write(struct.pack("<Q", len(head)) + head)
        for values in tensors.values():
            file.write(np.ascontiguousarray(values, np.float32).tobytes())


def make_variants(source, work, scale):
    config, tensors = json.loads((source / "adapter_config.json").read_text()), read_adapter(source)
    is_b = lambda name: ".lora_B." in name
    zero = {name: values * 0 if is_b(name) else values for name, values in tensors.items()}
    scaled = {name: values * scale if is_b(name) else values for name, values in tensors.items()}
    # Twice the rank halves alpha / r (rsLoRA: divides alpha / sqrt(r) by sqrt(2)); B makes up for it.
    gain, padded = math.sqrt(2) if config.get("use_rslora") else 2.0, {}
    for name, values in scaled.items():
        if is_b(name):
            padded[name] = np.concatenate([values * gain, np.zeros_like(values)], axis=1)
        elif ".lora_A." in name:
            padded[name] = np.concatenate([values, np.zeros_like(values)], axis=0)
        else:
            padded[name] = values
    write_adapter(work / "zero", config, zero)
    write_adapter(work / "scaled", config, scaled)
    write_adapter(work / "padded", dict(config, r=2 * config["r"]), padded)
    return {"none": None, "zero": work / "zero", "scaled": work / "scaled", "padded": work / "padded"}


def call(port, path, body=None, timeout=900):
    data = None if body is None else json.dumps(body).encode()
    request = urllib.request.Request(f"http://127.0.0.1:{port}{path}", data, {"Content-Type": "application/json"})
    with urllib.request.urlopen(request, timeout=timeout) as response:
        return json.load(response)


def rows(length):
    return [{"id": f"r{i}", "question": question,
             "state": (f"Context file excerpt:\n{SOURCE[3000 + 4500 * i:][:length]}\n\n" if length else "") +
                      f"Observation: {state}",
             "options": [{"id": f"o{j}", "description": text} for j, text in enumerate(options)]}
            for i, (state, question, options) in enumerate(CASES)]


def centered(port, length):
    out = []
    for row in rows(length):
        logits = call(port, "/v1/judgments", row)["option_logits"]
        out += [value - sum(logits) / len(logits) for value in logits]
    return np.array(out)


def run(arguments, model, adapter, ane, log):
    """One start: its logits for the short and the long prompts and a line of what the server reported."""
    command = [arguments.splash, "serve", "--model", "local/lora-matrix", "--model-dir", str(model), "--language-only",
               "--port", str(arguments.port)]
    command += ["--lora", str(adapter)] if adapter else []
    command += [] if ane else ["--disable-ane"]
    command += ["--draft-model", arguments.draft_model] if arguments.draft_model else []
    start = time.time()
    with open(log, "w") as output:
        server = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT, start_new_session=True)
    try:
        while True:
            if server.poll() is not None:
                raise RuntimeError(f"the server stopped; see {log}")
            try:
                call(arguments.port, "/v1/models", timeout=2)
                break
            except OSError:
                time.sleep(2)
        ready = time.time() - start
        short, long = centered(arguments.port, 0), centered(arguments.port, 7000)
        call(arguments.port, "/v1/chat/completions", {
            "model": "local/lora-matrix", "max_tokens": 300, "temperature": 0, "reasoning_effort": "none",
            "messages": [{"role": "user", "content": "Write a Python class `TTLCache` with LRU eviction and tests."}]})
        split = (call(arguments.port, "/status").get("ane_ffn") or {}).get("split_commands", 0)
    finally:
        os.killpg(server.pid, signal.SIGINT)
        try:
            server.wait(90)
        except subprocess.TimeoutExpired:
            os.killpg(server.pid, signal.SIGKILL)
    done = re.findall(r"([\d.]+) tok/s · ([\d.]+) tok/cycle", Path(log).read_text(errors="replace"))
    speed = f"{done[-1][0]:>6} tok/s {done[-1][1]:>4} tok/cycle" if done else "no decode line"
    return short, long, f"ready {ready:5.0f} s | split commands {split:4d} | {speed}"


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--model-dir", action="append", required=True, type=Path)
    parser.add_argument("--lora", required=True, type=Path)
    parser.add_argument("--draft-model", help="passed on to splash serve")
    parser.add_argument("--splash", default="./splash")
    parser.add_argument("--port", type=int, default=8011)
    parser.add_argument("--scale", type=float, default=4.0)
    parser.add_argument("--ane", choices=["both", "on", "off"], default="both")
    parser.add_argument("--work", type=Path, help="keep the adapters and server logs here")
    arguments = parser.parse_args()
    work = arguments.work or Path(tempfile.mkdtemp(prefix="lora-matrix-"))
    rms = lambda values: float(np.sqrt(np.mean(values ** 2)))
    try:
        variants = make_variants(arguments.lora, work / "adapters", arguments.scale)
        for number, model in enumerate(arguments.model_dir):
            print(f"\n{model}")
            logits = {}
            for ane in [mode == "on" for mode in ("on", "off") if arguments.ane in ("both", mode)]:
                for name, adapter in variants.items():
                    label = f"{name:6} {'ane' if ane else 'gpu'}"
                    log = work / f"serve-{number}-{name}-{'ane' if ane else 'gpu'}.log"
                    short, long, line = run(arguments, model, adapter, ane, log)
                    logits[name, ane] = (short, long)
                    print(f"  {label} | {line}", flush=True)
            for ane in sorted({ane for _, ane in logits}, reverse=True):
                where = "Neural Engine" if ane else "GPU only"
                for a, b, text in (("zero", "none", "zero adapter - no adapter"), ("padded", "scaled", "twice the rank - given rank"),
                                   ("scaled", "zero", f"effect of the adapter x{arguments.scale:g}")):
                    print(f"  {where:13} | {text:27} | logit RMS short {rms(logits[a, ane][0] - logits[b, ane][0]):.3f}"
                          f" long {rms(logits[a, ane][1] - logits[b, ane][1]):.3f}")
            if ("scaled", True) in logits and ("scaled", False) in logits:
                for index, text in ((0, "short"), (1, "long")):
                    with_ane = logits["scaled", True][index] - logits["zero", True][index]
                    gpu_only = logits["scaled", False][index] - logits["zero", False][index]
                    print(f"  effect, Neural Engine against GPU only, {text:5}: correlation "
                          f"{np.corrcoef(with_ane, gpu_only)[0, 1]:.3f}, slope {with_ane @ gpu_only / (gpu_only @ gpu_only):.2f}")
    finally:
        if not arguments.work:
            shutil.rmtree(work, ignore_errors=True)


if __name__ == "__main__":
    sys.exit(main())

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.

LoRa support?

3 participants