Repository navigation
Conversation
|
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>
72afaa7 to
6d17850
Compare
|
Thank you for this very important feature! 🚀 |
|
Thanks! It is out of draft now and rebased on current None of the open points is a blocker from my side. They are limits of this first version: 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 |
|
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.
|
|
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 Run it from the repository root of the branch. This is what it prints here (M5 Pro, 64 GB, MLX oQ4e of an abliterated Qwen3.8-27B, 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()) |
Closes #646. Rebased on
main(1.7.3 and the two fixes after it).What this adds
splash serve --model-dir PATH --lora DIRserves the target with the PEFT LoRAadapter in
DIR(adapter_config.jsonandadapter_model.safetensorsaspeftsaves them). The adapter is applied as the model runs, not merged: a4-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)withWas quantizedand
A,Bin BF16.How it works
The adapter is part of the model, not a mode of the engine:
--loralinks the two PEFT files into the assembled model root(
lora/), as--mmprojlinks a projector. Their digests are in theassembly's record, so a retrained adapter is another prepared model.
inspectModelRootreads the configuration intoModelDescriptor::loraand 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.cpploads the tensorsand 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().Linearadds the update wherever it runs an updated projection;the model's steps and the engine do not know of it (
QwenTarget.cppandeverything in
runtime/engine/are unchanged).t = A xis one extradispatch per projection or gate/up pair. The staged BF16 decode tile adds
B tas further steps of its own accumulation, so an update of zeros changesno 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 twhere the value is rounded (lora_tile,lora_swiglu_tile). Scratch comes from the arenas, sized from theprojections' shapes.
AneFfntakes updates of one rank on every layer'sgate, up and down (or none), in one step and in two pipelined steps: gate's
and up's
B trun on the ANE as a small FP16 product beside the int8 one,down's rotated
Aas extra int8 rows, and the step's join adds down'sB t. Each share holds its own parts of down'sA, so two shares in oneprogram 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):
--disable-aneBoth 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 took1.4% to 2% longer with the adapter in three alternating runs.
How I tested it
On
mainat d40c250:make check:check-source(architecture check included; no line addedto
runtime/engine),check-native-engine(CPU, Metal, sanitizers, buildconfigurations) and
check-pythonpass.check-appdoes notrun on my machine: its test bundle does not find
Sparkle.frameworkundermy 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/.lora-projectiontest: every path (staged decode tile in one row groupand 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-ffntest runs the split with a LoRA model as well: accuracy againstthe 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-configurationtest: adapter configurations accepted and refused,an Inkling-2-Mini root's adapter among the refused.
--lora(linking, launcher, completions)./v1/judgmentsoption logits. On the decode path (promptsunder 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).
--max-concurrent-requests 8): eight requests atonce, whose steps run up to 128 rows, answer correctly in 7.1-7.9 s, against
8.0-8.3 s without the adapter.
tasks, 4 of 4, over 38 requests and 52 split commands, none rerun.
Open points
--loraneeds--model-dir; adapters for catalog packages are not wired.that route is covered by the unit test but I have not run it on a real model.
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.
(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.
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