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.

Studio: batch MoE fine-tuning jobs with per-job expert LoRA (#15809)

Daniel Han2a9f230a2404
diff --git a/studio/backend/core/training/multi_lora_trainer.py b/studio/backend/core/training/multi_lora_trainer.py
index 3ea35eca47e..f1fe973f081 100644
--- a/studio/backend/core/training/multi_lora_trainer.py
+++ b/studio/backend/core/training/multi_lora_trainer.py
@@ -192,6 +192,57 @@ def _is_moe(model) -> bool:
return False
+# Fused-expert families checked batched vs alone; other MoE layouts train alone.
+BATCHED_MOE_MODEL_TYPES = frozenset({"qwen3_moe", "qwen3_5_moe", "qwen3_5_moe_text"})
+
+
+def _moe_refusal(model) -> Optional[str]:
+ if not _is_moe(model):
+ return None
+ config = getattr(model, "config", None)
+ configs = [c for c in (config, getattr(config, "text_config", None)) if c is not None]
+ if not any(getattr(c, "model_type", None) in BATCHED_MOE_MODEL_TYPES for c in configs):
+ return "Batched training does not support this MoE model; train these jobs one at a time."
+ if any(getattr(c, "output_router_logits", False) for c in configs):
+ # The router's load-balancing loss would average every job's tokens together.
+ return "Batched training does not support a router auxiliary loss; train these jobs one at a time."
+ return None
+
+
+def _expert_targets(model, target_modules) -> Optional[list[str]]:
+ """The fused expert parameters the lone job's get_peft_model adds as PEFT target_parameters."""
+ if not _is_moe(model):
+ return None
+ from unsloth.models._utils import get_moe_target_modules, get_moe_target_parameters
+
+ if get_moe_target_modules(model, target_modules):
+ raise RuntimeError(
+ "Batched training does not support per-expert LoRA modules; train these jobs one at a time."
+ )
+ return get_moe_target_parameters(model, target_modules) or None
+
+
+_SSM_CLASS_TAGS = ("mamba", "ssm", "shortconv", "short_conv", "hymba")
+
+
+def _has_ssm_mixer(model) -> bool:
+ """A Mamba / SSM / short-conv mixer; Gated DeltaNet (Qwen3.5 linear attention) is checked batched and passes."""
+ return any(
+ any(tag in type(module).__name__.lower() for tag in _SSM_CLASS_TAGS)
+ for module in model.modules()
+ )
+
+
+def _lone_target_modules(target_modules):
+ """What the lone job's prepare_model_for_training hands get_peft_model as target_modules."""
+ if isinstance(target_modules, str):
+ target_modules = [target_modules]
+ target_modules = list(target_modules or [])
+ if target_modules == ["all-linear"]:
+ return "all-linear"
+ return [m for m in target_modules if m != "all-linear"] or list(_DEFAULT_TARGETS)
+
+
def _resolve_targets(model, target_modules) -> list[str]:
"""Leaf names as PEFT resolves them: an explicit list, the Studio default, or every linear layer
except the output head for ``all-linear``."""
@@ -216,8 +267,23 @@ def _resolve_targets(model, target_modules) -> list[str]:
def _multi_lora_layers(model):
- from unsloth.kernels.multi_lora import MultiLoraLinear
- return [(n, m) for n, m in model.named_modules() if isinstance(m, MultiLoraLinear)]
+ from unsloth.kernels.multi_lora import _layers
+ return _layers(model)
+
+
+def _routed_modules(model):
+ """The modules a forward calls: dense LoRA layers and expert containers (their stacks are not modules)."""
+ from unsloth.kernels import multi_lora
+
+ # Unsloth releases before the expert kernel still batch dense jobs.
+ kinds = tuple(
+ k for k in (multi_lora.MultiLoraLinear, getattr(multi_lora, "MultiLoraExperts", None)) if k
+ )
+ return [(n, m) for n, m in model.named_modules() if isinstance(m, kinds)]
+
+
+# As get_peft_regex's vision_tags: a text forward never reaches these, and alone they stay untrained too.
+_VISION_TAGS = ("vision", "image", "visual", "patch")
def _seed_adapter(model, slot: int, seed: int) -> None:
@@ -227,9 +293,11 @@ def _seed_adapter(model, slot: int, seed: int) -> None:
generator = torch.Generator().manual_seed(int(seed))
with torch.no_grad():
for _, layer in _multi_lora_layers(model):
- A = torch.empty(layer.lora_A[slot].shape, dtype = torch.float32)
+ shape = layer.lora_A[slot].shape
+ # An expert stack (E, r, in) inits each expert as PEFT does its (E*r, in) matrix: fan_in = in.
+ A = torch.empty((math.prod(shape[:-1]), shape[-1]), dtype = torch.float32)
torch.nn.init.kaiming_uniform_(A, a = math.sqrt(5), generator = generator)
- layer.lora_A[slot].copy_(A)
+ layer.lora_A[slot].copy_(A.view(shape))
layer.lora_B[slot].zero_()
@@ -260,7 +328,7 @@ def _check_routed(model, device) -> None:
import torch
from unsloth.kernels.multi_lora import set_multi_lora_batch
- layers = _multi_lora_layers(model)
+ layers = _routed_modules(model)
hits = set()
handles = [
layer.register_forward_hook(lambda m, i, o, name = name: hits.add(name))
@@ -276,9 +344,13 @@ def _check_routed(model, device) -> None:
finally:
for handle in handles:
handle.remove()
- for _, layer in layers:
+ for _, layer in _multi_lora_layers(model):
layer.batch = layer.seen = layer.trained = None
- missed = [name for name, _ in layers if name not in hits]
+ missed = [
+ name
+ for name, _ in layers
+ if name not in hits and not any(tag in name.lower() for tag in _VISION_TAGS)
+ ]
if missed:
raise RuntimeError(
f"Batched training cannot run on this model: its forward skips {len(missed)} adapter "
@@ -705,6 +777,7 @@ def _export(
targets: list,
use_rslora: bool,
path: str = "",
+ target_parameters: Optional[list] = None,
) -> None:
from peft import LoraConfig
from safetensors.torch import save_file
@@ -730,6 +803,7 @@ def _export(
lora_dropout = 0.0,
bias = "none",
target_modules = targets,
+ **({"target_parameters": list(target_parameters)} if target_parameters else {}),
use_rslora = use_rslora,
task_type = "CAUSAL_LM",
base_model_name_or_path = getattr(model.config, "_name_or_path", None),
@@ -878,10 +952,12 @@ def _run(event_queue, stop_queue, config: dict, members: list) -> None:
raise RuntimeError(
"Batched training does not support text-diffusion models; train these jobs one at a time."
)
- if _is_moe(trainer.model):
- # The single-job path trains fused experts through PEFT target_parameters; these layers cannot.
+ moe_refusal = _moe_refusal(trainer.model)
+ if moe_refusal:
+ raise RuntimeError(moe_refusal)
+ if _has_ssm_mixer(trainer.model):
raise RuntimeError(
- "Batched training does not support MoE models; train these jobs one at a time."
+ "Batched training does not support state-space (Mamba-style) models; train these jobs one at a time."
)
if getattr(trainer.model, "peft_config", None):
# A saved LoRA loads as a PeftModel; the multi-LoRA layers would train fresh adapters and drop its weights.
@@ -950,15 +1026,32 @@ def _run(event_queue, stop_queue, config: dict, members: list) -> None:
_send_status(event_queue, f"Configuring {U} LoRA adapters...")
targets = _resolve_targets(model, config.get("target_modules"))
use_rslora = bool(config.get("use_rslora", False))
- injected = inject_multi_lora(
- model,
- targets,
- U,
- r = [int(m.config.get("lora_r", 16)) for m in live],
- lora_alpha = [float(m.config.get("lora_alpha", 16)) for m in live],
- use_rslora = use_rslora,
- )
- targets = sorted({name.rsplit(".", 1)[-1] for name in injected})
+ expert_targets = _expert_targets(model, _lone_target_modules(config.get("target_modules")))
+ try:
+ injected = inject_multi_lora(
+ model,
+ targets,
+ U,
+ r = [int(m.config.get("lora_r", 16)) for m in live],
+ lora_alpha = [float(m.config.get("lora_alpha", 16)) for m in live],
+ use_rslora = use_rslora,
+ )
+ except ValueError as exc:
+ # Expert-only targets (just gate_up_proj): the single job trains no dense layer either.
+ if not expert_targets or "No linear layers named" not in str(exc):
+ raise
+ injected = []
+ targets = sorted({name.rsplit(".", 1)[-1] for name in injected}) if injected else targets
+ if expert_targets:
+ from unsloth.kernels.multi_lora import inject_multi_lora_experts
+ inject_multi_lora_experts(
+ model,
+ expert_targets,
+ U,
+ r = [int(m.config.get("lora_r", 16)) for m in live],
+ lora_alpha = [float(m.config.get("lora_alpha", 16)) for m in live],
+ use_rslora = use_rslora,
+ )
for member in live:
_seed_adapter(model, member.slot, member.config.get("random_seed", 3407))
_enable_training(
@@ -993,7 +1086,7 @@ def _run(event_queue, stop_queue, config: dict, members: list) -> None:
_send(event_queue, "output_dir", member, output_dir = member.output_dir)
def export(member: _Member, path: str = "") -> None:
- _export(model, member, trainer, targets, use_rslora, path)
+ _export(model, member, trainer, targets, use_rslora, path, expert_targets)
def take_messages() -> Optional[bool]:
"""Applies queued member stops; returns the save flag of a whole-batch stop, if one arrived."""
diff --git a/studio/backend/routes/openai_fine_tuning.py b/studio/backend/routes/openai_fine_tuning.py
index 98618bd8fdd..40221237030 100644
--- a/studio/backend/routes/openai_fine_tuning.py
+++ b/studio/backend/routes/openai_fine_tuning.py
@@ -609,6 +609,29 @@ def _multi_lora_available() -> bool:
return _multi_lora
+_multi_lora_experts: Optional[bool] = None
+
+
+def _multi_lora_experts_available() -> bool:
+ """Whether the installed multi-LoRA kernels train fused MoE experts (inject_multi_lora_experts)."""
+ global _multi_lora_experts
+ if _multi_lora_experts is None:
+ try:
+ spec = importlib.util.find_spec("unsloth")
+ roots = list(spec.submodule_search_locations or []) if spec is not None else []
+ except (ImportError, ValueError):
+ roots = []
+ _multi_lora_experts = any(
+ "def inject_multi_lora_experts"
+ in (Path(root) / "kernels" / "multi_lora.py").read_text(
+ encoding = "utf-8", errors = "replace"
+ )
+ for root in roots
+ if (Path(root) / "kernels" / "multi_lora.py").is_file()
+ )
+ return _multi_lora_experts
+
+
def _batchable(request: TrainingStartRequest) -> bool:
"""Text LoRA/QLoRA on local files with nothing the batched trainer does not run; the rest trains alone."""
from core.training.eval_dataset import evaluation_enabled
@@ -655,19 +678,87 @@ def _batch_key(entry: _Queued) -> Optional[tuple]:
_MOE_COUNT_KEYS = ("num_experts", "n_routed_experts", "num_local_experts")
+# multi_lora_trainer.BATCHED_MOE_MODEL_TYPES.
+_BATCHED_MOE_TYPES = frozenset({"qwen3_moe", "qwen3_5_moe", "qwen3_5_moe_text"})
+# Recurrent / conv state is not checked batched; Gated DeltaNet ("linear_attention") is, and is not matched here.
+_SSM_MODEL_TYPES = frozenset(
+ {
+ "mamba",
+ "mamba2",
+ "falcon_mamba",
+ "falcon_h1",
+ "jamba",
+ "zamba",
+ "zamba2",
+ "nemotron_h",
+ "bamba",
+ "granitemoehybrid",
+ "lfm2",
+ "lfm2_moe",
+ "lfm2_vl",
+ "plamo2",
+ "hymba",
+ "mamba_ssm",
+ }
+)
+_SSM_LAYER_TYPES = ("mamba", "ssm", "conv", "mamba2")
+_SSM_KEYS = (
+ "ssm_state_size",
+ "mamba_d_state",
+ "mamba_n_heads",
+ "mamba_d_conv",
+ "state_size",
+ "conv_L_cache",
+)
+
+
+def _configs(config: dict) -> list[dict]:
+ return [c for c in (config, config.get("text_config") or {}) if isinstance(c, dict) and c]
def _moe_config(config: dict) -> bool:
- for cfg in (config, config.get("text_config") or {}):
+ for cfg in _configs(config):
count = next((cfg[k] for k in _MOE_COUNT_KEYS if cfg.get(k) is not None), None)
if count is not None:
return isinstance(count, int) and count > 0
return False
+def _moe_batches(config: dict, request: TrainingStartRequest) -> bool:
+ from utils.transformers_version import get_transformers_tier
+ configs = _configs(config)
+ return (
+ any(c.get("model_type") in _BATCHED_MOE_TYPES for c in configs)
+ and not any(c.get("output_router_logits") for c in configs)
+ and _multi_lora_experts_available()
+ # The worker's transformers: 4.57 holds experts as per-expert Linears, which train alone.
+ and get_transformers_tier(request.model_name, request.hf_token, probe = False) != "457"
+ )
+
+
+def _ssm_config(config: dict) -> bool:
+ for cfg in _configs(config):
+ if cfg.get("model_type") in _SSM_MODEL_TYPES:
+ return True
+ kinds = (
+ cfg.get("layer_types")
+ or cfg.get("layers_block_type")
+ or cfg.get("hybrid_override_pattern")
+ )
+ if isinstance(kinds, str):
+ kinds = [kinds]
+ if isinstance(kinds, (list, tuple)) and any(
+ isinstance(k, str) and any(tag in k.lower() for tag in _SSM_LAYER_TYPES) for k in kinds
+ ):
+ return True
+ if any(cfg.get(k) is not None for k in _SSM_KEYS):
+ return True
+ return False
+
+
async def _trains_alone(request: TrainingStartRequest) -> bool:
"""Outside what the batched trainer runs: text-diffusion models (own denoising objective), saved LoRA
- adapters (continued in place alone) and MoE models (fused experts train via target_parameters alone)."""
+ adapters (continued in place alone), state-space / conv mixers, and MoE layouts it has no expert LoRA for."""
from utils.models.diffusion_lm import diffusion_lm_profile_for_model
from utils.models.model_config import _read_raw_config_json, get_base_model_from_lora_identifier
@@ -687,7 +778,9 @@ async def _trains_alone(request: TrainingStartRequest) -> bool:
config = _read_raw_config_json(request.model_name, request.hf_token)
except Exception:
return True
- return config is None or _moe_config(config)
+ if config is None or _ssm_config(config):
+ return True
+ return _moe_config(config) and not _moe_batches(config, request)
return await asyncio.to_thread(probe)
diff --git a/studio/backend/tests/test_multi_lora_trainer.py b/studio/backend/tests/test_multi_lora_trainer.py
index 37e23775cd7..4ecdde2ff07 100644
--- a/studio/backend/tests/test_multi_lora_trainer.py
+++ b/studio/backend/tests/test_multi_lora_trainer.py
@@ -64,6 +64,54 @@ def _base():
return Qwen3ForCausalLM(config).float()
+def _qwen3_5(moe: bool):
+ """Tiny Qwen3.5 text model: one Gated DeltaNet (linear attention) layer, one full attention layer; ``moe``
+ swaps the MLPs for fused experts plus a shared expert, as in Qwen3.6-35B-A3B."""
+ import transformers
+
+ torch.manual_seed(0)
+ common = dict(
+ vocab_size = 64,
+ hidden_size = 32,
+ num_hidden_layers = 2,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ head_dim = 8,
+ max_position_embeddings = 128,
+ use_cache = False,
+ tie_word_embeddings = False,
+ layer_types = ["linear_attention", "full_attention"],
+ linear_num_key_heads = 2,
+ linear_num_value_heads = 4,
+ linear_key_head_dim = 8,
+ linear_value_head_dim = 8,
+ linear_conv_kernel_dim = 4,
+ )
+ if moe:
+ config = transformers.Qwen3_5MoeTextConfig(
+ **common,
+ num_experts = 4,
+ num_experts_per_tok = 2,
+ moe_intermediate_size = 16,
+ shared_expert_intermediate_size = 16,
+ )
+ return transformers.Qwen3_5MoeForCausalLM(config).float()
+ config = transformers.Qwen3_5TextConfig(**common, intermediate_size = 64)
+ return transformers.Qwen3_5ForCausalLM(config).float()
+
+
+def _kind_targets(kind):
+ # Lone runs train fused experts for the default targets; a bare "all-linear" string reaches no experts there.
+ return {"target_modules": []} if kind == "moe" else {}
+
+
+def _kind_base(kind):
+ if kind == "dense":
+ return _base()
+ pytest.importorskip("transformers", minversion = "5.2")
+ return _qwen3_5(moe = kind == "moe")
+
+
def _texts(n, seed):
g = torch.Generator().manual_seed(seed)
out = []
@@ -131,10 +179,11 @@ def _run(
trainer_attrs = None,
datasets = None,
model_attrs = None,
+ base = None,
wrap_tokenizer = None,
**extra,
):
- base = _base()
+ base = _base() if base is None else base
for name, value in (model_attrs or {}).items():
setattr(base, name, value)
pristine = copy.deepcopy(base)
@@ -534,6 +583,85 @@ def test_batched_member_trains_as_it_would_alone(batched_run, monkeypatch):
torch.testing.assert_close(batched[key], alone[key], atol = 1e-5, rtol = 1e-4)
[email protected]("kind", ["dense", "hybrid", "moe"])
+def test_a_neighbour_never_moves_a_members_training(monkeypatch, tmp_path, kind):
+ """Job B batched beside A, then beside a different A (data, rate, rank, seed): B's losses and adapter match."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ other = dict(MEMBERS[0], rows = 10, lr = 3e-2, r = 2, alpha = 2, seed = 99)
+ runs = []
+ for neighbour in (MEMBERS[0], other):
+ events, _, _ = _run(
+ monkeypatch, [neighbour, MEMBERS[1]], base = _kind_base(kind), **_kind_targets(kind)
+ )
+ mine = _member_events(events, "job_b")
+ losses = [e["loss"] for e in mine if e["type"] == "progress"]
+ runs.append(
+ (losses, load_file(os.path.join(mine[0]["output_dir"], "adapter_model.safetensors")))
+ )
+ (loss_1, adapter_1), (loss_2, adapter_2) = runs
+ assert len(loss_1) == EXPECTED_STEPS["job_b"] + 1
+ assert loss_2 == pytest.approx(loss_1, rel = 1e-5)
+ assert adapter_1.keys() == adapter_2.keys()
+ for key in adapter_1:
+ torch.testing.assert_close(adapter_2[key], adapter_1[key], atol = 1e-6, rtol = 1e-5)
+
+
[email protected]("kind", ["hybrid", "moe"])
+def test_a_hybrid_or_moe_member_trains_as_it_would_alone(monkeypatch, tmp_path, kind):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ batched, _, _ = _run(monkeypatch, MEMBERS[:2], base = _kind_base(kind), **_kind_targets(kind))
+ alone, _, _ = _run(monkeypatch, [MEMBERS[1]], base = _kind_base(kind), **_kind_targets(kind))
+ out = {}
+ for name, events in (("batched", batched), ("alone", alone)):
+ mine = _member_events(events, "job_b")
+ assert mine[-1]["type"] == "complete"
+ out[name] = (
+ [e["loss"] for e in mine if e["type"] == "progress"],
+ load_file(os.path.join(mine[0]["output_dir"], "adapter_model.safetensors")),
+ json.load(open(os.path.join(mine[0]["output_dir"], "adapter_config.json"))),
+ )
+ assert out["batched"][0][1:] == pytest.approx(out["alone"][0][1:], rel = 1e-4)
+ for key, value in out["alone"][1].items():
+ torch.testing.assert_close(out["batched"][1][key], value, atol = 1e-5, rtol = 1e-4)
+ # Every adapter trained, dense and expert alike (injecting experts must not freeze the dense ones).
+ trained = {
+ k: v.abs().max() > 0 for k, v in out["batched"][1].items() if k.endswith("lora_B.weight")
+ }
+ assert trained and all(trained.values()), [k for k, ok in trained.items() if not ok][:3]
+ if kind == "moe":
+ config = out["batched"][2]
+ assert sorted(config["target_parameters"]) == [
+ "mlp.experts.down_proj",
+ "mlp.experts.gate_up_proj",
+ ]
+ experts = [
+ k for k in out["batched"][1] if ".mlp.experts." in k and k.endswith("lora_B.weight")
+ ]
+ assert len(experts) == 4 and all(out["batched"][1][k].abs().max() > 0 for k in experts)
+ else:
+ # Gated DeltaNet projections train exactly when all-linear asks for them, as alone.
+ assert any(".linear_attn.in_proj_qkv." in k for k in out["batched"][1])
+
+
+def test_an_allowlisted_moe_with_a_router_aux_loss_trains_alone(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ pytest.importorskip("transformers", minversion = "5.2")
+ base = _qwen3_5(moe = True)
+ base.config.output_router_logits = True
+ events, _, _ = _run(monkeypatch, MEMBERS[:2], base = base, target_modules = [])
+ assert [e["type"] for e in events if e.get("member_run_id")] == ["error", "error"]
+ assert "auxiliary loss" in events[-1]["error"]
+
+
+def test_a_state_space_model_trains_alone(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ base = _base()
+ base.model.layers[0].mixer = type("MambaMixer", (torch.nn.Module,), {})()
+ events, _, _ = _run(monkeypatch, MEMBERS[:2], base = base)
+ assert [e["type"] for e in events if e.get("member_run_id")] == ["error", "error"]
+ assert "state-space" in events[-1]["error"]
+
+
PACKED = [
dict(
run_id = "job_a",
@@ -835,3 +963,33 @@ def test_packing_is_refused_where_packed_documents_see_each_other(monkeypatch, t
events, _, _ = _run(monkeypatch, PACKED[:2], max_seq_length = 24)
assert seen == []
assert all(_member_events(events, m["run_id"])[-1]["type"] == "complete" for m in PACKED[:2])
+
+
+def test_an_expert_only_moe_target_trains_batched(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ events, _, _ = _run(
+ monkeypatch, MEMBERS[:2], base = _kind_base("moe"), target_modules = ["gate_up_proj"]
+ )
+ mine = _member_events(events, "job_b")
+ assert mine[-1]["type"] == "complete", mine[-1]
+ adapter = load_file(os.path.join(mine[0]["output_dir"], "adapter_model.safetensors"))
+ assert adapter and all(".mlp.experts." in k for k in adapter), sorted(adapter)[:3]
+ assert all(v.abs().max() > 0 for k, v in adapter.items() if k.endswith("lora_B.weight"))
+
+
+def test_routing_check_runs_on_a_kernel_without_expert_support(monkeypatch):
+ import sys
+ import types
+
+ import unsloth.kernels
+
+ multi_lora_trainer = mlt
+ from unsloth.kernels import multi_lora
+
+ model = torch.nn.Sequential(torch.nn.Linear(4, 4))
+ multi_lora.inject_multi_lora(model, ["0"], 2, 2, 2)
+ # An Unsloth release that predates the expert kernel: only the dense layer class exists.
+ old = types.SimpleNamespace(MultiLoraLinear = multi_lora.MultiLoraLinear)
+ monkeypatch.setattr(unsloth.kernels, "multi_lora", old)
+ monkeypatch.setitem(sys.modules, "unsloth.kernels.multi_lora", old)
+ assert [name for name, _ in multi_lora_trainer._routed_modules(model)] == ["0"]
diff --git a/studio/backend/tests/test_openai_fine_tuning.py b/studio/backend/tests/test_openai_fine_tuning.py
index 5b798188299..0f4bfb7bbb5 100644
--- a/studio/backend/tests/test_openai_fine_tuning.py
+++ b/studio/backend/tests/test_openai_fine_tuning.py
@@ -1114,11 +1114,40 @@ def test_listing_pages_through_a_batch_that_is_still_loading(batch_queue):
@pytest.mark.parametrize(
- "model_kind", ["diffusion", "lora_adapter", "moe", "moe_text_config", "dense"]
+ "model_kind",
+ [
+ "diffusion",
+ "lora_adapter",
+ "moe",
+ "moe_text_config",
+ "moe_router_aux_loss",
+ "mamba",
+ "jamba",
+ "lfm2",
+ "ssm_keys",
+ "dense",
+ "hybrid_gated_deltanet",
+ "qwen3_5_moe",
+ "qwen3_moe",
+ "qwen3_moe_on_transformers_4",
+ "qwen3_moe_without_expert_kernels",
+ ],
)
-def test_only_plain_dense_models_batch(batch_queue, monkeypatch, model_kind):
+def test_only_checked_model_kinds_batch(batch_queue, monkeypatch, model_kind):
import utils.models.diffusion_lm as diffusion_lm
import utils.models.model_config as model_config
+ import utils.transformers_version as transformers_version
+
+ monkeypatch.setattr(
+ transformers_version,
+ "get_transformers_tier",
+ lambda *a, **k: "457" if model_kind == "qwen3_moe_on_transformers_4" else "default",
+ )
+ monkeypatch.setattr(
+ openai_fine_tuning,
+ "_multi_lora_experts_available",
+ lambda: model_kind != "qwen3_moe_without_expert_kernels",
+ )
client, calls, _live, gpu, _backend = batch_queue
monkeypatch.setattr(openai_fine_tuning, "_trains_alone", _REAL_TRAINS_ALONE)
@@ -1133,8 +1162,42 @@ def test_only_plain_dense_models_batch(batch_queue, monkeypatch, model_kind):
lambda *a, **k: "unsloth/Qwen3-0.6B" if model_kind == "lora_adapter" else None,
)
configs = {
- "moe": {"model_type": "qwen3_moe", "num_experts": 128},
+ "moe": {"model_type": "deepseek_v3", "n_routed_experts": 256},
"moe_text_config": {"text_config": {"num_local_experts": 8}},
+ "moe_router_aux_loss": {
+ "model_type": "qwen3_5_moe",
+ "text_config": {
+ "model_type": "qwen3_5_moe_text",
+ "num_experts": 256,
+ "output_router_logits": True,
+ },
+ },
+ "mamba": {"model_type": "mamba2", "state_size": 128},
+ "jamba": {
+ "model_type": "jamba",
+ "num_experts": 16,
+ "layers_block_type": ["mamba", "attention"],
+ },
+ "lfm2": {"model_type": "lfm2", "layer_types": ["conv", "full_attention"]},
+ "ssm_keys": {"model_type": "custom_hybrid", "mamba_d_state": 64},
+ "hybrid_gated_deltanet": {
+ "model_type": "qwen3_5",
+ "text_config": {
+ "model_type": "qwen3_5_text",
+ "layer_types": ["linear_attention", "full_attention"],
+ },
+ },
+ "qwen3_5_moe": {
+ "model_type": "qwen3_5_moe",
+ "text_config": {
+ "model_type": "qwen3_5_moe_text",
+ "num_experts": 256,
+ "layer_types": ["linear_attention", "full_attention"],
+ },
+ },
+ "qwen3_moe": {"model_type": "qwen3_moe", "num_experts": 128},
+ "qwen3_moe_on_transformers_4": {"model_type": "qwen3_moe", "num_experts": 128},
+ "qwen3_moe_without_expert_kernels": {"model_type": "qwen3_moe", "num_experts": 128},
}
monkeypatch.setattr(
model_config,
@@ -1150,7 +1213,7 @@ def test_only_plain_dense_models_batch(batch_queue, monkeypatch, model_kind):
await openai_fine_tuning._drain_once()
_run(flow())
- if model_kind == "dense":
+ if model_kind in ("dense", "hybrid_gated_deltanet", "qwen3_5_moe", "qwen3_moe"):
assert len(calls["batch"]) == 1 and calls["start"] == []
else:
assert calls["batch"] == []