Defuser 0.0.30__tar.gz → 0.0.32__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. {defuser-0.0.30 → defuser-0.0.32}/Defuser.egg-info/PKG-INFO +1 -1
  2. {defuser-0.0.30 → defuser-0.0.32}/PKG-INFO +1 -1
  3. {defuser-0.0.30 → defuser-0.0.32}/defuser/model_registry.py +16 -0
  4. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/moe_experts_interface.py +3 -2
  5. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/unfused_moe/common.py +14 -0
  6. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/unfused_moe/glm4_moe.py +13 -4
  7. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/unfused_moe/glm4_moe_lite.py +10 -2
  8. {defuser-0.0.30 → defuser-0.0.32}/defuser/utils/device.py +50 -24
  9. {defuser-0.0.30 → defuser-0.0.32}/pyproject.toml +1 -1
  10. {defuser-0.0.30 → defuser-0.0.32}/tests/test_convert_model.py +145 -0
  11. defuser-0.0.32/tests/test_device_utils.py +157 -0
  12. {defuser-0.0.30 → defuser-0.0.32}/tests/test_meta_model_defusion.py +51 -0
  13. defuser-0.0.30/tests/test_device_utils.py +0 -43
  14. {defuser-0.0.30 → defuser-0.0.32}/Defuser.egg-info/SOURCES.txt +0 -0
  15. {defuser-0.0.30 → defuser-0.0.32}/Defuser.egg-info/dependency_links.txt +0 -0
  16. {defuser-0.0.30 → defuser-0.0.32}/Defuser.egg-info/requires.txt +0 -0
  17. {defuser-0.0.30 → defuser-0.0.32}/Defuser.egg-info/top_level.txt +0 -0
  18. {defuser-0.0.30 → defuser-0.0.32}/LICENSE +0 -0
  19. {defuser-0.0.30 → defuser-0.0.32}/README.md +0 -0
  20. {defuser-0.0.30 → defuser-0.0.32}/defuser/__init__.py +0 -0
  21. {defuser-0.0.30 → defuser-0.0.32}/defuser/checkpoint_ops.py +0 -0
  22. {defuser-0.0.30 → defuser-0.0.32}/defuser/defuser.py +0 -0
  23. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/__init__.py +0 -0
  24. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/glm4v.py +0 -0
  25. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/model_patches.py +0 -0
  26. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/replace_modules.py +0 -0
  27. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/runtime_defusion.py +0 -0
  28. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/unfused_moe/__init__.py +0 -0
  29. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/unfused_moe/mixtral.py +0 -0
  30. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/unfused_moe/qwen2_moe.py +0 -0
  31. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/unfused_moe/qwen3_moe.py +0 -0
  32. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/unfused_moe/qwen3_next.py +0 -0
  33. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/unfused_moe/qwen3_omni_moe.py +0 -0
  34. {defuser-0.0.30 → defuser-0.0.32}/defuser/modeling/update_module.py +0 -0
  35. {defuser-0.0.30 → defuser-0.0.32}/defuser/utils/__init__.py +0 -0
  36. {defuser-0.0.30 → defuser-0.0.32}/defuser/utils/common.py +0 -0
  37. {defuser-0.0.30 → defuser-0.0.32}/defuser/utils/hf.py +0 -0
  38. {defuser-0.0.30 → defuser-0.0.32}/defuser/utils/model.py +0 -0
  39. {defuser-0.0.30 → defuser-0.0.32}/setup.cfg +0 -0
  40. {defuser-0.0.30 → defuser-0.0.32}/setup.py +0 -0
  41. {defuser-0.0.30 → defuser-0.0.32}/tests/test_candidate_coverage.py +0 -0
  42. {defuser-0.0.30 → defuser-0.0.32}/tests/test_filter_rules.py +0 -0
  43. {defuser-0.0.30 → defuser-0.0.32}/tests/test_moe_experts_interface.py +0 -0
  44. {defuser-0.0.30 → defuser-0.0.32}/tests/test_replace_modules_tracker.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: Defuser
3
- Version: 0.0.30
3
+ Version: 0.0.32
4
4
  Summary: Model defuser helper for HF Transformers.
5
5
  Author-email: ModelCloud <qubitium@modelcloud.ai>
6
6
  License-Expression: Apache-2.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: Defuser
3
- Version: 0.0.30
3
+ Version: 0.0.32
4
4
  Summary: Model defuser helper for HF Transformers.
5
5
  Author-email: ModelCloud <qubitium@modelcloud.ai>
6
6
  License-Expression: Apache-2.0
@@ -286,6 +286,16 @@ MODEL_CONFIG = {
286
286
  "jetmoe": {
287
287
  "min_transformers_version": MIN_SUPPORTED_TRANSFORMERS_VERSION,
288
288
  },
289
+ # Native Transformers MoE backbones whose fused 3-D expert tensors the
290
+ # generic experts pass already splits. Registering them lets
291
+ # ``convert_model()`` report the conversion instead of returning False and
292
+ # leaving routed experts fused.
293
+ "kimi_k25": {
294
+ "min_transformers_version": MIN_SUPPORTED_TRANSFORMERS_VERSION,
295
+ },
296
+ "kimi_linear": {
297
+ "min_transformers_version": MIN_SUPPORTED_TRANSFORMERS_VERSION,
298
+ },
289
299
  "laguna": {
290
300
  "min_transformers_version": MIN_SUPPORTED_TRANSFORMERS_VERSION,
291
301
  },
@@ -313,6 +323,9 @@ MODEL_CONFIG = {
313
323
  "longcat_flash": {
314
324
  "min_transformers_version": MIN_SUPPORTED_TRANSFORMERS_VERSION,
315
325
  },
326
+ "mimo_v2_flash": {
327
+ "min_transformers_version": MIN_SUPPORTED_TRANSFORMERS_VERSION,
328
+ },
316
329
  "minimax": {
317
330
  "min_transformers_version": MIN_SUPPORTED_TRANSFORMERS_VERSION,
318
331
  },
@@ -346,6 +359,9 @@ MODEL_CONFIG = {
346
359
  "solar_open2": {
347
360
  "min_transformers_version": MIN_SUPPORTED_TRANSFORMERS_VERSION,
348
361
  },
362
+ "unlimited_ocr": {
363
+ "min_transformers_version": MIN_SUPPORTED_TRANSFORMERS_VERSION,
364
+ },
349
365
  "zamba2": {
350
366
  "min_transformers_version": MIN_SUPPORTED_TRANSFORMERS_VERSION,
351
367
  },
@@ -33,7 +33,7 @@ from torch import nn
33
33
 
34
34
  from defuser.model_registry import MODEL_CONFIG, PATCH
35
35
  from defuser.utils.common import compile_module_name_filter, matches_module_name_filter
36
- from defuser.utils.device import clear_memory, to_meta
36
+ from defuser.utils.device import clear_memory, model_accelerator_devices, to_meta
37
37
 
38
38
  from defuser import DEBUG_ON
39
39
 
@@ -787,7 +787,8 @@ def prepare_model_for_moe_quantization(
787
787
  # and should use full module replacement instead
788
788
  if unfused_modules:
789
789
  if DEBUG_ON: logger.info(f"[MoE Prep] Unfused {len(unfused_modules)} MOE experts modules")
790
- clear_memory()
790
+ # Only flush devices this model occupies; a CPU/meta model touches no accelerator.
791
+ clear_memory(device_list=model_accelerator_devices(model))
791
792
 
792
793
  # Set config for linear_loop forward only when the upstream model uses
793
794
  # the decorator-based experts interface.
@@ -7,6 +7,20 @@ import torch
7
7
  from torch import nn
8
8
 
9
9
 
10
+ def router_logits_from_output(router_output):
11
+ """Return raw router logits from a router tensor or the Transformers 5.22 tuple.
12
+
13
+ Transformers 5.22 routers return ``(router_logits, topk_weights,
14
+ topk_indices)``. Defuser keeps its own grouped top-k selection, so it only
15
+ needs the raw logits; the router's precomputed top-k is intentionally
16
+ discarded so the routing math stays byte-identical across Transformers
17
+ versions.
18
+ """
19
+ if isinstance(router_output, tuple):
20
+ return router_output[0]
21
+ return router_output
22
+
23
+
10
24
  def run_routed_experts(
11
25
  experts: nn.ModuleList,
12
26
  hidden_states: torch.Tensor,
@@ -6,6 +6,8 @@
6
6
  import torch
7
7
  import torch.nn as nn
8
8
 
9
+ from .common import router_logits_from_output
10
+
9
11
  class LinearGlm4MoeMoE(nn.Module):
10
12
  """
11
13
  A mixed expert module containing shared experts.
@@ -34,9 +36,16 @@ class LinearGlm4MoeMoE(nn.Module):
34
36
  self.routed_scaling_factor = config.routed_scaling_factor
35
37
  self.top_k = config.num_experts_per_tok
36
38
 
37
- def route_tokens_to_experts(self, router_logits: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
38
- """Replicate GLM4's grouped expert selection and top-k weight normalization."""
39
+ def route_tokens_to_experts(self, router_logits) -> tuple[torch.Tensor, torch.Tensor]:
40
+ """Replicate GLM4's grouped expert selection and top-k weight normalization.
41
+
42
+ Accepts either the raw logits tensor or the Transformers 5.22 router
43
+ output ``(router_logits, topk_weights, topk_indices)``. Only the logits
44
+ are used: Defuser re-derives the top-k selection below, so the router's
45
+ precomputed weights and indices would change its routing math.
46
+ """
39
47
  # Keep the expert selection identical to the upstream GLM4 MoE router.
48
+ router_logits = router_logits_from_output(router_logits)
40
49
  router_logits = router_logits.sigmoid()
41
50
  router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
42
51
  group_scores = (
@@ -87,8 +96,8 @@ class LinearGlm4MoeMoE(nn.Module):
87
96
  """Apply routed experts plus the shared expert branch, matching upstream GLM4 MoE."""
88
97
  residuals = hidden_states
89
98
  orig_shape = hidden_states.shape
90
- router_logits = self.gate(hidden_states)
91
- topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
99
+ router_output = self.gate(hidden_states)
100
+ topk_indices, topk_weights = self.route_tokens_to_experts(router_output)
92
101
  hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
93
102
  hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape)
94
103
  hidden_states = hidden_states + self.shared_experts(residuals)
@@ -9,6 +9,8 @@
9
9
  import torch
10
10
  import torch.nn as nn
11
11
 
12
+ from .common import router_logits_from_output
13
+
12
14
  class LinearGlm4MoeLiteMoE(nn.Module):
13
15
  """
14
16
  A mixed expert module containing shared experts.
@@ -65,6 +67,12 @@ class LinearGlm4MoeLiteMoE(nn.Module):
65
67
  return final_hidden_states
66
68
 
67
69
  def route_tokens_to_experts(self, router_logits):
70
+ """Accept raw logits or the Transformers 5.22 ``(logits, weights, indices)`` tuple.
71
+
72
+ Defuser re-derives the grouped top-k selection below, so only the logits
73
+ are used; the router's precomputed top-k would change the routing math.
74
+ """
75
+ router_logits = router_logits_from_output(router_logits)
68
76
  router_logits = router_logits.sigmoid()
69
77
  router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
70
78
  group_scores = (
@@ -92,8 +100,8 @@ class LinearGlm4MoeLiteMoE(nn.Module):
92
100
  def forward(self, hidden_states):
93
101
  residuals = hidden_states
94
102
  orig_shape = hidden_states.shape
95
- router_logits = self.gate(hidden_states)
96
- topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
103
+ router_output = self.gate(hidden_states)
104
+ topk_indices, topk_weights = self.route_tokens_to_experts(router_output)
97
105
  hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
98
106
  hidden_states = self.experts_forward(hidden_states, topk_indices, topk_weights).view(*orig_shape)
99
107
  hidden_states = hidden_states + self.shared_experts(residuals)
@@ -31,11 +31,42 @@ def to_meta(
31
31
  raise TypeError(f"Unsupported type for to_meta: {type(obj)!r}")
32
32
 
33
33
 
34
+ def model_accelerator_devices(module: torch.nn.Module) -> list[torch.device]:
35
+ """Return the distinct non-CPU, non-meta devices holding ``module``'s tensors."""
36
+ devices: list[torch.device] = []
37
+ for tensor in (*module.parameters(), *module.buffers()):
38
+ device = tensor.device
39
+ if device.type in ("cpu", "meta") or device in devices:
40
+ continue
41
+ devices.append(device)
42
+ return devices
43
+
44
+
45
+ def _accelerator_ordinals(device_list, device_type: str, current_device) -> list[int]:
46
+ ordinals: list[int] = []
47
+ for dev in device_list:
48
+ dev = torch.device(dev)
49
+ if dev.type != device_type:
50
+ continue
51
+ index = dev.index if dev.index is not None else current_device()
52
+ if index not in ordinals:
53
+ ordinals.append(index)
54
+ return ordinals
55
+
56
+
34
57
  def clear_memory(
35
58
  tensor: torch.Tensor | list[torch.Tensor] | None = None,
36
59
  device_list: tuple | list | str | torch.device | None = None,
37
60
  ):
38
- """Release Python references and flush accelerator caches after tensor surgery."""
61
+ """Release Python references and flush accelerator caches after tensor surgery.
62
+
63
+ ``device_list=None`` synchronizes every accelerator this process has already
64
+ initialized. An explicit ``device_list`` synchronizes only the listed CUDA/XPU
65
+ devices; a list with no accelerator entries (for example ``[]`` or ``["cpu"]``)
66
+ synchronizes nothing. An accelerator runtime that was never initialized is
67
+ never touched, so cleaning up after CPU or meta work cannot create a device
68
+ context (ModelCloud/GPTQModel#5105).
69
+ """
39
70
  # ------------------------
40
71
  # Clear CPU-side references
41
72
  # ------------------------
@@ -54,37 +85,32 @@ def clear_memory(
54
85
  # -----------------------------------
55
86
  # CUDA-specific clearing
56
87
  # -----------------------------------
57
- if torch.cuda.is_available():
58
- # No device_list → clear all GPUs
59
- if not device_list:
88
+ if torch.cuda.is_available() and torch.cuda.is_initialized():
89
+ if device_list is None:
60
90
  # Fix https://github.com/intel/auto-round/issues/1004
61
91
  torch.cuda.synchronize()
62
92
  torch.cuda.empty_cache()
63
93
  else:
64
- # Parse valid CUDA device IDs
65
- devices = []
66
- for dev in device_list:
67
- dev = str(dev)
68
- if not dev.startswith("cuda"):
69
- continue
70
- # cuda / cuda:0 / cuda:1
71
- if ":" in dev:
72
- devid = int(dev.split(":")[-1])
73
- else:
74
- devid = 0
75
- devices.append(devid)
76
-
77
- for d in devices:
78
- torch.cuda.synchronize(d)
79
-
80
- torch.cuda.empty_cache()
94
+ ordinals = _accelerator_ordinals(device_list, "cuda", torch.cuda.current_device)
95
+ for ordinal in ordinals:
96
+ torch.cuda.synchronize(ordinal)
97
+ if ordinals:
98
+ torch.cuda.empty_cache()
81
99
 
82
100
  # -----------------------------------
83
101
  # XPU-specific clearing
84
102
  # -----------------------------------
85
- if hasattr(torch, "xpu") and torch.xpu.is_available():
86
- torch.xpu.synchronize()
87
- torch.xpu.empty_cache()
103
+ xpu = getattr(torch, "xpu", None)
104
+ if xpu is not None and xpu.is_available() and getattr(xpu, "is_initialized", lambda: True)():
105
+ if device_list is None:
106
+ xpu.synchronize()
107
+ xpu.empty_cache()
108
+ else:
109
+ ordinals = _accelerator_ordinals(device_list, "xpu", xpu.current_device)
110
+ for ordinal in ordinals:
111
+ xpu.synchronize(ordinal)
112
+ if ordinals:
113
+ xpu.empty_cache()
88
114
 
89
115
 
90
116
  def unsupported_meta_device(model):
@@ -9,7 +9,7 @@ build-backend = "setuptools.build_meta"
9
9
 
10
10
  [project]
11
11
  name = "Defuser"
12
- version = "0.0.30"
12
+ version = "0.0.32"
13
13
  description = "Model defuser helper for HF Transformers."
14
14
  readme = "README.md"
15
15
  requires-python = ">=3.9"
@@ -17,6 +17,10 @@ from transformers.models.bailing_hybrid.modeling_bailing_hybrid import (
17
17
  BailingHybridForCausalLM,
18
18
  )
19
19
  from transformers.models.glm4_moe.modeling_glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM, Glm4MoeMoE
20
+ from transformers.models.kimi_linear.configuration_kimi_linear import KimiLinearConfig
21
+ from transformers.models.kimi_linear.modeling_kimi_linear import KimiLinearForCausalLM
22
+ from transformers.models.mimo_v2_flash.configuration_mimo_v2_flash import MiMoV2FlashConfig
23
+ from transformers.models.mimo_v2_flash.modeling_mimo_v2_flash import MiMoV2FlashForCausalLM
20
24
  from transformers.models.glm4_moe_lite.configuration_glm4_moe_lite import Glm4MoeLiteConfig
21
25
  from transformers.models.glm4_moe_lite.modeling_glm4_moe_lite import (
22
26
  Glm4MoeLiteForCausalLM,
@@ -301,6 +305,49 @@ def _tiny_glm4_moe_config():
301
305
  )
302
306
 
303
307
 
308
+ def _tiny_kimi_linear_config():
309
+ return KimiLinearConfig(
310
+ vocab_size=64,
311
+ hidden_size=32,
312
+ intermediate_size=48,
313
+ moe_intermediate_size=16,
314
+ num_hidden_layers=2,
315
+ num_attention_heads=4,
316
+ num_key_value_heads=2,
317
+ head_dim=8,
318
+ num_experts=4,
319
+ num_experts_per_tok=2,
320
+ linear_num_key_heads=2,
321
+ linear_num_value_heads=4,
322
+ linear_key_head_dim=8,
323
+ linear_value_head_dim=8,
324
+ linear_conv_kernel_dim=4,
325
+ pad_token_id=0,
326
+ bos_token_id=1,
327
+ eos_token_id=2,
328
+ )
329
+
330
+
331
+ def _tiny_mimo_v2_flash_config():
332
+ return MiMoV2FlashConfig(
333
+ vocab_size=64,
334
+ hidden_size=32,
335
+ intermediate_size=48,
336
+ moe_intermediate_size=16,
337
+ num_hidden_layers=2,
338
+ num_attention_heads=4,
339
+ num_key_value_heads=2,
340
+ head_dim=8,
341
+ n_routed_experts=4,
342
+ num_experts_per_tok=2,
343
+ layer_types=["full_attention", "sliding_attention"],
344
+ mlp_layer_types=["dense", "sparse"],
345
+ pad_token_id=0,
346
+ bos_token_id=1,
347
+ eos_token_id=2,
348
+ )
349
+
350
+
304
351
  def _tiny_glm4v_config():
305
352
  return Glm4vConfig(
306
353
  text_config={
@@ -1190,6 +1237,104 @@ def test_glm4_moe_lite_defused_forward_matches_fused_math():
1190
1237
  hidden_states,
1191
1238
  )
1192
1239
 
1240
+
1241
+ @pytest.mark.parametrize(
1242
+ ("config_factory", "block_cls"),
1243
+ [
1244
+ (_tiny_glm4_moe_config, LinearGlm4MoeMoE),
1245
+ (lambda: _tiny_moe_config(Glm4MoeLiteConfig), LinearGlm4MoeLiteMoE),
1246
+ ],
1247
+ )
1248
+ def test_glm4_route_tokens_accepts_tuple_and_tensor_equivalently(config_factory, block_cls):
1249
+ """Transformers 5.22 routers return ``(logits, weights, indices)``.
1250
+
1251
+ The replacement block must unwrap the tuple while keeping Defuser's grouped
1252
+ top-k routing math identical to the plain-logits path.
1253
+ """
1254
+
1255
+ config = config_factory()
1256
+ block = block_cls(config).eval()
1257
+ hidden_states = torch.randn(2, 3, config.hidden_size, dtype=torch.float32)
1258
+ with torch.no_grad():
1259
+ router_output = block.gate(hidden_states)
1260
+ logits = router_output[0] if isinstance(router_output, tuple) else router_output
1261
+
1262
+ with torch.no_grad():
1263
+ tuple_indices, tuple_weights = block.route_tokens_to_experts((logits, None, None))
1264
+ tensor_indices, tensor_weights = block.route_tokens_to_experts(logits)
1265
+
1266
+ torch.testing.assert_close(tuple_indices, tensor_indices, rtol=0, atol=0)
1267
+ torch.testing.assert_close(tuple_weights, tensor_weights, rtol=0, atol=0)
1268
+
1269
+
1270
+ @pytest.mark.parametrize(
1271
+ ("model_type", "config_factory", "model_cls"),
1272
+ [
1273
+ ("glm4_moe", _tiny_glm4_moe_config, Glm4MoeForCausalLM),
1274
+ (
1275
+ "glm4_moe_lite",
1276
+ lambda: _tiny_moe_config(Glm4MoeLiteConfig, num_hidden_layers=2),
1277
+ Glm4MoeLiteForCausalLM,
1278
+ ),
1279
+ ],
1280
+ )
1281
+ def test_defused_glm4_model_forward_accepts_router_tuple(model_type, config_factory, model_cls):
1282
+ """The installed Transformers router return shape must not crash a defused model."""
1283
+
1284
+ replace_fused_blocks(model_type)
1285
+ model = model_cls(config_factory()).eval()
1286
+ input_ids = torch.tensor([[1, 2, 3, 4]])
1287
+
1288
+ with torch.no_grad():
1289
+ logits = model(input_ids=input_ids).logits
1290
+
1291
+ assert logits.shape == (1, 4, model.config.vocab_size)
1292
+ assert torch.isfinite(logits).all()
1293
+
1294
+
1295
+ @pytest.mark.parametrize("model_type", ["kimi_k25", "kimi_linear", "mimo_v2_flash", "unlimited_ocr"])
1296
+ def test_native_moe_model_types_are_registered(model_type):
1297
+ """Native Transformers MoE backbones must not fall through the registry.
1298
+
1299
+ Without a registry entry ``convert_model()`` returns False and the routed
1300
+ experts stay fused as 3-D parameters, so downstream quantizers silently
1301
+ leave them in the source dtype.
1302
+ """
1303
+
1304
+ assert model_type in MODEL_CONFIG
1305
+ assert MODEL_CONFIG[model_type]["min_transformers_version"] == MIN_SUPPORTED_TRANSFORMERS_VERSION
1306
+
1307
+
1308
+ @pytest.mark.parametrize(
1309
+ ("model_type", "config_factory", "model_cls"),
1310
+ [
1311
+ ("kimi_linear", _tiny_kimi_linear_config, KimiLinearForCausalLM),
1312
+ ("mimo_v2_flash", _tiny_mimo_v2_flash_config, MiMoV2FlashForCausalLM),
1313
+ ],
1314
+ )
1315
+ def test_native_moe_defusion_preserves_forward(model_type, config_factory, model_cls):
1316
+ """Registering a native MoE type must defuse it without changing the output."""
1317
+
1318
+ model = model_cls(config_factory()).eval()
1319
+ input_ids = torch.tensor([[1, 2, 3, 4]])
1320
+
1321
+ with torch.no_grad():
1322
+ expected = model(input_ids=input_ids, use_cache=False).logits
1323
+
1324
+ assert convert_model(model, cleanup_original=False) is True
1325
+
1326
+ experts = [module for name, module in model.named_modules() if name.endswith(".mlp.experts")]
1327
+ assert experts, f"{model_type}: no routed-expert containers found"
1328
+ assert hasattr(experts[0], "0")
1329
+ assert hasattr(experts[0].get_submodule("0"), "gate_proj")
1330
+ assert not hasattr(experts[0], "gate_up_proj")
1331
+
1332
+ with torch.no_grad():
1333
+ actual = model(input_ids=input_ids, use_cache=False).logits
1334
+
1335
+ torch.testing.assert_close(actual, expected, atol=1e-6, rtol=0)
1336
+
1337
+
1193
1338
  def test_glm4v_checkpoint_mapping_splits_gate_up_proj():
1194
1339
  from defuser.defuser import get_checkpoint_conversion_mapping
1195
1340
 
@@ -0,0 +1,157 @@
1
+ # SPDX-FileCopyrightText: 2026 ModelCloud.ai
2
+ # SPDX-FileCopyrightText: 2026 qubitium@modelcloud.ai
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ # Contact: qubitium@modelcloud.ai, x.com/qubitium
5
+
6
+ import pytest
7
+ import torch
8
+
9
+ from defuser.utils.device import to_meta
10
+
11
+
12
+ def test_to_meta_on_module_moves_parameters_to_meta():
13
+ module = torch.nn.Linear(8, 4)
14
+
15
+ to_meta(module)
16
+
17
+ assert next(module.parameters()).is_meta
18
+
19
+
20
+ def test_to_meta_on_parameter_releases_parameter_storage():
21
+ parameter = torch.nn.Parameter(torch.randn(3, 5))
22
+
23
+ meta_parameter = to_meta(parameter)
24
+
25
+ assert not parameter.is_meta
26
+ assert meta_parameter.is_meta
27
+ assert meta_parameter.requires_grad == parameter.requires_grad
28
+ assert tuple(meta_parameter.shape) == (3, 5)
29
+
30
+
31
+ def test_to_meta_on_tensor_returns_meta_tensor():
32
+ tensor = torch.randn(2, 6)
33
+
34
+ meta_tensor = to_meta(tensor)
35
+
36
+ assert not tensor.is_meta
37
+ assert meta_tensor.is_meta
38
+ assert tuple(meta_tensor.shape) == (2, 6)
39
+
40
+
41
+ def test_to_meta_rejects_unsupported_type():
42
+ with pytest.raises(TypeError, match="Unsupported type for to_meta"):
43
+ to_meta("not-a-tensor")
44
+
45
+
46
+ class _FakeAccelerator:
47
+ """Records synchronize/empty_cache calls instead of touching real hardware."""
48
+
49
+ def __init__(self, *, initialized, current=0):
50
+ self.initialized = initialized
51
+ self.current = current
52
+ self.synced = []
53
+ self.emptied = 0
54
+
55
+ def is_available(self):
56
+ return True
57
+
58
+ def is_initialized(self):
59
+ return self.initialized
60
+
61
+ def current_device(self):
62
+ return self.current
63
+
64
+ def synchronize(self, device=None):
65
+ self.synced.append(self.current if device is None else device)
66
+
67
+ def empty_cache(self):
68
+ self.emptied += 1
69
+
70
+
71
+ @pytest.fixture
72
+ def fake_cuda(monkeypatch):
73
+ def install(**kwargs):
74
+ fake = _FakeAccelerator(**kwargs)
75
+ for name in ("is_available", "is_initialized", "current_device", "synchronize", "empty_cache"):
76
+ monkeypatch.setattr(torch.cuda, name, getattr(fake, name))
77
+ if hasattr(torch, "xpu"):
78
+ monkeypatch.setattr(torch.xpu, "is_available", lambda: False)
79
+ return fake
80
+
81
+ return install
82
+
83
+
84
+ def test_clear_memory_never_initializes_an_unused_accelerator(fake_cuda):
85
+ from defuser.utils.device import clear_memory
86
+
87
+ fake = fake_cuda(initialized=False)
88
+ clear_memory()
89
+ clear_memory(device_list=["cuda:1"])
90
+ assert fake.synced == [] and fake.emptied == 0
91
+
92
+
93
+ @pytest.mark.parametrize("device_list", [[], ["cpu"], "cpu", ["meta"]])
94
+ def test_clear_memory_with_no_accelerator_devices_syncs_nothing(fake_cuda, device_list):
95
+ from defuser.utils.device import clear_memory
96
+
97
+ fake = fake_cuda(initialized=True)
98
+ clear_memory(device_list=device_list)
99
+ assert fake.synced == [] and fake.emptied == 0
100
+
101
+
102
+ def test_clear_memory_syncs_only_listed_cuda_ordinals(fake_cuda):
103
+ from defuser.utils.device import clear_memory
104
+
105
+ fake = fake_cuda(initialized=True, current=0)
106
+ clear_memory(device_list=["cuda:1", torch.device("cuda", 2), "cuda:1", "cpu"])
107
+ assert fake.synced == [1, 2]
108
+ assert fake.emptied == 1
109
+
110
+
111
+ def test_clear_memory_bare_cuda_means_the_current_device(fake_cuda):
112
+ from defuser.utils.device import clear_memory
113
+
114
+ fake = fake_cuda(initialized=True, current=3)
115
+ clear_memory(device_list="cuda")
116
+ assert fake.synced == [3]
117
+
118
+
119
+ def test_clear_memory_default_still_flushes_an_initialized_runtime(fake_cuda):
120
+ from defuser.utils.device import clear_memory
121
+
122
+ fake = fake_cuda(initialized=True, current=0)
123
+ clear_memory()
124
+ assert fake.synced == [0] and fake.emptied == 1
125
+
126
+
127
+ def test_model_accelerator_devices_ignores_cpu_and_meta():
128
+ from defuser.utils.device import model_accelerator_devices
129
+
130
+ model = torch.nn.Sequential(torch.nn.Linear(2, 2), torch.nn.Linear(2, 2, device="meta"))
131
+ model.register_buffer("scale", torch.ones(1))
132
+ assert model_accelerator_devices(model) == []
133
+
134
+
135
+ def test_moe_preparation_on_a_cpu_model_syncs_no_accelerator(fake_cuda, monkeypatch):
136
+ """A CPU/meta conversion must not create or sync any CUDA context (GPTQModel#5105)."""
137
+ from defuser.modeling import moe_experts_interface
138
+
139
+ calls = []
140
+ real_clear_memory = moe_experts_interface.clear_memory
141
+
142
+ def recording_clear_memory(*args, **kwargs):
143
+ calls.append(kwargs.get("device_list", args[1] if len(args) > 1 else None))
144
+ return real_clear_memory(*args, **kwargs)
145
+
146
+ monkeypatch.setattr(moe_experts_interface, "clear_memory", recording_clear_memory)
147
+ monkeypatch.setattr(moe_experts_interface, "_unfuse_experts_weights_inplace", lambda *a, **k: True)
148
+ monkeypatch.setattr(moe_experts_interface, "_model_experts_defuse_specs", lambda model: [])
149
+ fake = fake_cuda(initialized=True)
150
+
151
+ model = torch.nn.Module()
152
+ model.experts = torch.nn.Linear(2, 2)
153
+ unfused = moe_experts_interface.prepare_model_for_moe_quantization(model)
154
+
155
+ assert unfused
156
+ assert calls == [[]]
157
+ assert fake.synced == [] and fake.emptied == 0
@@ -238,6 +238,16 @@ def _build_model_config(case: dict):
238
238
  elif model_type == "lfm2_moe":
239
239
  config.layer_types = ["full_attention", "short_conv"]
240
240
  config.num_dense_layers = 0
241
+ elif model_type == "kimi_k25":
242
+ # The DeepSeek-V3 text backbone starts with dense layers; force every
243
+ # tiny layer onto the routed-expert path.
244
+ config.text_config.first_k_dense_replace = 0
245
+ elif model_type == "kimi_linear":
246
+ config.mlp_layer_types = ["sparse"] * config.num_hidden_layers
247
+ elif model_type == "mimo_v2_flash":
248
+ config.mlp_layer_types = ["dense", "sparse"]
249
+ elif model_type == "unlimited_ocr":
250
+ config.text_config.mlp_layer_types = ["sparse"] * config.text_config.num_hidden_layers
241
251
  elif model_type == "laguna":
242
252
  config.layer_types = ["full_attention"] * config.num_hidden_layers
243
253
  config.mlp_layer_types = ["dense"] + ["sparse"] * (config.num_hidden_layers - 1)
@@ -713,6 +723,27 @@ META_MODEL_CASES = [
713
723
  "validator": "parallel",
714
724
  "min_targets": 4,
715
725
  },
726
+ {
727
+ "model_type": "kimi_k25",
728
+ "mode": "convert",
729
+ "model_module": "transformers.models.kimi_k25.modeling_kimi_k25",
730
+ "model_class": "Kimi_K25ForConditionalGeneration",
731
+ "config_module": "transformers.models.kimi_k25.configuration_kimi_k25",
732
+ "config_class": "Kimi_K25Config",
733
+ "target_class_paths": ("transformers.models.deepseek_v3.modeling_deepseek_v3.DeepseekV3Experts",),
734
+ "validator": "experts",
735
+ "min_targets": 2,
736
+ },
737
+ {
738
+ "model_type": "kimi_linear",
739
+ "mode": "convert",
740
+ "model_module": "transformers.models.kimi_linear.modeling_kimi_linear",
741
+ "model_class": "KimiLinearForCausalLM",
742
+ "config_module": "transformers.models.kimi_linear.configuration_kimi_linear",
743
+ "config_class": "KimiLinearConfig",
744
+ "target_class_paths": ("transformers.models.kimi_linear.modeling_kimi_linear.KimiLinearExperts",),
745
+ "validator": "experts",
746
+ },
716
747
  {
717
748
  "model_type": "laguna",
718
749
  "mode": "convert",
@@ -756,6 +787,16 @@ META_MODEL_CASES = [
756
787
  "validator": "longcat",
757
788
  "min_targets": 2,
758
789
  },
790
+ {
791
+ "model_type": "mimo_v2_flash",
792
+ "mode": "convert",
793
+ "model_module": "transformers.models.mimo_v2_flash.modeling_mimo_v2_flash",
794
+ "model_class": "MiMoV2FlashForCausalLM",
795
+ "config_module": "transformers.models.mimo_v2_flash.configuration_mimo_v2_flash",
796
+ "config_class": "MiMoV2FlashConfig",
797
+ "target_class_paths": ("transformers.models.mimo_v2_flash.modeling_mimo_v2_flash.MiMoV2FlashExperts",),
798
+ "validator": "experts",
799
+ },
759
800
  {
760
801
  "model_type": "minimax",
761
802
  "mode": "convert",
@@ -951,6 +992,16 @@ META_MODEL_CASES = [
951
992
  "validator": "experts",
952
993
  "min_targets": 2,
953
994
  },
995
+ {
996
+ "model_type": "unlimited_ocr",
997
+ "mode": "convert",
998
+ "model_module": "transformers.models.unlimited_ocr.modeling_unlimited_ocr",
999
+ "model_class": "UnlimitedOcrForConditionalGeneration",
1000
+ "config_module": "transformers.models.unlimited_ocr.configuration_unlimited_ocr",
1001
+ "config_class": "UnlimitedOcrConfig",
1002
+ "target_class_paths": ("transformers.models.unlimited_ocr.modeling_unlimited_ocr.UnlimitedOcrTextExperts",),
1003
+ "validator": "experts",
1004
+ },
954
1005
  {
955
1006
  "model_type": "zamba2",
956
1007
  "mode": "convert",
@@ -1,43 +0,0 @@
1
- # SPDX-FileCopyrightText: 2026 ModelCloud.ai
2
- # SPDX-FileCopyrightText: 2026 qubitium@modelcloud.ai
3
- # SPDX-License-Identifier: Apache-2.0
4
- # Contact: qubitium@modelcloud.ai, x.com/qubitium
5
-
6
- import pytest
7
- import torch
8
-
9
- from defuser.utils.device import to_meta
10
-
11
-
12
- def test_to_meta_on_module_moves_parameters_to_meta():
13
- module = torch.nn.Linear(8, 4)
14
-
15
- to_meta(module)
16
-
17
- assert next(module.parameters()).is_meta
18
-
19
-
20
- def test_to_meta_on_parameter_releases_parameter_storage():
21
- parameter = torch.nn.Parameter(torch.randn(3, 5))
22
-
23
- meta_parameter = to_meta(parameter)
24
-
25
- assert not parameter.is_meta
26
- assert meta_parameter.is_meta
27
- assert meta_parameter.requires_grad == parameter.requires_grad
28
- assert tuple(meta_parameter.shape) == (3, 5)
29
-
30
-
31
- def test_to_meta_on_tensor_returns_meta_tensor():
32
- tensor = torch.randn(2, 6)
33
-
34
- meta_tensor = to_meta(tensor)
35
-
36
- assert not tensor.is_meta
37
- assert meta_tensor.is_meta
38
- assert tuple(meta_tensor.shape) == (2, 6)
39
-
40
-
41
- def test_to_meta_rejects_unsupported_type():
42
- with pytest.raises(TypeError, match="Unsupported type for to_meta"):
43
- to_meta("not-a-tensor")
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes