deepinfer-sm86 0.1.0__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 (36) hide show
  1. deepinfer_sm86-0.1.0/LICENSE +201 -0
  2. deepinfer_sm86-0.1.0/NOTICE +17 -0
  3. deepinfer_sm86-0.1.0/PKG-INFO +117 -0
  4. deepinfer_sm86-0.1.0/README.md +85 -0
  5. deepinfer_sm86-0.1.0/pyproject.toml +47 -0
  6. deepinfer_sm86-0.1.0/setup.cfg +4 -0
  7. deepinfer_sm86-0.1.0/src/deepinfer/__init__.py +68 -0
  8. deepinfer_sm86-0.1.0/src/deepinfer/attrdict.py +118 -0
  9. deepinfer_sm86-0.1.0/src/deepinfer/engine/__init__.py +35 -0
  10. deepinfer_sm86-0.1.0/src/deepinfer/engine/kv_cache.py +929 -0
  11. deepinfer_sm86-0.1.0/src/deepinfer/engine/memory_budget.py +163 -0
  12. deepinfer_sm86-0.1.0/src/deepinfer/engine/metrics.py +169 -0
  13. deepinfer_sm86-0.1.0/src/deepinfer/environ.py +235 -0
  14. deepinfer_sm86-0.1.0/src/deepinfer/logger.py +189 -0
  15. deepinfer_sm86-0.1.0/src/deepinfer/moe/__init__.py +1 -0
  16. deepinfer_sm86-0.1.0/src/deepinfer/moe/cpu_avx2.py +229 -0
  17. deepinfer_sm86-0.1.0/src/deepinfer/moe/cpu_avx2_gemv.cpp +260 -0
  18. deepinfer_sm86-0.1.0/src/deepinfer/moe/cpu_avx2_packed.cpp +143 -0
  19. deepinfer_sm86-0.1.0/src/deepinfer/moe/deepseek_v2_runtime.py +2481 -0
  20. deepinfer_sm86-0.1.0/src/deepinfer/moe/fused_moe.py +366 -0
  21. deepinfer_sm86-0.1.0/src/deepinfer/moe/gguf_index.py +436 -0
  22. deepinfer_sm86-0.1.0/src/deepinfer/moe/gpu_quant.py +379 -0
  23. deepinfer_sm86-0.1.0/src/deepinfer/moe/grouped_moe.py +328 -0
  24. deepinfer_sm86-0.1.0/src/deepinfer/moe/layout.py +42 -0
  25. deepinfer_sm86-0.1.0/src/deepinfer/moe/paged_adapter.py +374 -0
  26. deepinfer_sm86-0.1.0/src/deepinfer/moe/paged_mla_kernel.py +572 -0
  27. deepinfer_sm86-0.1.0/src/deepinfer/moe/paged_mla_quant.py +295 -0
  28. deepinfer_sm86-0.1.0/src/deepinfer/moe/ptr_grouped_moe.py +318 -0
  29. deepinfer_sm86-0.1.0/src/deepinfer/py.typed +0 -0
  30. deepinfer_sm86-0.1.0/src/deepinfer/scheduler/__init__.py +14 -0
  31. deepinfer_sm86-0.1.0/src/deepinfer/scheduler/paged.py +1323 -0
  32. deepinfer_sm86-0.1.0/src/deepinfer_sm86.egg-info/PKG-INFO +117 -0
  33. deepinfer_sm86-0.1.0/src/deepinfer_sm86.egg-info/SOURCES.txt +34 -0
  34. deepinfer_sm86-0.1.0/src/deepinfer_sm86.egg-info/dependency_links.txt +1 -0
  35. deepinfer_sm86-0.1.0/src/deepinfer_sm86.egg-info/requires.txt +14 -0
  36. deepinfer_sm86-0.1.0/src/deepinfer_sm86.egg-info/top_level.txt +1 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,17 @@
1
+ DeepInfer-SM86
2
+ ==============
3
+
4
+ This repository is an unofficial SM86 backend extension for the DeepInfer
5
+ project. It is not an official DeepInfer release.
6
+
7
+ Portions of the source, model layout, naming and test structure are derived
8
+ from DeepInfer, which is distributed under the Apache License 2.0.
9
+
10
+ Original project:
11
+ https://gitee.com/mirrors/DeepInfer
12
+
13
+ The extension adds SM86-oriented Qwen2/Qwen2.5 W4A16, W3A16, GQA decode,
14
+ static KV-cache and CUDA Graph experiments. It does not claim to be a complete
15
+ DeepInfer engine implementation.
16
+
17
+ All derived code remains under the Apache License 2.0; see LICENSE.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: deepinfer-sm86
3
+ Version: 0.1.0
4
+ Summary: Native streaming DeepSeek-V2-Lite GGUF MoE and paged MLA primitives for memory-constrained CUDA GPUs
5
+ Author: DeepInfer-SM86 contributors
6
+ License-Expression: Apache-2.0
7
+ Keywords: deepseek,moe,gguf,paged-attention,cuda,sm86
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ License-File: NOTICE
19
+ Requires-Dist: torch>=2.5
20
+ Requires-Dist: numpy>=1.24
21
+ Requires-Dist: transformers>=4.49
22
+ Requires-Dist: accelerate>=1.3
23
+ Requires-Dist: gguf>=0.19
24
+ Requires-Dist: typing-extensions>=4.8
25
+ Provides-Extra: cuda
26
+ Requires-Dist: cupy-cuda12x[ctk]<15,>=14.2; extra == "cuda"
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=8; extra == "dev"
29
+ Requires-Dist: build>=1; extra == "dev"
30
+ Requires-Dist: wheel>=0.43; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # deepinfer-sm86
34
+
35
+ Native DeepSeek-V2-Lite GGUF MoE runtime primitives for memory-constrained
36
+ CUDA GPUs.
37
+
38
+ This wheel contains the reusable library layer:
39
+
40
+ - packed GGUF expert index and streaming reader;
41
+ - fused Q4_K/Q5_0/Q8_0 grouped MoE kernels;
42
+ - fused paged MLA (FP16) and native INT8/FP8 E4M3/E5M2 paged MLA;
43
+ - CPU AVX2 packed GEMV/dequant sources, compiled at runtime;
44
+ - paged KV cache, memory budget and metrics primitives;
45
+ - generic paged continuous-batching scheduler.
46
+
47
+ Model weights, tokenizer metadata, benchmark scripts, the Qwen server and the
48
+ repository's application workspace are **not** included in the wheel.
49
+
50
+ ## Install
51
+
52
+ ```bash
53
+ pip install deepinfer-sm86
54
+ # GPU kernels also need CuPy matching the installed CUDA build:
55
+ pip install "deepinfer-sm86[cuda]"
56
+ ```
57
+
58
+ `torch` must be installed with the CUDA build matching the target GPU; it is a
59
+ normal dependency so pip can be pointed at the PyTorch index when needed.
60
+
61
+ ## Direct runtime
62
+
63
+ ```python
64
+ from deepinfer.moe.deepseek_v2_runtime import DeepSeekV2LiteGGUFRuntime
65
+
66
+ runtime = DeepSeekV2LiteGGUFRuntime(
67
+ "DeepSeek-V2-Lite-Chat-Q4_K_M.gguf",
68
+ meta_dir="meta",
69
+ max_cache=512,
70
+ )
71
+ try:
72
+ result = runtime.generate(
73
+ [{"role": "user", "content": "只回答数字:5-2=?"}],
74
+ max_new_tokens=8,
75
+ temperature=0.0,
76
+ )
77
+ print(result.text)
78
+ finally:
79
+ runtime.close()
80
+ ```
81
+
82
+ ## Paged scheduler
83
+
84
+ ```python
85
+ from deepinfer.scheduler import PagedBatchScheduler
86
+
87
+ scheduler = PagedBatchScheduler(
88
+ runtime,
89
+ max_num_seqs=2,
90
+ block_size=16,
91
+ prefill_chunk_tokens=8,
92
+ )
93
+ try:
94
+ request = scheduler.submit(
95
+ [{"role": "user", "content": "只回答数字:2+3=?"}],
96
+ max_new_tokens=8,
97
+ temperature=0.0,
98
+ )
99
+ print(request.future.result(timeout=120).text)
100
+ finally:
101
+ scheduler.stop()
102
+ ```
103
+
104
+ The scheduler is generic; it expects the runtime to expose `model`,
105
+ `tokenizer`, `device`, `max_cache`, `forward_logits` and `_sample`, which the
106
+ DeepSeek runtime does.
107
+
108
+ ## Optional CPU AVX2 cold experts
109
+
110
+ The C++ sources are shipped in the wheel. At runtime, `deepinfer.moe.cpu_avx2`
111
+ builds a small shared library with `g++ -O3 -mavx2 -mfma -fopenmp`; if the
112
+ compiler is unavailable, the runtime falls back to PyTorch CPU dequantization.
113
+ No binary DLL is bundled.
114
+
115
+ ## License
116
+
117
+ Apache-2.0. See `LICENSE` and `NOTICE`.
@@ -0,0 +1,85 @@
1
+ # deepinfer-sm86
2
+
3
+ Native DeepSeek-V2-Lite GGUF MoE runtime primitives for memory-constrained
4
+ CUDA GPUs.
5
+
6
+ This wheel contains the reusable library layer:
7
+
8
+ - packed GGUF expert index and streaming reader;
9
+ - fused Q4_K/Q5_0/Q8_0 grouped MoE kernels;
10
+ - fused paged MLA (FP16) and native INT8/FP8 E4M3/E5M2 paged MLA;
11
+ - CPU AVX2 packed GEMV/dequant sources, compiled at runtime;
12
+ - paged KV cache, memory budget and metrics primitives;
13
+ - generic paged continuous-batching scheduler.
14
+
15
+ Model weights, tokenizer metadata, benchmark scripts, the Qwen server and the
16
+ repository's application workspace are **not** included in the wheel.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install deepinfer-sm86
22
+ # GPU kernels also need CuPy matching the installed CUDA build:
23
+ pip install "deepinfer-sm86[cuda]"
24
+ ```
25
+
26
+ `torch` must be installed with the CUDA build matching the target GPU; it is a
27
+ normal dependency so pip can be pointed at the PyTorch index when needed.
28
+
29
+ ## Direct runtime
30
+
31
+ ```python
32
+ from deepinfer.moe.deepseek_v2_runtime import DeepSeekV2LiteGGUFRuntime
33
+
34
+ runtime = DeepSeekV2LiteGGUFRuntime(
35
+ "DeepSeek-V2-Lite-Chat-Q4_K_M.gguf",
36
+ meta_dir="meta",
37
+ max_cache=512,
38
+ )
39
+ try:
40
+ result = runtime.generate(
41
+ [{"role": "user", "content": "只回答数字:5-2=?"}],
42
+ max_new_tokens=8,
43
+ temperature=0.0,
44
+ )
45
+ print(result.text)
46
+ finally:
47
+ runtime.close()
48
+ ```
49
+
50
+ ## Paged scheduler
51
+
52
+ ```python
53
+ from deepinfer.scheduler import PagedBatchScheduler
54
+
55
+ scheduler = PagedBatchScheduler(
56
+ runtime,
57
+ max_num_seqs=2,
58
+ block_size=16,
59
+ prefill_chunk_tokens=8,
60
+ )
61
+ try:
62
+ request = scheduler.submit(
63
+ [{"role": "user", "content": "只回答数字:2+3=?"}],
64
+ max_new_tokens=8,
65
+ temperature=0.0,
66
+ )
67
+ print(request.future.result(timeout=120).text)
68
+ finally:
69
+ scheduler.stop()
70
+ ```
71
+
72
+ The scheduler is generic; it expects the runtime to expose `model`,
73
+ `tokenizer`, `device`, `max_cache`, `forward_logits` and `_sample`, which the
74
+ DeepSeek runtime does.
75
+
76
+ ## Optional CPU AVX2 cold experts
77
+
78
+ The C++ sources are shipped in the wheel. At runtime, `deepinfer.moe.cpu_avx2`
79
+ builds a small shared library with `g++ -O3 -mavx2 -mfma -fopenmp`; if the
80
+ compiler is unavailable, the runtime falls back to PyTorch CPU dequantization.
81
+ No binary DLL is bundled.
82
+
83
+ ## License
84
+
85
+ Apache-2.0. See `LICENSE` and `NOTICE`.
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "deepinfer-sm86"
7
+ version = "0.1.0"
8
+ description = "Native streaming DeepSeek-V2-Lite GGUF MoE and paged MLA primitives for memory-constrained CUDA GPUs"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE", "NOTICE"]
13
+ authors = [{ name = "DeepInfer-SM86 contributors" }]
14
+ keywords = ["deepseek", "moe", "gguf", "paged-attention", "cuda", "sm86"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
23
+ ]
24
+ dependencies = [
25
+ "torch>=2.5",
26
+ "numpy>=1.24",
27
+ "transformers>=4.49",
28
+ "accelerate>=1.3",
29
+ "gguf>=0.19",
30
+ "typing-extensions>=4.8",
31
+ ]
32
+
33
+ [project.optional-dependencies]
34
+ cuda = ["cupy-cuda12x[ctk]>=14.2,<15"]
35
+ dev = ["pytest>=8", "build>=1", "wheel>=0.43"]
36
+
37
+ [tool.setuptools]
38
+ package-dir = { "" = "src" }
39
+ include-package-data = true
40
+
41
+ [tool.setuptools.packages.find]
42
+ where = ["src"]
43
+ include = ["deepinfer*"]
44
+
45
+ [tool.setuptools.package-data]
46
+ "deepinfer.moe" = ["*.cpp"]
47
+ "deepinfer" = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,68 @@
1
+ # 严禁在本文件内进行任何形式的 import torch 或初始化 device 的行为,会导致子进程的故障
2
+ import os
3
+ import platform
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ from deepinfer.attrdict import AttrDict as AttrDict
7
+ from deepinfer.environ import envs as envs
8
+
9
+
10
+ def _so_platform_tag() -> str:
11
+ """扩展模块(deepinfer._C)的平台目录标签,与构建脚本
12
+ (scripts/*.sh、Makefile)的 `<accelerator>-<arch>` 约定一致(如 `nvidia-x86_64`)。
13
+
14
+ 只用轻量信号(环境变量 / deep_cluster.hardware),严禁在此 import torch。
15
+ """
16
+ accelerator = envs.DEEPINFER_ACCELERATOR
17
+ if not accelerator:
18
+ try:
19
+ from deep_cluster.hardware import accelerator_kind
20
+
21
+ accelerator = accelerator_kind()
22
+ except Exception: # noqa: BLE001
23
+ accelerator = ""
24
+ if accelerator not in ("nvidia", "ascend"):
25
+ accelerator = "nvidia" # 无加速卡 / 探测失败:缺省按 nvidia
26
+ # Native execution targets Linux; the fallback keeps config/model source
27
+ # tests importable on other platforms without changing native behavior.
28
+ machine = os.uname().machine if hasattr(os, "uname") else platform.machine()
29
+ return f"{accelerator}-{machine}"
30
+
31
+
32
+ # 构建产物按平台分目录存放(deepinfer/_so/<tag>/),加入包搜索路径后,import 仍按 canonical
33
+ # soabi 名解析到本平台的那一份;同 arch 的 nvidia / ascend 因此可以共存于同一棵代码树。
34
+ _so_dir = os.path.join(os.path.dirname(__file__), "_so", _so_platform_tag())
35
+ if os.path.isdir(_so_dir):
36
+ __path__.append(_so_dir)
37
+
38
+ __version__ = "0.1.0"
39
+
40
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
41
+ # 导入依赖时可能调用 torch.cuda.is_available,提前初始化 CUDA 后再设置
42
+ # CUDA_VISIBLE_DEVICES 会失效,因此改用 NVML 检测。
43
+ os.environ["PYTORCH_NVML_BASED_CUDA_CHECK"] = "1"
44
+
45
+ # EPLB shuffle symmem
46
+ os.environ["TORCH_SYMM_MEM_ALLOW_OVERLAPPING_DEVICES"] = "1"
47
+
48
+ os.environ["CUDA_SCALE_LAUNCH_QUEUES"] = "4x"
49
+
50
+
51
+ if TYPE_CHECKING:
52
+ from deepinfer.platform import Platform
53
+
54
+ PLATFORM: Platform
55
+
56
+
57
+ def __getattr__(name: str) -> Any:
58
+ """Lazily initialize the platform after visible devices are configured."""
59
+ if name != "PLATFORM":
60
+ raise AttributeError(f"module 'deepinfer' has no attribute {name!r}")
61
+
62
+ # NPU initialization patches torch.cuda and initializes the ACL runtime, so
63
+ # it must happen only after ASCEND_RT_VISIBLE_DEVICES has been configured.
64
+ from deepinfer.platform import get_platform
65
+
66
+ platform = get_platform()
67
+ globals()[name] = platform
68
+ return platform
@@ -0,0 +1,118 @@
1
+ """Attribute-access dictionaries with nested dicts normalized on writes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Mapping
7
+ from typing import Any
8
+
9
+ from typing_extensions import Self # noqa: UP035
10
+
11
+ __all__ = ["AttrDict", "merge"]
12
+
13
+
14
+ def merge(left: Mapping[Any, Any], right: Mapping[Any, Any]) -> dict[Any, Any]:
15
+ """Merge recursively when both values are mappings; otherwise prefer right."""
16
+ result = {}
17
+ left_keys = frozenset(left)
18
+ right_keys = frozenset(right)
19
+ for key in left_keys - right_keys:
20
+ result[key] = left[key]
21
+ for key in right_keys - left_keys:
22
+ result[key] = right[key]
23
+ for key in left_keys & right_keys:
24
+ lv, rv = left[key], right[key]
25
+ if isinstance(lv, Mapping) and isinstance(rv, Mapping):
26
+ result[key] = merge(lv, rv)
27
+ else:
28
+ result[key] = rv
29
+ return result
30
+
31
+
32
+ class AttrDict(dict):
33
+ """Wrap nested dicts on writes, preserving existing AttrDict references.
34
+
35
+ Reads have no side effects. Lists and their elements remain unchanged.
36
+ ``+`` merges recursively; ``|`` performs a shallow dictionary union.
37
+ """
38
+
39
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
40
+ super().__init__(*args, **kwargs)
41
+ for k, v in list(self.items()):
42
+ if isinstance(v, dict) and not isinstance(v, AttrDict):
43
+ dict.__setitem__(self, k, self.__class__(v))
44
+
45
+ def __getattr__(self, name: str) -> Any:
46
+ try:
47
+ return self[name]
48
+ except KeyError:
49
+ raise AttributeError(name) from None
50
+
51
+ def __setattr__(self, name: str, value: Any) -> None:
52
+ self[name] = value
53
+
54
+ def __delattr__(self, name: str) -> None:
55
+ try:
56
+ del self[name]
57
+ except KeyError:
58
+ raise AttributeError(name) from None
59
+
60
+ def __setitem__(self, key: Any, value: Any) -> None:
61
+ dict.__setitem__(self, key, self._wrap(value))
62
+
63
+ def _wrap(self, value: Any) -> Any:
64
+ if isinstance(value, dict) and not isinstance(value, AttrDict):
65
+ return self.__class__(value)
66
+ return value
67
+
68
+ def setdefault(self, key: Any, default: Any = None) -> Any:
69
+ if key not in self:
70
+ self[key] = default
71
+ return self[key]
72
+
73
+ def update(self, *args: Any, **kwargs: Any) -> None:
74
+ other = dict(*args, **kwargs)
75
+ for k, v in other.items():
76
+ self[k] = v
77
+
78
+ def __add__(self, other: Any) -> Self:
79
+ if not isinstance(other, Mapping):
80
+ return NotImplemented
81
+ return self.__class__(merge(self, other))
82
+
83
+ def __radd__(self, other: Any) -> Self:
84
+ if not isinstance(other, Mapping):
85
+ return NotImplemented
86
+ return self.__class__(merge(other, self))
87
+
88
+ def __iadd__(self, other: Any) -> Self:
89
+ if not isinstance(other, Mapping):
90
+ return NotImplemented
91
+ merged = merge(self, other)
92
+ self.clear()
93
+ self.update(merged)
94
+ return self
95
+
96
+ def __or__(self, other: Any) -> Self:
97
+ if not isinstance(other, Mapping):
98
+ return NotImplemented
99
+ result = self.copy()
100
+ result.update(other)
101
+ return result
102
+
103
+ def __ror__(self, other: Any) -> Self:
104
+ if not isinstance(other, Mapping):
105
+ return NotImplemented
106
+ result = self.__class__(other)
107
+ result.update(self)
108
+ return result
109
+
110
+ def __ior__(self, other: Any) -> Self:
111
+ self.update(other)
112
+ return self
113
+
114
+ def __repr__(self) -> str:
115
+ return json.dumps(dict(self), indent=4, default=str)
116
+
117
+ def copy(self) -> Self:
118
+ return self.__class__(dict.copy(self))