Defuser 0.0.31__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.31 → defuser-0.0.32}/Defuser.egg-info/PKG-INFO +1 -1
  2. {defuser-0.0.31 → defuser-0.0.32}/PKG-INFO +1 -1
  3. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/moe_experts_interface.py +3 -2
  4. {defuser-0.0.31 → defuser-0.0.32}/defuser/utils/device.py +50 -24
  5. {defuser-0.0.31 → defuser-0.0.32}/pyproject.toml +1 -1
  6. defuser-0.0.32/tests/test_device_utils.py +157 -0
  7. defuser-0.0.31/tests/test_device_utils.py +0 -43
  8. {defuser-0.0.31 → defuser-0.0.32}/Defuser.egg-info/SOURCES.txt +0 -0
  9. {defuser-0.0.31 → defuser-0.0.32}/Defuser.egg-info/dependency_links.txt +0 -0
  10. {defuser-0.0.31 → defuser-0.0.32}/Defuser.egg-info/requires.txt +0 -0
  11. {defuser-0.0.31 → defuser-0.0.32}/Defuser.egg-info/top_level.txt +0 -0
  12. {defuser-0.0.31 → defuser-0.0.32}/LICENSE +0 -0
  13. {defuser-0.0.31 → defuser-0.0.32}/README.md +0 -0
  14. {defuser-0.0.31 → defuser-0.0.32}/defuser/__init__.py +0 -0
  15. {defuser-0.0.31 → defuser-0.0.32}/defuser/checkpoint_ops.py +0 -0
  16. {defuser-0.0.31 → defuser-0.0.32}/defuser/defuser.py +0 -0
  17. {defuser-0.0.31 → defuser-0.0.32}/defuser/model_registry.py +0 -0
  18. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/__init__.py +0 -0
  19. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/glm4v.py +0 -0
  20. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/model_patches.py +0 -0
  21. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/replace_modules.py +0 -0
  22. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/runtime_defusion.py +0 -0
  23. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/unfused_moe/__init__.py +0 -0
  24. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/unfused_moe/common.py +0 -0
  25. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/unfused_moe/glm4_moe.py +0 -0
  26. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/unfused_moe/glm4_moe_lite.py +0 -0
  27. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/unfused_moe/mixtral.py +0 -0
  28. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/unfused_moe/qwen2_moe.py +0 -0
  29. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/unfused_moe/qwen3_moe.py +0 -0
  30. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/unfused_moe/qwen3_next.py +0 -0
  31. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/unfused_moe/qwen3_omni_moe.py +0 -0
  32. {defuser-0.0.31 → defuser-0.0.32}/defuser/modeling/update_module.py +0 -0
  33. {defuser-0.0.31 → defuser-0.0.32}/defuser/utils/__init__.py +0 -0
  34. {defuser-0.0.31 → defuser-0.0.32}/defuser/utils/common.py +0 -0
  35. {defuser-0.0.31 → defuser-0.0.32}/defuser/utils/hf.py +0 -0
  36. {defuser-0.0.31 → defuser-0.0.32}/defuser/utils/model.py +0 -0
  37. {defuser-0.0.31 → defuser-0.0.32}/setup.cfg +0 -0
  38. {defuser-0.0.31 → defuser-0.0.32}/setup.py +0 -0
  39. {defuser-0.0.31 → defuser-0.0.32}/tests/test_candidate_coverage.py +0 -0
  40. {defuser-0.0.31 → defuser-0.0.32}/tests/test_convert_model.py +0 -0
  41. {defuser-0.0.31 → defuser-0.0.32}/tests/test_filter_rules.py +0 -0
  42. {defuser-0.0.31 → defuser-0.0.32}/tests/test_meta_model_defusion.py +0 -0
  43. {defuser-0.0.31 → defuser-0.0.32}/tests/test_moe_experts_interface.py +0 -0
  44. {defuser-0.0.31 → 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.31
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.31
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
@@ -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.
@@ -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.31"
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"
@@ -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
@@ -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