Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Add batched multi-LoRA training kernels (#14648)

Daniel Han3c7890559f31
diff --git a/tests/test_multi_lora.py b/tests/test_multi_lora.py
new file mode 100644
index 00000000000..b359f5b1c72
--- /dev/null
+++ b/tests/test_multi_lora.py
@@ -0,0 +1,708 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Batched multi-LoRA training: kernels against an fp64 reference, and per-adapter isolation."""
+
+from __future__ import annotations
+
+import os
+import pathlib
+import subprocess
+import sys
+import textwrap
+
+import pytest
+import torch
+import unsloth # noqa: F401
+
+from real_accelerator import has_real_cuda
+from unsloth.kernels import multi_lora as ml
+
+REPO = pathlib.Path(__file__).resolve().parents[1]
+
+
+def _case(
+ U = 3,
+ M = 37,
+ K = 48,
+ N = 40,
+ R = 8,
+ seed = 0,
+ dtype = torch.float64,
+ device = "cpu",
+):
+ g = torch.Generator().manual_seed(seed)
+ X = torch.randn(M, K, generator = g, dtype = torch.float64)
+ W = torch.randn(N, K, generator = g, dtype = torch.float64) / 7
+ A = torch.randn(U, R, K, generator = g, dtype = torch.float64)
+ B = torch.randn(U, N, R, generator = g, dtype = torch.float64)
+ ids = torch.randint(-1, U, (M,), generator = g)
+ ids[ids == U - 1] = 0 # the last adapter gets no tokens
+ scales = torch.linspace(0.5, 2.0, U, dtype = torch.float64)
+ cast = lambda t: t.to(device = device, dtype = dtype)
+ return cast(X), cast(W), cast(A), cast(B), scales.to(device), ids.to(device)
+
+
+def _dense(X, W, A, B, scales, ids):
+ rows = []
+ for t in range(X.shape[0]):
+ y = X[t] @ W.t()
+ u = int(ids[t])
+ if u >= 0:
+ y = y + scales[u] * (X[t] @ A[u].t()) @ B[u].t()
+ rows.append(y)
+ return torch.stack(rows)
+
+
+def test_batch_groups_tokens_by_adapter_in_original_order():
+ ids = torch.tensor([2, 0, -1, 0, 2, 1, -1, 0])
+ batch = ml.MultiLoraBatch.from_adapter_ids(ids, 4)
+ assert batch.seg_start.tolist() == [0, 3, 4, 6, 6]
+ assert batch.sorted_idx.tolist()[:6] == [1, 3, 7, 5, 0, 4]
+ assert sorted(batch.sorted_idx.tolist()[6:]) == [2, 6]
+ per_row = ml.MultiLoraBatch.from_adapter_ids(torch.tensor([1, 0]), 2, seq_len = 3)
+ assert per_row.seg_start.tolist() == [0, 3, 6]
+ assert per_row.sorted_idx.tolist() == [3, 4, 5, 0, 1, 2]
+ with pytest.raises(ValueError):
+ ml.MultiLoraBatch.from_adapter_ids(torch.tensor([0, 4]), 4)
+
+
+def test_reference_delta_matches_the_per_token_definition():
+ X, W, A, B, scales, ids = _case()
+ batch = ml.MultiLoraBatch.from_adapter_ids(ids, A.shape[0])
+ Y = X @ W.t() + ml.multi_lora_delta(X, A, B, scales, batch)
+ torch.testing.assert_close(Y, _dense(X, W, A, B, scales, ids), rtol = 1e-12, atol = 1e-12)
+
+
+def _tiny_model(U, ranks = 4):
+ torch.manual_seed(0)
+ model = torch.nn.Sequential(torch.nn.Linear(16, 24), torch.nn.Tanh(), torch.nn.Linear(24, 8))
+ model = model.double()
+ ml.inject_multi_lora(model, ["0", "2"], U, r = ranks, lora_alpha = 8)
+ for _, layer in ml._layers(model):
+ layer.double()
+ for B in layer.lora_B:
+ torch.nn.init.normal_(B)
+ return model
+
+
+def test_each_adapter_gets_only_its_own_gradient():
+ model = _tiny_model(3)
+ x = torch.randn(10, 16, dtype = torch.float64)
+ ids = torch.tensor([0, 1, 0, 2, 1, 0, -1, 2, 1, 0])
+ ml.set_multi_lora_batch(model, ids)
+ out = model(x)
+ # Loss on adapter 1's rows only: adapters 0 and 2 must see exactly zero.
+ out[ids == 1].pow(2).sum().backward()
+ for _, layer in ml._layers(model):
+ for params in (layer.lora_A, layer.lora_B):
+ assert params[0].grad.abs().max() == 0 and params[2].grad.abs().max() == 0
+ assert params[1].grad.abs().max() > 0
+ assert all(not p.requires_grad for n, p in model.named_parameters() if "lora_" not in n)
+
+
+def test_batched_training_matches_each_adapter_trained_alone():
+ U, steps = 2, 4
+ x = torch.randn(8, 16, dtype = torch.float64)
+ target = torch.randn(8, 8, dtype = torch.float64)
+ ids = torch.tensor([0, 1, 1, 0, 0, 1, 0, 1])
+
+ def train(model, rows, row_ids):
+ opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr = 1e-2)
+ ml.set_multi_lora_batch(model, row_ids)
+ for _ in range(steps):
+ opt.zero_grad()
+ err = (model(x[rows]) - target[rows]).pow(2).mean(1)
+ loss = sum(err[row_ids == u].mean() for u in range(U) if (row_ids == u).any())
+ loss.backward()
+ ml.drop_absent_adapter_grads_(model)
+ ml.clip_grad_norm_per_adapter_(model, 0.5)
+ opt.step()
+ return model
+
+ batched = train(_tiny_model(U), slice(None), ids)
+ for u in range(U):
+ solo = train(_tiny_model(U), ids == u, torch.full((int((ids == u).sum()),), u))
+ for (_, a), (_, b) in zip(ml._layers(batched), ml._layers(solo)):
+ torch.testing.assert_close(a.lora_A[u], b.lora_A[u], rtol = 1e-10, atol = 1e-12)
+ torch.testing.assert_close(a.lora_B[u], b.lora_B[u], rtol = 1e-10, atol = 1e-12)
+
+
+def test_ranks_differ_per_adapter_and_export_at_their_own_rank():
+ model = _tiny_model(2, ranks = [2, 4])
+ layer = ml._layers(model)[0][1]
+ A, B = layer.stacked()
+ assert A.shape == (2, 4, 16) and B.shape == (2, 24, 4)
+ assert A[0, 2:].abs().max() == 0 and B[0, :, 2:].abs().max() == 0
+ state = ml.adapter_state_dict(model, 0)
+ assert state["base_model.model.0.lora_A.weight"].shape == (2, 16)
+ assert state["base_model.model.0.lora_B.weight"].shape == (24, 2)
+ assert layer.scales.tolist() == [4.0, 2.0]
+
+
+def test_an_adapter_absent_from_the_batch_is_not_stepped():
+ model = _tiny_model(3)
+ params = [p for p in model.parameters() if p.requires_grad]
+ opt = torch.optim.AdamW(params, lr = 1e-2, weight_decay = 0.1)
+ before = [p.detach().clone() for p in params]
+ ml.set_multi_lora_batch(model, torch.tensor([0, 2, 0, 2]))
+ model(torch.randn(4, 16, dtype = torch.float64)).sum().backward()
+ assert ml.drop_absent_adapter_grads_(model) == [1]
+ ml.clip_grad_norm_per_adapter_(model, 1.0)
+ opt.step()
+ for (name, p), old in zip(
+ [(n, p) for n, p in model.named_parameters() if p.requires_grad], before
+ ):
+ moved = not torch.equal(p, old)
+ assert moved == (".1" not in name.rsplit("lora_", 1)[1]), name
+ assert (p in opt.state and len(opt.state[p]) > 0) == moved, name
+
+
+def test_a_target_that_matches_nothing_leaves_the_model_trainable():
+ model = torch.nn.Sequential(torch.nn.Linear(4, 4))
+ with pytest.raises(ValueError):
+ ml.inject_multi_lora(model, ["q_proj"], 2)
+ assert all(p.requires_grad for p in model.parameters())
+
+
+def test_a_single_string_target_is_one_name():
+ torch.manual_seed(0)
+ model = torch.nn.Sequential(torch.nn.Linear(4, 4), torch.nn.Linear(4, 4))
+ assert ml.inject_multi_lora(model, "1", 2) == ["1"]
+
+
+def test_per_adapter_loss_is_each_adapters_own_mean():
+ logits = torch.randn(3, 5, 7)
+ labels = torch.randint(0, 7, (3, 5))
+ labels[1, 3:] = -100
+ total, losses = ml.per_adapter_loss(logits, labels, torch.tensor([1, 0, 1]), 2)
+ lone = lambda r: torch.nn.functional.cross_entropy(
+ logits[r, :-1].reshape(-1, 7), labels[r, 1:].reshape(-1), ignore_index = -100
+ )
+ torch.testing.assert_close(losses, torch.stack([lone([1]), lone([0, 2])]))
+ torch.testing.assert_close(total, losses.sum())
+
+
+def test_targets_match_qualified_names_like_peft():
+ torch.manual_seed(0)
+ model = torch.nn.Sequential(torch.nn.Sequential(torch.nn.Linear(4, 4)), torch.nn.Linear(4, 4))
+ assert ml.inject_multi_lora(model, ["0.0"], 2) == ["0.0"]
+ assert isinstance(model[0][0], ml.MultiLoraLinear) and not isinstance(
+ model[1], ml.MultiLoraLinear
+ )
+
+
+def test_layers_refuse_a_batch_that_does_not_match_the_tokens():
+ model = _tiny_model(2)
+ with pytest.raises(ValueError):
+ model(torch.randn(4, 16, dtype = torch.float64))
+ ml.set_multi_lora_batch(model, torch.tensor([0, 1, 0]))
+ with pytest.raises(ValueError):
+ model(torch.randn(4, 16, dtype = torch.float64))
+
+
+_INTERPRET = textwrap.dedent(
+ """
+ import importlib.util, os, sys, types
+ import torch
+ import triton
+ import triton.language as tl
+ root = sys.argv[1]
+
+ @triton.jit
+ def _probe(X, n):
+ for i in range(0, n, 1):
+ tl.store(X + i, i)
+
+ try: # some interpreter builds cannot take a runtime loop bound with this NumPy
+ _probe[(1,)](torch.zeros(2), 2)
+ except Exception as exc: # noqa: BLE001
+ print("INTERPRETER UNSUPPORTED", repr(exc)[:200])
+ sys.exit(0)
+ pkg = types.ModuleType("mlk"); pkg.__path__ = []; sys.modules["mlk"] = pkg
+ utils = types.ModuleType("mlk.utils")
+ utils._base_quant_state = lambda layer, W: None
+ utils.fast_dequantize = lambda W, q = None, dtype = None, **k: W
+ utils.matmul_lora = lambda X, W, Wq, A, B, s, out = None: X @ W.t()
+ utils.torch_amp_custom_fwd = utils.torch_amp_custom_bwd = lambda f: f
+ sys.modules["mlk.utils"] = utils
+ spec = importlib.util.spec_from_file_location("mlk.multi_lora", os.path.join(root, "unsloth/kernels/multi_lora.py"))
+ ml = importlib.util.module_from_spec(spec); sys.modules[spec.name] = ml; spec.loader.exec_module(ml)
+ torch.manual_seed(0)
+ U, M, K, N, R = 3, 37, 48, 40, 8
+ X = torch.randn(M, K, requires_grad = True)
+ W = torch.randn(N, K) / 7
+ A = torch.randn(U, R, K, requires_grad = True)
+ B = torch.randn(U, N, R, requires_grad = True)
+ scales = torch.tensor([0.5, 2.0, 1.0])
+ ids = torch.randint(-1, U, (M,)); ids[ids == 2] = 0
+ batch = ml.MultiLoraBatch.from_adapter_ids(ids, U)
+ if len(sys.argv) > 2: # negative control: a wrong segment table must be caught
+ batch.seg_start[1] += 1
+ Y = ml.MultiLoRA_W.apply(X, W, None, A, B, scales, batch.sorted_idx, batch.seg_start)
+ g = torch.randn_like(Y)
+ got = (Y,) + torch.autograd.grad(Y, (X, A, B), g)
+ batch = ml.MultiLoraBatch.from_adapter_ids(ids, U)
+ X64, A64, B64 = [t.detach().double().requires_grad_() for t in (X, A, B)]
+ Y64 = X64 @ W.double().t() + ml.multi_lora_delta(X64, A64, B64, scales.double(), batch)
+ want = (Y64,) + torch.autograd.grad(Y64, (X64, A64, B64), g.double())
+ for name, a, b in zip(("Y", "dX", "dA", "dB"), got, want):
+ err = (a.double() - b).abs().max().item()
+ assert err <= 1e-4 * max(b.abs().max().item(), 1), (name, err)
+ assert got[2][2].abs().max() == 0 and got[3][2].abs().max() == 0
+ print("KERNELS OK")
+ """
+)
+
+
[email protected]("negative_control", [False, True])
+def test_triton_kernels_match_fp64_in_the_interpreter(tmp_path, negative_control):
+ pytest.importorskip("triton")
+ script = tmp_path / "interpret.py"
+ script.write_text(_INTERPRET, encoding = "utf-8")
+ env = {**os.environ, "TRITON_INTERPRET": "1"}
+ argv = [sys.executable, str(script), str(REPO)] + (["break"] if negative_control else [])
+ proc = subprocess.run(argv, env = env, capture_output = True, text = True, timeout = 600)
+ if "INTERPRETER UNSUPPORTED" in proc.stdout:
+ pytest.skip(proc.stdout.strip())
+ if negative_control:
+ assert proc.returncode != 0 and "AssertionError" in proc.stderr, proc.stdout + proc.stderr
+ else:
+ assert proc.returncode == 0 and "KERNELS OK" in proc.stdout, proc.stdout + proc.stderr
+
+
[email protected](not has_real_cuda(), reason = "needs a CUDA GPU")
[email protected]("dtype", [torch.float32, torch.float16, torch.bfloat16])
+ "shape", [(3, 37, 48, 40, 8), (4, 1000, 512, 768, 16), (2, 257, 4096, 1024, 64)]
+)
+def test_triton_kernels_match_fp64_on_gpu(dtype, shape):
+ if dtype == torch.bfloat16 and not torch.cuda.is_bf16_supported():
+ pytest.skip("no bf16")
+ U, M, K, N, R = shape
+ X, W, A, B, scales, ids = _case(U, M, K, N, R, dtype = dtype, device = "cuda")
+ X.requires_grad_()
+ A.requires_grad_()
+ B.requires_grad_()
+ batch = ml.MultiLoraBatch.from_adapter_ids(ids, U)
+ Y = ml.multi_lora_linear(X, W, None, None, A, B, scales.float(), batch)
+ g = torch.randn_like(Y)
+ got = (Y,) + torch.autograd.grad(Y, (X, A, B), g)
+ X64, A64, B64 = [t.detach().double().requires_grad_() for t in (X, A, B)]
+ Y64 = X64 @ W.double().t() + ml.multi_lora_delta(X64, A64, B64, scales, batch)
+ want = (Y64,) + torch.autograd.grad(Y64, (X64, A64, B64), g.double())
+ tol = {torch.float32: 1e-4, torch.float16: 2e-2, torch.bfloat16: 6e-2}[dtype]
+ for name, a, b in zip(("Y", "dX", "dA", "dB"), got, want):
+ rel = (a.double() - b).norm() / b.norm().clamp_min(1e-12)
+ assert rel <= tol, (name, rel.item())
+ assert got[2][U - 1].abs().max() == 0 and got[3][U - 1].abs().max() == 0
+
+
+def test_presence_spans_gradient_accumulation_and_resets_after_a_step():
+ model = _tiny_model(3)
+ for ids in (torch.tensor([0, 0]), torch.tensor([2, 2])):
+ ml.set_multi_lora_batch(model, ids)
+ model(torch.randn(2, 16, dtype = torch.float64)).sum().backward()
+ # Adapter 0 trained in the first microbatch: its accumulated gradient survives.
+ assert ml.drop_absent_adapter_grads_(model) == [1]
+ layer = ml._layers(model)[0][1]
+ assert layer.lora_B[0].grad is not None and layer.lora_B[1].grad is None
+ assert layer.seen is None
+
+
+def test_presence_and_loss_means_are_global_across_ranks(monkeypatch):
+ groups = []
+
+ def all_reduce(
+ t,
+ op = None,
+ group = None,
+ ):
+ groups.append(group)
+ if t.dtype == torch.int32: # presence: the other rank trained adapter 1
+ t.add_(torch.tensor([0, 1], dtype = torch.int32))
+ else: # valid tokens per adapter: 10 more for adapter 1 on the other rank
+ t.add_(torch.tensor([0.0, 10.0], dtype = t.dtype))
+
+ monkeypatch.setattr(ml, "_distributed", lambda: True)
+ monkeypatch.setattr(torch.distributed, "all_reduce", all_reduce)
+ monkeypatch.setattr(torch.distributed, "get_world_size", lambda group = None: 2)
+ model = _tiny_model(2)
+ ml.set_multi_lora_batch(model, torch.tensor([0]))
+ model(torch.randn(1, 16, dtype = torch.float64)).sum().backward()
+ assert ml.drop_absent_adapter_grads_(model, process_group = "dp") == []
+
+ logits = torch.randn(2, 6, 7)
+ labels = torch.randint(0, 7, (2, 6))
+ total, local = ml.per_adapter_loss(logits, labels, torch.tensor([0, 1]), 2, process_group = "dp")
+ # This rank: 5 tokens per adapter. Adapter 1 also has 10 on the other rank, so it weighs 5/15 here.
+ torch.testing.assert_close(total, (local[0] * 5 / 5 + local[1] * 5 / 15) * 2)
+ assert groups == ["dp", "dp"]
+
+
+def test_an_adapter_whose_labels_are_all_ignored_does_not_train():
+ model = _tiny_model(2)
+ params = [p for p in model.parameters() if p.requires_grad]
+ opt = torch.optim.AdamW(params, lr = 1e-2, weight_decay = 0.1)
+ ml.set_multi_lora_batch(model, torch.tensor([0, 1]))
+ hidden = model(torch.randn(2, 16, dtype = torch.float64))
+ logits = hidden.view(2, 4, 2)
+ labels = torch.tensor([[0, 1, 0, 1], [-100, -100, -100, -100]])
+ total, _ = ml.per_adapter_loss(logits, labels, torch.tensor([0, 1]), 2, model = model)
+ total.backward()
+ assert ml.drop_absent_adapter_grads_(model) == [1]
+ layer = ml._layers(model)[0][1]
+ before = layer.lora_B[1].detach().clone()
+ opt.step()
+ assert torch.equal(layer.lora_B[1], before) and layer.lora_B[1] not in opt.state
+
+
+def test_gradient_accumulation_weights_microbatches_by_tokens():
+ torch.manual_seed(1)
+ x = torch.randn(4, 16, dtype = torch.float64)
+ ids = torch.tensor([0, 1, 0, 1])
+ labels = torch.tensor([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, -100, -100], [1, 1, 0, 0]])
+
+ def grads(chunks, num_items):
+ model = _tiny_model(2)
+ for rows in chunks:
+ ml.set_multi_lora_batch(model, ids[rows])
+ logits = model(x[rows]).view(len(rows), 4, 2)
+ total, _ = ml.per_adapter_loss(
+ logits, labels[rows], ids[rows], 2, num_items_in_batch = num_items
+ )
+ total.backward()
+ return [p.grad.clone() for p in model.parameters() if p.requires_grad]
+
+ window = sum(ml.adapter_token_counts(labels[r], ids[r], 2) for r in ([0, 1], [2, 3]))
+ assert window.tolist() == [4.0, 6.0]
+ whole = grads([[0, 1, 2, 3]], None)
+ for a, b in zip(grads([[0, 1], [2, 3]], window), whole):
+ torch.testing.assert_close(a, b)
+ # Per-microbatch means weight adapter 0's 1-token microbatch like its 3-token one.
+ assert any(not torch.allclose(a, b) for a, b in zip(grads([[0, 1], [2, 3]], None), whole))
+
+
+def test_layers_with_different_adapter_counts_are_refused():
+ model = torch.nn.Sequential(torch.nn.Linear(8, 8), torch.nn.Linear(8, 8))
+ ml.inject_multi_lora(model, ["0"], 2, r = 4)
+ ml.inject_multi_lora(model, ["1"], 4, r = 4)
+ with pytest.raises(ValueError, match = "same number of adapters"):
+ ml.set_multi_lora_batch(model, torch.tensor([3, 0, 1]))
+
+
+def test_a_step_where_no_adapter_trained_clips_to_zero_norms():
+ model = _tiny_model(2)
+ ml.set_multi_lora_batch(model, torch.tensor([-1, -1]))
+ assert ml.drop_absent_adapter_grads_(model) == [0, 1]
+ assert ml.clip_grad_norm_per_adapter_(model, 1.0).tolist() == [0.0, 0.0]
+
+
+def test_fsdp2_sharded_grads_norm_and_clip_on_local_shards(tmp_path):
+ script = tmp_path / "dtensor.py"
+ script.write_text(
+ textwrap.dedent(
+ """
+ import importlib.util, os, sys, types, torch, torch.distributed as dist
+ from torch.distributed.device_mesh import init_device_mesh
+ from torch.distributed.tensor import Shard, distribute_tensor
+
+ pkg = types.ModuleType("mlk"); pkg.__path__ = []; sys.modules["mlk"] = pkg
+ utils = types.ModuleType("mlk.utils")
+ utils._base_quant_state = lambda layer, W: None
+ utils.fast_dequantize = lambda W, q = None, dtype = None, **k: W
+ utils.matmul_lora = lambda X, W, Wq, A, B, s, out = None: X @ W.t()
+ utils.torch_amp_custom_fwd = utils.torch_amp_custom_bwd = lambda f: f
+ sys.modules["mlk.utils"] = utils
+ path = os.path.join(sys.argv[2], "unsloth/kernels/multi_lora.py")
+ spec = importlib.util.spec_from_file_location("mlk.multi_lora", path)
+ ml = importlib.util.module_from_spec(spec); sys.modules[spec.name] = ml; spec.loader.exec_module(ml)
+
+ os.environ.update(MASTER_ADDR = "127.0.0.1", MASTER_PORT = sys.argv[1])
+ dist.init_process_group("gloo", rank = 0, world_size = 1)
+ mesh = init_device_mesh("cpu", (1,))
+ torch.manual_seed(0)
+ model = torch.nn.Sequential(torch.nn.Linear(8, 8))
+ ml.inject_multi_lora(model, ["0"], 2, r = 4)
+ layer = model[0]
+ grads = [torch.randn_like(p) for p in layer.parameters() if p.requires_grad]
+ want = []
+ for u in range(2):
+ sq = sum(g.pow(2).sum() for g in (grads[u], grads[2 + u]))
+ want.append(float(sq.sqrt()))
+ for p, g in zip([p for p in layer.parameters() if p.requires_grad], grads):
+ p.data = distribute_tensor(p.data, mesh, [Shard(0)])
+ p.grad = distribute_tensor(g, mesh, [Shard(0)])
+ got = ml.clip_grad_norm_per_adapter_(model, 0.5)
+ after = ml.per_adapter_grad_norm(model)
+ assert torch.allclose(got, torch.tensor(want), rtol = 1e-5), (got, want)
+ assert torch.allclose(after, torch.tensor([0.5, 0.5]), rtol = 1e-4), after
+ dist.destroy_process_group()
+ print("DTENSOR OK")
+ """
+ ),
+ encoding = "utf-8",
+ )
+ port = str(29500 + os.getpid() % 1000)
+ proc = subprocess.run(
+ [sys.executable, str(script), port, str(REPO)],
+ capture_output = True,
+ text = True,
+ timeout = 600,
+ env = os.environ,
+ )
+ assert proc.returncode == 0 and "DTENSOR OK" in proc.stdout, (
+ proc.stdout[-2000:] + proc.stderr[-4000:]
+ )
+
+
+def test_ddp_two_ranks_train_each_adapter_on_its_global_mean(tmp_path):
+ # gloo DDP, 2 ranks with different adapters: per-adapter grads must equal the global-batch mean.
+ script = tmp_path / "ddp.py"
+ script.write_text(
+ textwrap.dedent(
+ """
+ import importlib.util, os, sys, types, torch, torch.distributed as dist
+ import torch.multiprocessing as mp
+
+ def load(root):
+ pkg = types.ModuleType("mlk"); pkg.__path__ = []; sys.modules["mlk"] = pkg
+ utils = types.ModuleType("mlk.utils")
+ utils._base_quant_state = lambda layer, W: None
+ utils.fast_dequantize = lambda W, q = None, dtype = None, **k: W
+ utils.matmul_lora = lambda X, W, Wq, A, B, s, out = None: X @ W.t()
+ utils.torch_amp_custom_fwd = utils.torch_amp_custom_bwd = lambda f: f
+ sys.modules["mlk.utils"] = utils
+ path = os.path.join(root, "unsloth/kernels/multi_lora.py")
+ spec = importlib.util.spec_from_file_location("mlk.multi_lora", path)
+ ml = importlib.util.module_from_spec(spec); sys.modules[spec.name] = ml
+ spec.loader.exec_module(ml)
+ return ml
+
+ def model(ml):
+ torch.manual_seed(0)
+ m = torch.nn.Sequential(torch.nn.Linear(6, 5)).double()
+ ml.inject_multi_lora(m, ["0"], 3, r = 2)
+ for B in m[0].lora_B:
+ torch.nn.init.normal_(B)
+ return m
+
+ def data():
+ g = torch.Generator().manual_seed(1)
+ x = torch.randn(4, 3, 6, generator = g, dtype = torch.float64)
+ labels = torch.randint(0, 5, (4, 3), generator = g)
+ labels[3, 1:] = -100 # adapter 1's second row: one valid label fewer
+ return x, labels, torch.tensor([0, 0, 1, 1])
+
+ def grads(m):
+ return [p.grad.clone() if p.grad is not None else None for p in m.parameters() if p.requires_grad]
+
+ def worker(rank, root, port, out):
+ os.environ.update(MASTER_ADDR = "127.0.0.1", MASTER_PORT = port)
+ dist.init_process_group("gloo", rank = rank, world_size = 2)
+ ml = load(root)
+ m = torch.nn.parallel.DistributedDataParallel(model(ml))
+ x, labels, ids = data()
+ rows = slice(2 * rank, 2 * rank + 2)
+ ml.set_multi_lora_batch(m.module, ids[rows], seq_len = 3)
+ total, _ = ml.per_adapter_loss(m(x[rows]), labels[rows], ids[rows], 3, model = m.module)
+ total.backward()
+ absent = ml.drop_absent_adapter_grads_(m.module)
+ torch.save({"absent": absent, "grads": grads(m.module)}, f"{out}/rank{rank}.pt")
+ dist.destroy_process_group()
+
+ if __name__ == "__main__":
+ root, port, out = sys.argv[1:4]
+ mp.spawn(worker, args = (root, port, out), nprocs = 2)
+ ml = load(root)
+ m = model(ml)
+ x, labels, ids = data()
+ ml.set_multi_lora_batch(m, ids, seq_len = 3)
+ total, _ = ml.per_adapter_loss(m(x), labels, ids, 3, model = m)
+ total.backward()
+ ml.drop_absent_adapter_grads_(m)
+ want = grads(m)
+ r0, r1 = (torch.load(f"{out}/rank{r}.pt") for r in (0, 1))
+ assert r0["absent"] == r1["absent"] == [2], (r0["absent"], r1["absent"])
+ for a, b, w in zip(r0["grads"], r1["grads"], want):
+ if w is None:
+ assert a is None and b is None
+ continue
+ torch.testing.assert_close(a, b)
+ torch.testing.assert_close(a, w)
+ print("DDP OK")
+ """
+ ),
+ encoding = "utf-8",
+ )
+ port = str(30500 + os.getpid() % 1000)
+ proc = subprocess.run(
+ [sys.executable, str(script), str(REPO), port, str(tmp_path)],
+ capture_output = True,
+ text = True,
+ timeout = 600,
+ )
+ assert proc.returncode == 0 and "DDP OK" in proc.stdout, (
+ proc.stdout[-2000:] + proc.stderr[-4000:]
+ )
+
+
[email protected](not has_real_cuda(), reason = "needs a CUDA GPU")
[email protected]("triton_kernels", [True, False])
+def test_compiles_fullgraph_without_recompiling_per_batch(triton_kernels):
+ from torch._dynamo.utils import counters
+
+ def model():
+ torch.manual_seed(0)
+ m = torch.nn.Sequential(torch.nn.Linear(64, 128), torch.nn.GELU(), torch.nn.Linear(128, 32))
+ m = m.cuda().to(torch.bfloat16)
+ ml.inject_multi_lora(m, ["0", "2"], 3, r = [4, 8, 8])
+ for _, layer in ml._layers(m):
+ for B in layer.lora_B:
+ torch.nn.init.normal_(B, std = 0.05)
+ return m
+
+ def step(m, fn, x, ids):
+ ml.set_multi_lora_batch(m, ids)
+ m.zero_grad(set_to_none = True)
+ y = fn(x)
+ y.float().pow(2).mean().backward()
+ return [y.detach()] + [p.grad.clone() for p in m.parameters() if p.requires_grad]
+
+ ml.set_multi_lora_triton(triton_kernels)
+ try:
+ torch._dynamo.reset()
+ counters.clear()
+ eager, compiled = model(), model()
+ fn = torch.compile(compiled, fullgraph = True)
+ g = torch.Generator().manual_seed(0)
+ for _ in range(4): # same size, different routing: one graph
+ x = torch.randn(48, 64, generator = g).cuda().to(torch.bfloat16)
+ ids = torch.randint(-1, 3, (48,), generator = g).cuda()
+ for a, b in zip(step(compiled, fn, x, ids), step(eager, eager, x, ids)):
+ rel = (a.float() - b.float()).norm() / b.float().norm().clamp_min(1e-12)
+ assert rel < 3e-2, rel
+ assert sum(counters["graph_break"].values()) == 0
+ assert counters["stats"]["unique_graphs"] == 1
+ finally:
+ ml.set_multi_lora_triton(True)
+ torch._dynamo.reset()
+
+
+def _tiny_qwen3(attn):
+ from transformers import Qwen3Config, Qwen3ForCausalLM
+
+ torch.manual_seed(0)
+ config = Qwen3Config(
+ vocab_size = 64,
+ hidden_size = 32,
+ intermediate_size = 64,
+ num_hidden_layers = 2,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ head_dim = 8,
+ max_position_embeddings = 128,
+ attn_implementation = attn,
+ )
+ config.use_cache = (
+ False # training setup: transformers only detects packed rows without a KV cache
+ )
+ model = Qwen3ForCausalLM(config).double()
+ targets = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+ ml.inject_multi_lora(model, targets, 8, r = 4)
+ for _, layer in ml._layers(model):
+ layer.double()
+ for B in layer.lora_B:
+ torch.nn.init.normal_(B, std = 0.1)
+ return model
+
+
[email protected]("attn", ["sdpa", "eager"])
+def test_packed_rows_of_eight_adapters_match_each_sequence_alone(attn):
+ # bsz 2, 8 users' sequences packed 4 per row, position_ids restarting per sequence (varlen packing).
+ model = _tiny_qwen3(attn)
+ g = torch.Generator().manual_seed(0)
+ lengths = [5, 9, 3, 7, 6, 4, 8, 5]
+ seqs = [torch.randint(0, 64, (n,), generator = g) for n in lengths]
+
+ def adapter_grads(u):
+ return [p.grad.clone() for _, l in ml._layers(model) for p in (l.lora_A[u], l.lora_B[u])]
+
+ alone = {}
+ for u, seq in enumerate(seqs):
+ model.zero_grad(set_to_none = True)
+ ml.set_multi_lora_batch(model, torch.tensor([u]), seq_len = len(seq))
+ out = model(input_ids = seq[None]).logits
+ total, losses = ml.per_adapter_loss(out, seq[None], torch.tensor([u]), 8)
+ total.backward()
+ alone[u] = (losses[u], adapter_grads(u))
+
+ rows = [list(range(0, 4)), list(range(4, 8))]
+ T = max(sum(lengths[u] for u in r) for r in rows)
+ input_ids = torch.zeros(2, T, dtype = torch.long)
+ labels = torch.full((2, T), -100)
+ ids = torch.full((2, T), -1)
+ position_ids = torch.zeros(2, T, dtype = torch.long)
+ for b, r in enumerate(rows):
+ at = 0
+ for u in r:
+ n = lengths[u]
+ input_ids[b, at : at + n] = seqs[u]
+ labels[b, at + 1 : at + n] = seqs[u][1:] # first token of a sequence is never a label
+ ids[b, at : at + n] = u
+ position_ids[b, at : at + n] = torch.arange(n)
+ at += n
+ position_ids[b, at:] = torch.arange(T - at) # padding tail: its own sequence, no labels
+
+ def packed(position_ids):
+ model.zero_grad(set_to_none = True)
+ ml.set_multi_lora_batch(model, ids)
+ out = model(input_ids = input_ids, position_ids = position_ids).logits
+ total, losses = ml.per_adapter_loss(out, labels, ids, 8)
+ total.backward()
+ return losses, {u: adapter_grads(u) for u in range(8)}
+
+ losses, grads = packed(position_ids)
+ for u in range(8): # Qwen3's RMSNorm runs in float32: fp32-level tolerance
+ torch.testing.assert_close(losses[u], alone[u][0], rtol = 1e-5, atol = 1e-6)
+ for a, b in zip(grads[u], alone[u][1]):
+ torch.testing.assert_close(a, b, rtol = 1e-5, atol = 1e-6)
+ # Negative control: without restarting positions the sequences attend to each other.
+ contaminated, _ = packed(torch.arange(T).expand(2, T))
+ assert not torch.allclose(contaminated, losses, rtol = 1e-3, atol = 1e-4)
+
+
+def _absent_adapter_case(dtype):
+ # Every token is adapter 0's; adapter 1 is absent from the batch.
+ X, W, A, B, scales, _ = _case(U = 2, M = 9, K = 16, N = 12, R = 4, dtype = torch.float64)
+ ids = torch.zeros(X.shape[0], dtype = torch.long)
+ batch = ml.MultiLoraBatch.from_adapter_ids(ids, 2)
+ want = (X @ W.t() + scales[0] * (X @ A[0].t()) @ B[0].t()).to(dtype)
+ cast = lambda t: t.to(dtype)
+ return cast(X), cast(W), cast(A), cast(B), scales, batch, want
+
+
[email protected]("poison", ["nan_A", "nan_B", "inf_B", "fp16_overflow"])
+def test_an_absent_adapter_cannot_corrupt_present_tokens_in_the_reference_path(poison):
+ dtype = torch.float16 if poison == "fp16_overflow" else torch.float64
+ X, W, A, B, scales, batch, want = _absent_adapter_case(dtype)
+ A, B = A.clone(), B.clone()
+ if poison == "nan_A":
+ A[1, 0, 0] = float("nan")
+ elif poison == "nan_B":
+ B[1, 0, 0] = float("nan")
+ elif poison == "inf_B":
+ B[1, 0, 0] = float("inf")
+ else: # finite fp16 weights whose X @ A.T overflows to inf
+ A[1] = 6.0e4
+ X = X.requires_grad_()
+ A = A.requires_grad_()
+ B = B.requires_grad_()
+ Y = X @ W.t() + ml.multi_lora_delta(X, A, B, scales, batch)
+ assert torch.isfinite(Y).all()
+ tol = dict(rtol = 1e-2, atol = 1e-2) if dtype == torch.float16 else {}
+ torch.testing.assert_close(Y, want, **tol)
+ Y.float().pow(2).sum().backward()
+ assert torch.isfinite(A.grad[0]).all() and torch.isfinite(B.grad[0]).all()
+ assert A.grad[0].abs().max() > 0
+ assert torch.isfinite(X.grad).all()
diff --git a/tests/test_multi_lora_absent_nan_a_dx.py b/tests/test_multi_lora_absent_nan_a_dx.py
new file mode 100644
index 00000000000..71b34deb661
--- /dev/null
+++ b/tests/test_multi_lora_absent_nan_a_dx.py
@@ -0,0 +1,50 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Reference path: an absent adapter's non-finite lora_A must not reach dX, or every earlier layer's
+present adapters get NaN gradients (isolation across layers)."""
+
+import pytest
+import torch
+import unsloth # noqa: F401
+from unsloth.kernels import multi_lora as ml
+
+
+def _two_layer(poison, adapter = 2):
+ torch.manual_seed(0)
+ m = torch.nn.Sequential(
+ torch.nn.Linear(16, 24), torch.nn.GELU(), torch.nn.Linear(24, 8)
+ ).double()
+ ml.inject_multi_lora(m, ["0", "2"], 3, r = 4)
+ for _, layer in ml._layers(m):
+ layer.double()
+ for B in layer.lora_B:
+ torch.nn.init.normal_(B, std = 0.1)
+ if poison:
+ with torch.no_grad():
+ m[2].lora_A[adapter][0, 0] = float("nan")
+ return m
+
+
[email protected]("negative_control", [False, True])
+def test_absent_nan_lora_a_does_not_reach_earlier_layers(negative_control):
+ ml.set_multi_lora_triton(False)
+ try:
+ grads = {}
+ for poison in (False, True):
+ # Negative control: poison present adapter 0 so the check can fail.
+ m = _two_layer(poison, adapter = 0 if negative_control else 2)
+ x = torch.randn(40, 16, dtype = torch.float64, generator = torch.Generator().manual_seed(1))
+ ids = torch.randint(0, 2, (40,), generator = torch.Generator().manual_seed(2))
+ ml.set_multi_lora_batch(m, ids)
+ m(x).pow(2).sum().backward()
+ grads[poison] = [p.grad for p in m[0].lora_A[:2]] + [p.grad for p in m[0].lora_B[:2]]
+ finite = all(torch.isfinite(g).all() for g in grads[True])
+ if negative_control:
+ assert not finite
+ else:
+ assert finite
+ for a, b in zip(grads[False], grads[True]):
+ torch.testing.assert_close(a, b, rtol = 0, atol = 0)
+ finally:
+ ml.set_multi_lora_triton(True)
diff --git a/unsloth/kernels/multi_lora.py b/unsloth/kernels/multi_lora.py
new file mode 100644
index 00000000000..bf4b386ee0a
--- /dev/null
+++ b/unsloth/kernels/multi_lora.py
@@ -0,0 +1,871 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""
+Batched multi-LoRA training: many LoRA adapters on one frozen base model, trained in one batch.
+
+Each token belongs to one adapter (or none, id -1); tokens are stable-sorted by adapter once per batch
+and kernels gather rows through that order (like Punica SGMV, but with dX and per-adapter dA / dB).
+
+``UNSLOTH_MULTI_LORA_TRITON=0`` (or no CUDA / XPU) uses a PyTorch loop. LoRA dropout is unsupported.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import math
+import os
+from dataclasses import dataclass
+from typing import Iterable, Optional
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from .utils import (
+ _base_quant_state,
+ fast_dequantize,
+ matmul_lora,
+ torch_amp_custom_bwd,
+ torch_amp_custom_fwd,
+)
+
+try:
+ import triton
+ import triton.language as tl
+ HAS_TRITON = True
+except Exception: # noqa: BLE001
+ HAS_TRITON = False
+
+__all__ = [
+ "MultiLoraBatch",
+ "MultiLoraLinear",
+ "multi_lora_delta",
+ "multi_lora_linear",
+ "inject_multi_lora",
+ "set_multi_lora_batch",
+ "per_adapter_loss",
+ "adapter_token_counts",
+ "per_adapter_grad_norm",
+ "clip_grad_norm_per_adapter_",
+ "drop_absent_adapter_grads_",
+ "adapter_state_dict",
+ "set_multi_lora_triton",
+]
+
+
+# Read once: an environment lookup inside a compiled forward would be a guard on every call.
+_TRITON_ENABLED = HAS_TRITON and os.environ.get("UNSLOTH_MULTI_LORA_TRITON", "1") != "0"
+
+
+def set_multi_lora_triton(enabled: bool) -> None:
+ """Turn the Triton kernels on or off (off = the PyTorch fallback); ``UNSLOTH_MULTI_LORA_TRITON=0``."""
+ global _TRITON_ENABLED
+ _TRITON_ENABLED = bool(enabled) and HAS_TRITON
+
+
+def _use_triton(X: torch.Tensor) -> bool:
+ return _TRITON_ENABLED and X.device.type in ("cuda", "xpu")
+
+
+@dataclass
+class MultiLoraBatch:
+ """``sorted_idx[seg_start[u]:seg_start[u + 1]]`` are adapter u's rows; id -1 sorts last, in no segment.
+
+ Shapes depend only on the token count, so a new batch never changes a kernel grid or compiled graph.
+ """
+
+ sorted_idx: torch.Tensor
+ seg_start: torch.Tensor
+ num_adapters: int
+ token_ids: Optional[torch.Tensor] = None
+
+ @classmethod
+ def from_adapter_ids(
+ cls,
+ adapter_ids: torch.Tensor,
+ num_adapters: int,
+ seq_len: Optional[int] = None,
+ ) -> "MultiLoraBatch":
+ """``adapter_ids``: one id per token (any shape), or one per row with ``seq_len`` tokens each."""
+ ids = adapter_ids.reshape(-1).to(torch.int64)
+ if seq_len is not None:
+ ids = ids.repeat_interleave(seq_len)
+ if ids.numel() and (ids.max() >= num_adapters or ids.min() < -1):
+ raise ValueError(f"Adapter ids must be in [-1, {num_adapters}).")
+ keys = torch.where(ids < 0, torch.full_like(ids, num_adapters), ids)
+ sorted_idx = torch.argsort(keys, stable = True).to(torch.int32)
+ counts = torch.bincount(keys, minlength = num_adapters + 1)[:num_adapters]
+ seg_start = torch.zeros(num_adapters + 1, dtype = torch.int32, device = ids.device)
+ seg_start[1:] = torch.cumsum(counts, 0)
+ return cls(sorted_idx, seg_start, num_adapters, ids)
+
+ @property
+ def num_tokens(self) -> int:
+ return self.sorted_idx.numel()
+
+
+if HAS_TRITON:
+
+ @triton.jit
+ def _seg_mm_kernel(
+ IN,
+ W,
+ OUT,
+ SCALES,
+ IDX,
+ SEG,
+ N,
+ K,
+ stride_in,
+ stride_out,
+ stride_wu,
+ stride_wk,
+ stride_wn,
+ IN_SORTED: tl.constexpr,
+ OUT_SORTED: tl.constexpr,
+ ADD: tl.constexpr,
+ SCALE: tl.constexpr,
+ IEEE: tl.constexpr,
+ BLOCK_M: tl.constexpr,
+ BLOCK_N: tl.constexpr,
+ BLOCK_K: tl.constexpr,
+ ):
+ # OUT[rows] (+)= scale_u * IN[rows] @ W_u, W_u read as (K, N) through strides. A row is either the
+ # token's position in the sorted order (H, dH live there) or its original row (X, Y, dY, dX).
+ pid = tl.program_id(0)
+ u = tl.program_id(1)
+ n_tiles = tl.cdiv(N, BLOCK_N)
+ pid_m = pid // n_tiles
+ pid_n = pid % n_tiles
+ start = tl.load(SEG + u)
+ end = tl.load(SEG + u + 1)
+ m0 = start + pid_m * BLOCK_M
+ if m0 >= end:
+ return
+ offs_p = m0 + tl.arange(0, BLOCK_M)
+ mask_m = offs_p < end
+ rows = tl.load(IDX + offs_p, mask = mask_m, other = 0).to(tl.int64)
+ offs_p = offs_p.to(tl.int64)
+ if IN_SORTED:
+ in_rows = offs_p
+ else:
+ in_rows = rows
+ if OUT_SORTED:
+ out_rows = offs_p
+ else:
+ out_rows = rows
+ offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
+ mask_n = offs_n < N
+ offs_k = tl.arange(0, BLOCK_K)
+ w_base = W + u.to(tl.int64) * stride_wu
+ acc = tl.zeros((BLOCK_M, BLOCK_N), dtype = tl.float32)
+ for k0 in range(0, K, BLOCK_K):
+ kk = k0 + offs_k
+ mask_k = kk < K
+ a = tl.load(
+ IN + in_rows[:, None] * stride_in + kk[None, :],
+ mask = mask_m[:, None] & mask_k[None, :],
+ other = 0.0,
+ )
+ b = tl.load(
+ w_base + kk[:, None] * stride_wk + offs_n[None, :] * stride_wn,
+ mask = mask_k[:, None] & mask_n[None, :],
+ other = 0.0,
+ )
+ if IEEE:
+ acc += tl.dot(a, b, input_precision = "ieee")
+ else:
+ acc += tl.dot(a, b)
+ if SCALE:
+ acc *= tl.load(SCALES + u).to(tl.float32)
+ ptrs = OUT + out_rows[:, None] * stride_out + offs_n[None, :]
+ mask = mask_m[:, None] & mask_n[None, :]
+ if ADD:
+ acc += tl.load(ptrs, mask = mask, other = 0.0).to(tl.float32)
+ tl.store(ptrs, acc.to(OUT.dtype.element_ty), mask = mask)
+
+ @triton.jit
+ def _seg_wgrad_kernel(
+ P,
+ Q,
+ OUT,
+ SCALES,
+ IDX,
+ SEG,
+ I,
+ J,
+ stride_p,
+ stride_q,
+ stride_ou,
+ stride_oi,
+ stride_oj,
+ P_SORTED: tl.constexpr,
+ Q_SORTED: tl.constexpr,
+ SCALE: tl.constexpr,
+ IEEE: tl.constexpr,
+ BLOCK_T: tl.constexpr,
+ BLOCK_I: tl.constexpr,
+ BLOCK_J: tl.constexpr,
+ ):
+ # OUT_u = scale_u * P[seg_u].T @ Q[seg_u]; an adapter with no tokens stores zeros.
+ pid = tl.program_id(0)
+ u = tl.program_id(1)
+ j_tiles = tl.cdiv(J, BLOCK_J)
+ pid_i = pid // j_tiles
+ pid_j = pid % j_tiles
+ start = tl.load(SEG + u)
+ end = tl.load(SEG + u + 1)
+ offs_i = pid_i * BLOCK_I + tl.arange(0, BLOCK_I)
+ offs_j = pid_j * BLOCK_J + tl.arange(0, BLOCK_J)
+ mask_i = offs_i < I
+ mask_j = offs_j < J
+ acc = tl.zeros((BLOCK_I, BLOCK_J), dtype = tl.float32)
+ for t0 in range(start, end, BLOCK_T):
+ offs_p = t0 + tl.arange(0, BLOCK_T)
+ mask_t = offs_p < end
+ rows = tl.load(IDX + offs_p, mask = mask_t, other = 0).to(tl.int64)
+ offs_p = offs_p.to(tl.int64)
+ if P_SORTED:
+ p_rows = offs_p
+ else:
+ p_rows = rows
+ if Q_SORTED:
+ q_rows = offs_p
+ else:
+ q_rows = rows
+ p = tl.load(
+ P + p_rows[None, :] * stride_p + offs_i[:, None],
+ mask = mask_i[:, None] & mask_t[None, :],
+ other = 0.0,
+ )
+ q = tl.load(
+ Q + q_rows[:, None] * stride_q + offs_j[None, :],
+ mask = mask_t[:, None] & mask_j[None, :],
+ other = 0.0,
+ )
+ if IEEE:
+ acc += tl.dot(p, q, input_precision = "ieee")
+ else:
+ acc += tl.dot(p, q)
+ if SCALE:
+ acc *= tl.load(SCALES + u).to(tl.float32)
+ ptrs = (
+ OUT
+ + u.to(tl.int64) * stride_ou
+ + offs_i[:, None] * stride_oi
+ + offs_j[None, :] * stride_oj
+ )
+ tl.store(ptrs, acc.to(OUT.dtype.element_ty), mask = mask_i[:, None] & mask_j[None, :])
+
+
+def _block(n: int, lo: int, hi: int) -> int:
+ return max(lo, min(hi, triton.next_power_of_2(n)))
+
+
+def _launch_seg_mm(
+ inp: torch.Tensor,
+ W: torch.Tensor,
+ out: torch.Tensor,
+ scales: Optional[torch.Tensor],
+ idx: torch.Tensor,
+ seg: torch.Tensor,
+ N: int,
+ stride_wu: int,
+ stride_wk: int,
+ stride_wn: int,
+ in_sorted: bool,
+ out_sorted: bool,
+ add: bool,
+) -> None:
+ M, K = inp.shape
+ BLOCK_M = 64
+ BLOCK_N = _block(N, 16, 128)
+ BLOCK_K = _block(K, 16, 64 if BLOCK_N > 32 else 128)
+ grid = (triton.cdiv(M, BLOCK_M) * triton.cdiv(N, BLOCK_N), seg.shape[0] - 1)
+ _wrap(_seg_mm_kernel)[grid](
+ inp,
+ W,
+ out,
+ scales if scales is not None else inp,
+ idx,
+ seg,
+ N,
+ K,
+ inp.stride(0),
+ out.stride(0),
+ stride_wu,
+ stride_wk,
+ stride_wn,
+ IN_SORTED = in_sorted,
+ OUT_SORTED = out_sorted,
+ ADD = add,
+ SCALE = scales is not None,
+ IEEE = inp.dtype == torch.float32,
+ BLOCK_M = BLOCK_M,
+ BLOCK_N = BLOCK_N,
+ BLOCK_K = BLOCK_K,
+ num_warps = 4,
+ enable_fp_fusion = True,
+ )
+
+
+def _launch_seg_wgrad(
+ P: torch.Tensor,
+ Q: torch.Tensor,
+ out: torch.Tensor,
+ scales: Optional[torch.Tensor],
+ idx: torch.Tensor,
+ seg: torch.Tensor,
+ p_sorted: bool,
+ q_sorted: bool,
+) -> None:
+ _, I, J = out.shape
+ BLOCK_I = _block(I, 16, 64)
+ BLOCK_J = _block(J, 16, 64)
+ grid = (triton.cdiv(I, BLOCK_I) * triton.cdiv(J, BLOCK_J), seg.shape[0] - 1)
+ _wrap(_seg_wgrad_kernel)[grid](
+ P,
+ Q,
+ out,
+ scales if scales is not None else P,
+ idx,
+ seg,
+ I,
+ J,
+ P.stride(0),
+ Q.stride(0),
+ out.stride(0),
+ out.stride(1),
+ out.stride(2),
+ P_SORTED = p_sorted,
+ Q_SORTED = q_sorted,
+ SCALE = scales is not None,
+ IEEE = P.dtype == torch.float32,
+ BLOCK_T = 64,
+ BLOCK_I = BLOCK_I,
+ BLOCK_J = BLOCK_J,
+ num_warps = 4,
+ enable_fp_fusion = True,
+ )
+
+
+# triton_op lets Dynamo trace the launches without a graph break; wrap_triton rejects interpreter kernels.
+_INTERPRETED = os.environ.get("TRITON_INTERPRET", "0") == "1"
+if HAS_TRITON and hasattr(torch.library, "triton_op") and not _INTERPRETED:
+ _wrap = torch.library.wrap_triton
+ _seg_mm_op = torch.library.triton_op("unsloth::multi_lora_seg_mm", mutates_args = {"out"})(
+ _launch_seg_mm
+ )
+ _seg_wgrad_op = torch.library.triton_op("unsloth::multi_lora_seg_wgrad", mutates_args = {"out"})(
+ _launch_seg_wgrad
+ )
+else:
+ _wrap = lambda kernel: kernel # noqa: E731
+ _seg_mm_op, _seg_wgrad_op = _launch_seg_mm, _launch_seg_wgrad
+
+
+def _eager_guard(device: torch.device):
+ if torch.compiler.is_compiling():
+ return contextlib.nullcontext()
+ return _device_guard(device)
+
+
+def _seg_mm(
+ inp: torch.Tensor,
+ W: torch.Tensor,
+ w_strides: tuple[int, int, int],
+ N: int,
+ out: torch.Tensor,
+ batch: MultiLoraBatch,
+ scales: Optional[torch.Tensor],
+ in_sorted: bool,
+ out_sorted: bool,
+ add: bool,
+) -> torch.Tensor:
+ with _eager_guard(inp.device):
+ _seg_mm_op(
+ inp,
+ W,
+ out,
+ scales,
+ batch.sorted_idx,
+ batch.seg_start,
+ N,
+ *w_strides,
+ in_sorted,
+ out_sorted,
+ add,
+ )
+ return out
+
+
+def _seg_wgrad(
+ P: torch.Tensor,
+ Q: torch.Tensor,
+ out: torch.Tensor,
+ batch: MultiLoraBatch,
+ scales: Optional[torch.Tensor],
+ p_sorted: bool,
+ q_sorted: bool,
+) -> torch.Tensor:
+ with _eager_guard(P.device):
+ _seg_wgrad_op(P, Q, out, scales, batch.sorted_idx, batch.seg_start, p_sorted, q_sorted)
+ return out
+
+
+def _device_guard(device: torch.device):
+ if device.type == "cuda":
+ return torch.cuda.device(device)
+ if device.type == "xpu":
+ return torch.xpu.device(device)
+ return contextlib.nullcontext()
+
+
+def _shrink(
+ X,
+ A,
+ batch,
+ H = None,
+):
+ if H is None:
+ H = torch.empty(X.shape[0], A.shape[1], dtype = X.dtype, device = X.device)
+ return _seg_mm(
+ X,
+ A,
+ (A.stride(0), A.stride(2), A.stride(1)),
+ A.shape[1],
+ H,
+ batch,
+ None,
+ False,
+ True,
+ False,
+ )
+
+
+def _expand_add(H, B, scales, Y, batch):
+ return _seg_mm(
+ H,
+ B,
+ (B.stride(0), B.stride(2), B.stride(1)),
+ B.shape[1],
+ Y,
+ batch,
+ scales,
+ True,
+ False,
+ True,
+ )
+
+
+class MultiLoRA_W(torch.autograd.Function):
+ """Y = X @ W.T + per-token-adapter LoRA, fused forward and backward over sorted adapter segments."""
+
+ @staticmethod
+ @torch_amp_custom_fwd
+ def forward(ctx, X, W, W_quant, A, B, scales, sorted_idx, seg_start):
+ batch = MultiLoraBatch(sorted_idx, seg_start, A.shape[0])
+ shape = X.shape
+ X = X.reshape(-1, shape[-1])
+ if not X.is_contiguous():
+ X = X.contiguous()
+ dtype = X.dtype
+ A_dtype, B_dtype = A.dtype, B.dtype
+ A, B = A.to(dtype), B.to(dtype)
+ Y = matmul_lora(X, W, W_quant, None, None, None)
+ if not Y.is_contiguous():
+ Y = Y.contiguous()
+ H = _shrink(X, A, batch)
+ _expand_add(H, B, scales, Y, batch)
+ ctx.custom_saved_tensors = (W, W_quant)
+ ctx.save_for_backward(X, H, A, B, scales, sorted_idx, seg_start)
+ ctx.shape = shape
+ ctx.ab_dtypes = (A_dtype, B_dtype)
+ return Y.view(*shape[:-1], Y.shape[-1])
+
+ @staticmethod
+ @torch_amp_custom_bwd
+ def backward(ctx, dY):
+ W, W_quant = ctx.custom_saved_tensors
+ X, H, A, B, scales, sorted_idx, seg_start = ctx.saved_tensors
+ batch = MultiLoraBatch(sorted_idx, seg_start, A.shape[0])
+ dY = dY.reshape(-1, dY.shape[-1])
+ if not dY.is_contiguous():
+ dY = dY.contiguous()
+ dtype = X.dtype
+ if dY.dtype != dtype:
+ dY = dY.to(dtype)
+ U, R, _ = A.shape
+ dH = torch.empty(X.shape[0], R, dtype = dtype, device = X.device)
+ _seg_mm(
+ dY, B, (B.stride(0), B.stride(1), B.stride(2)), R, dH, batch, scales, False, True, False
+ )
+ dA = torch.empty(A.shape, dtype = torch.float32, device = X.device)
+ dB = torch.empty(B.shape, dtype = torch.float32, device = X.device)
+ _seg_wgrad(dH, X, dA, batch, None, True, False)
+ _seg_wgrad(dY, H, dB, batch, scales, False, True)
+ W = fast_dequantize(W.t(), W_quant, dtype = dtype).to(dtype)
+ dX = dY @ W.t()
+ del W
+ _seg_mm(
+ dH,
+ A,
+ (A.stride(0), A.stride(1), A.stride(2)),
+ A.shape[2],
+ dX,
+ batch,
+ None,
+ True,
+ False,
+ True,
+ )
+ A_dtype, B_dtype = ctx.ab_dtypes
+ return dX.view(ctx.shape), None, None, dA.to(A_dtype), dB.to(B_dtype), None, None, None
+
+
+def multi_lora_delta(X, A, B, scales, batch: MultiLoraBatch):
+ """Reference LoRA delta in plain PyTorch: every adapter on every token, masked; no host sync."""
+ shape = X.shape
+ X = X.reshape(-1, shape[-1])
+ U = A.shape[0]
+ ids = batch.token_ids
+ if ids is None:
+ ids = torch.full((X.shape[0],), -1, dtype = torch.int64, device = X.device)
+ seg = batch.seg_start.long()
+ pos = torch.arange(X.shape[0], device = X.device)
+ ids = ids.scatter(0, batch.sorted_idx.long(), torch.searchsorted(seg[1:], pos, right = True))
+ ids = torch.where(ids >= U, torch.full_like(ids, -1), ids)
+ # torch.where, not a 0/1 multiply (0 * inf = nan); X is masked too so dH @ A_u cannot leak into dX.
+ scales = scales.to(X.dtype)
+ out = X.new_zeros(X.shape[0], B.shape[1])
+ for u in range(U):
+ own = (ids == u).unsqueeze(1)
+ H = torch.where(own, torch.where(own, X, 0) @ A[u].to(X.dtype).t(), 0)
+ out = torch.where(own, (H @ B[u].to(X.dtype).t()) * scales[u], out)
+ return out.view(*shape[:-1], out.shape[-1])
+
+
+def multi_lora_linear(X, W, W_quant, bias, A, B, scales, batch: Optional[MultiLoraBatch]):
+ """``F.linear(X, W, bias)`` plus each token's adapter delta. ``W`` may be a 4-bit / quantized weight."""
+ if batch is None or X.shape[:-1].numel() != batch.num_tokens:
+ raise ValueError(
+ "Call set_multi_lora_batch(model, ...) with this batch's adapter ids first."
+ )
+ if _use_triton(X):
+ Y = MultiLoRA_W.apply(X, W, W_quant, A, B, scales, batch.sorted_idx, batch.seg_start)
+ else:
+ Wd = fast_dequantize(W, W_quant, dtype = X.dtype) if W_quant is not None else W.to(X.dtype)
+ Y = F.linear(X, Wd) + multi_lora_delta(X, A, B, scales, batch)
+ if bias is not None:
+ Y = Y + bias.to(Y.dtype)
+ return Y
+
+
+class MultiLoraLinear(nn.Module):
+ """Frozen base linear with ``num_adapters`` LoRA adapters, separate (A, B) params each (PEFT init).
+
+ Separate params keep optimizer state per adapter, so an absent adapter's AdamW state is untouched.
+ """
+
+ def __init__(
+ self,
+ base: nn.Module,
+ num_adapters: int,
+ r: int | Iterable[int] = 16,
+ lora_alpha: float | Iterable[float] = 16,
+ use_rslora: bool = False,
+ dtype: torch.dtype = torch.float32,
+ ):
+ super().__init__()
+ self.base_layer = base
+ for p in base.parameters():
+ p.requires_grad_(False)
+ ranks = [int(r)] * num_adapters if isinstance(r, int) else [int(x) for x in r]
+ alphas = (
+ [float(lora_alpha)] * num_adapters
+ if isinstance(lora_alpha, (int, float))
+ else [float(x) for x in lora_alpha]
+ )
+ if len(ranks) != num_adapters or len(alphas) != num_adapters:
+ raise ValueError("Need one rank and one alpha per adapter.")
+ self.ranks = ranks
+ out_features, in_features = base.out_features, base.in_features
+ device = base.weight.device
+ kw = dict(dtype = dtype, device = device)
+ self.lora_A = nn.ParameterList(
+ [nn.Parameter(torch.zeros(k, in_features, **kw)) for k in ranks]
+ )
+ self.lora_B = nn.ParameterList(
+ [nn.Parameter(torch.zeros(out_features, k, **kw)) for k in ranks]
+ )
+ scales = [a / (math.sqrt(k) if use_rslora else k) for a, k in zip(alphas, ranks)]
+ self.register_buffer("scales", torch.tensor(scales, dtype = torch.float32, device = device))
+ self.reset_parameters()
+ # Not a buffer: DDP broadcasts buffers from rank 0, giving every rank rank 0's routing.
+ self.batch: Optional[MultiLoraBatch] = None
+ self.seen: Optional[torch.Tensor] = None
+ self.trained: Optional[torch.Tensor] = None
+
+ @torch.no_grad()
+ def reset_parameters(self):
+ for A, B in zip(self.lora_A, self.lora_B):
+ nn.init.kaiming_uniform_(A, a = math.sqrt(5))
+ B.zero_()
+
+ @property
+ def num_adapters(self) -> int:
+ return len(self.lora_A)
+
+ def stacked(self) -> tuple[torch.Tensor, torch.Tensor]:
+ """(U, R, in) and (U, out, R), zero padded to the largest rank."""
+ R = max(self.ranks)
+ A = torch.stack([F.pad(a, (0, 0, 0, R - a.shape[0])) for a in self.lora_A])
+ B = torch.stack([F.pad(b, (0, R - b.shape[1])) for b in self.lora_B])
+ return A, B
+
+ def forward(self, x):
+ W = self.base_layer.weight
+ A, B = self.stacked()
+ return multi_lora_linear(
+ x,
+ W,
+ _base_quant_state(self.base_layer, W),
+ getattr(self.base_layer, "bias", None),
+ A,
+ B,
+ self.scales,
+ self.batch,
+ )
+
+
+def inject_multi_lora(
+ model: nn.Module,
+ target_modules: str | Iterable[str],
+ num_adapters: int,
+ r: int | Iterable[int] = 16,
+ lora_alpha: float | Iterable[float] = 16,
+ use_rslora: bool = False,
+) -> list[str]:
+ """Freeze ``model`` and wrap every linear layer named, or dotted-suffixed by, a target, as PEFT does."""
+ targets = (target_modules,) if isinstance(target_modules, str) else tuple(target_modules)
+ found = [
+ (name, module)
+ for name, module in model.named_modules()
+ if name
+ and any(name == t or name.endswith("." + t) for t in targets)
+ and hasattr(module, "in_features")
+ and hasattr(module, "weight")
+ ]
+ if not found:
+ raise ValueError(f"No linear layers named {targets} found.")
+ for p in model.parameters():
+ p.requires_grad_(False)
+ for name, module in found:
+ parent_name, _, child = name.rpartition(".")
+ parent = model.get_submodule(parent_name) if parent_name else model
+ setattr(parent, child, MultiLoraLinear(module, num_adapters, r, lora_alpha, use_rslora))
+ return [name for name, _ in found]
+
+
+def _layers(model: nn.Module) -> list[tuple[str, MultiLoraLinear]]:
+ return [(n, m) for n, m in model.named_modules() if isinstance(m, MultiLoraLinear)]
+
+
+def set_multi_lora_batch(
+ model: nn.Module,
+ adapter_ids: torch.Tensor,
+ seq_len: Optional[int] = None,
+) -> MultiLoraBatch:
+ """Route this batch's tokens to their adapters (one id per token, or one per row with ``seq_len``)."""
+ layers = _layers(model)
+ if not layers:
+ raise ValueError("The model has no multi-LoRA layers.")
+ counts = {layer.num_adapters for _, layer in layers}
+ if len(counts) > 1:
+ raise ValueError(
+ f"Every multi-LoRA layer must have the same number of adapters, got {sorted(counts)}."
+ )
+ # One routing table per device: a model split over GPUs keeps each layer's indices local.
+ by_device: dict[torch.device, MultiLoraBatch] = {}
+ for _, layer in layers:
+ device = layer.lora_A[0].device
+ if device not in by_device:
+ by_device[device] = MultiLoraBatch.from_adapter_ids(
+ adapter_ids.to(device), layer.num_adapters, seq_len
+ )
+ layer.batch = by_device[device]
+ seg = layer.batch.seg_start
+ present = (seg[1:] - seg[:-1]) > 0
+ layer.seen = present if layer.seen is None else layer.seen | present
+ return next(iter(by_device.values()))
+
+
+def _distributed() -> bool:
+ return torch.distributed.is_available() and torch.distributed.is_initialized()
+
+
+def drop_absent_adapter_grads_(model: nn.Module, process_group = None) -> list[int]:
+ """Set grads to None for adapters with no valid tokens since the last call on any rank; call before ``step()``."""
+ layers = _layers(model)
+ first = layers[0][1] if layers else None
+ present = (
+ None if first is None else (first.trained if first.trained is not None else first.seen)
+ )
+ if present is None:
+ return []
+ present = present.to(torch.int32)
+ if _distributed():
+ torch.distributed.all_reduce(present, group = process_group)
+ absent = [u for u, n in enumerate(present.tolist()) if n == 0]
+ for _, layer in layers:
+ layer.seen = layer.trained = None
+ for u in absent:
+ layer.lora_A[u].grad = None
+ layer.lora_B[u].grad = None
+ return absent
+
+
+def _label_adapter_ids(ids: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
+ # A shifted label belongs to its own token's adapter: (B, T) ids for packed rows, (B,) per row.
+ ids = ids.to(labels.device).long()
+ return ids[:, 1:] if ids.dim() == 2 else ids[:, None].expand(-1, labels.shape[1] - 1)
+
+
+def adapter_token_counts(
+ labels: torch.Tensor,
+ row_adapter_ids: torch.Tensor,
+ num_adapters: int,
+ ignore_index: int = -100,
+) -> torch.Tensor:
+ """Valid (shifted) label tokens per adapter in one microbatch; ids of -1 count for none."""
+ valid = (labels[:, 1:] != ignore_index).float()
+ ids = _label_adapter_ids(row_adapter_ids, labels)
+ keep = (ids >= 0).to(valid.dtype)
+ return torch.zeros(num_adapters, device = labels.device).index_add(
+ 0, ids.clamp_min(0).reshape(-1), (valid * keep).reshape(-1)
+ )
+
+
+def per_adapter_loss(
+ logits: torch.Tensor,
+ labels: torch.Tensor,
+ row_adapter_ids: torch.Tensor,
+ num_adapters: int,
+ ignore_index: int = -100,
+ process_group = None,
+ model: Optional[nn.Module] = None,
+ num_items_in_batch: Optional[torch.Tensor] = None,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Causal LM loss averaged within each adapter, summed over adapters.
+
+ ``row_adapter_ids``: (B,) or per token (B, T). Pass ``model`` for ``drop_absent_adapter_grads_``, and under
+ gradient accumulation ``num_items_in_batch`` = per-adapter ``adapter_token_counts`` summed over the window.
+ Returns (total, this rank's per-adapter losses).
+ """
+ shift_logits = logits[:, :-1].float()
+ shift_labels = labels[:, 1:]
+ token_loss = F.cross_entropy(
+ shift_logits.reshape(-1, shift_logits.shape[-1]),
+ shift_labels.reshape(-1),
+ ignore_index = ignore_index,
+ reduction = "none",
+ ).view(shift_labels.shape)
+ valid = (shift_labels != ignore_index).float()
+ ids = _label_adapter_ids(row_adapter_ids, labels)
+ # Tokens with no adapter add zero to slot 0 instead of being masked out: no host sync under compile.
+ keep = (ids >= 0).to(token_loss.dtype)
+ ids = ids.clamp_min(0).reshape(-1)
+ sums = torch.zeros(num_adapters, device = logits.device).index_add(
+ 0, ids, (token_loss * keep).reshape(-1)
+ )
+ counts = torch.zeros(num_adapters, device = logits.device).index_add(
+ 0, ids, (valid * keep).reshape(-1)
+ )
+ denom = counts if num_items_in_batch is None else num_items_in_batch.to(counts)
+ losses = sums / denom.clamp_min(1)
+ if model is not None:
+ # Adapters with valid label tokens: routed rows whose labels are all ignored do not train.
+ trained = counts > 0
+ for _, layer in _layers(model):
+ mark = trained.to(layer.lora_A[0].device)
+ layer.trained = mark if layer.trained is None else layer.trained | mark
+ if not _distributed():
+ return losses.sum(), losses.detach()
+ # Undo DDP / FSDP's rank average so each adapter's gradient is its mean over the global batch.
+ total = denom.detach().clone()
+ torch.distributed.all_reduce(total, group = process_group)
+ world = torch.distributed.get_world_size(process_group)
+ return (sums / total.clamp_min(1)).sum() * world, losses.detach()
+
+
+def _adapter_grads(model: nn.Module) -> list[list[torch.Tensor]]:
+ layers = _layers(model)
+ grads = [[] for _ in range(layers[0][1].num_adapters)] if layers else []
+ for _, layer in layers:
+ for u in range(layer.num_adapters):
+ for p in (layer.lora_A[u], layer.lora_B[u]):
+ if p.grad is not None:
+ grads[u].append(p.grad)
+ return grads
+
+
+def _local(t: torch.Tensor) -> torch.Tensor:
+ # FSDP2 parameters and grads are DTensors: work on this rank's shard.
+ return t.to_local() if hasattr(t, "to_local") else t
+
+
+def _grad_sq(model: nn.Module, process_group = None) -> torch.Tensor:
+ layers = _layers(model)
+ if not layers:
+ raise ValueError("The model has no multi-LoRA layers.")
+ device = _local(layers[0][1].lora_A[0]).device
+ out = torch.zeros(layers[0][1].num_adapters, device = device)
+ sharded = False
+ for u, gs in enumerate(_adapter_grads(model)):
+ for g in gs:
+ sharded = sharded or hasattr(g, "to_local")
+ out[u] += _local(g).float().pow(2).sum().to(device)
+ if sharded and _distributed():
+ torch.distributed.all_reduce(out, group = process_group)
+ return out
+
+
+def per_adapter_grad_norm(model: nn.Module, process_group = None) -> torch.Tensor:
+ """(U,) gradient L2 norm of each adapter over every multi-LoRA layer (0 for an adapter without grads)."""
+ return _grad_sq(model, process_group).sqrt()
+
+
+def clip_grad_norm_per_adapter_(
+ model: nn.Module,
+ max_norm: float,
+ eps: float = 1e-6,
+ process_group = None,
+) -> torch.Tensor:
+ """Clip each adapter's gradient to ``max_norm`` on its own, so one adapter never rescales another."""
+ norms = per_adapter_grad_norm(model, process_group)
+ coef = (max_norm / (norms + eps)).clamp(max = 1.0)
+ for u, gs in enumerate(_adapter_grads(model)):
+ for g in gs:
+ local = _local(g)
+ local.mul_(coef[u].to(device = local.device, dtype = local.dtype))
+ return norms
+
+
+def _full(p: torch.Tensor) -> torch.Tensor:
+ return p.full_tensor() if hasattr(p, "full_tensor") else p
+
+
+def adapter_state_dict(
+ model: nn.Module,
+ adapter: int,
+ prefix: str = "base_model.model.",
+) -> dict:
+ """Adapter ``adapter`` as a PEFT LoRA state dict (``<name>.lora_A.weight`` / ``lora_B.weight``)."""
+ out = {}
+ for name, layer in _layers(model):
+ out[f"{prefix}{name}.lora_A.weight"] = _full(layer.lora_A[adapter]).detach().clone()
+ out[f"{prefix}{name}.lora_B.weight"] = _full(layer.lora_B[adapter]).detach().clone()
+ return out