aetherflow-ai 0.2.0__py3-none-any.whl
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.
- aetherflow/__init__.py +322 -0
- aetherflow/agent_api.py +234 -0
- aetherflow/backends/__init__.py +69 -0
- aetherflow/backends/base.py +74 -0
- aetherflow/backends/capabilities.py +286 -0
- aetherflow/backends/contracts.py +278 -0
- aetherflow/backends/cuda/__init__.py +16 -0
- aetherflow/backends/cuda/backend.py +1023 -0
- aetherflow/backends/cuda/codegen.py +2874 -0
- aetherflow/backends/cuda/cublas.py +428 -0
- aetherflow/backends/cuda/cudnn.py +305 -0
- aetherflow/backends/cuda/cufft.py +384 -0
- aetherflow/backends/cuda/cusparse.py +381 -0
- aetherflow/backends/cuda/dialect.py +80 -0
- aetherflow/backends/cuda/memory.py +243 -0
- aetherflow/backends/device_attention.py +257 -0
- aetherflow/backends/device_backend.py +1569 -0
- aetherflow/backends/device_conv.py +970 -0
- aetherflow/backends/device_elementwise.py +629 -0
- aetherflow/backends/device_index.py +230 -0
- aetherflow/backends/device_linear.py +1301 -0
- aetherflow/backends/device_loss.py +109 -0
- aetherflow/backends/device_misc.py +249 -0
- aetherflow/backends/device_norm.py +197 -0
- aetherflow/backends/device_plan.py +1062 -0
- aetherflow/backends/device_pool.py +592 -0
- aetherflow/backends/device_reduce.py +512 -0
- aetherflow/backends/device_scan.py +457 -0
- aetherflow/backends/device_shape.py +108 -0
- aetherflow/backends/device_shared.py +1107 -0
- aetherflow/backends/device_sparse.py +373 -0
- aetherflow/backends/discovery.py +286 -0
- aetherflow/backends/hardware.py +784 -0
- aetherflow/backends/hip/__init__.py +15 -0
- aetherflow/backends/hip/backend.py +567 -0
- aetherflow/backends/hip/blas.py +227 -0
- aetherflow/backends/hip/codegen.py +109 -0
- aetherflow/backends/hip/dialect.py +62 -0
- aetherflow/backends/hip/memory.py +418 -0
- aetherflow/backends/hip/rtc.py +126 -0
- aetherflow/backends/hip/runtime.py +2018 -0
- aetherflow/backends/kernel_cache.py +240 -0
- aetherflow/backends/reference_backend.py +76 -0
- aetherflow/backends/registry.py +224 -0
- aetherflow/conformance.py +2791 -0
- aetherflow/deploy.py +259 -0
- aetherflow/dynamic.py +252 -0
- aetherflow/frontend/__init__.py +39 -0
- aetherflow/frontend/compat.py +118 -0
- aetherflow/frontend/eager.py +345 -0
- aetherflow/frontend/module.py +320 -0
- aetherflow/frontend/torch_export.py +2047 -0
- aetherflow/fuzz.py +1093 -0
- aetherflow/gguf.py +693 -0
- aetherflow/ir/__init__.py +144 -0
- aetherflow/ir/control.py +444 -0
- aetherflow/ir/grad.py +240 -0
- aetherflow/ir/grad_rules.py +1814 -0
- aetherflow/ir/graph.py +370 -0
- aetherflow/ir/liveness.py +227 -0
- aetherflow/ir/loop.py +437 -0
- aetherflow/ir/ops.py +6333 -0
- aetherflow/ir/second_order.py +111 -0
- aetherflow/ir/serialize.py +180 -0
- aetherflow/ir/shape_contract.py +146 -0
- aetherflow/ir/types.py +363 -0
- aetherflow/ir/verifier.py +130 -0
- aetherflow/ir/version.py +196 -0
- aetherflow/lower/__init__.py +202 -0
- aetherflow/lower/cstyle.py +354 -0
- aetherflow/lower/elementwise.py +346 -0
- aetherflow/lower/indexing.py +170 -0
- aetherflow/lower/kernel.py +448 -0
- aetherflow/lower/kernels/__init__.py +262 -0
- aetherflow/lower/kernels/attention.py +390 -0
- aetherflow/lower/kernels/common.py +95 -0
- aetherflow/lower/kernels/conv.py +2927 -0
- aetherflow/lower/kernels/elementwise.py +676 -0
- aetherflow/lower/kernels/image.py +97 -0
- aetherflow/lower/kernels/interpolate.py +381 -0
- aetherflow/lower/kernels/misc.py +154 -0
- aetherflow/lower/kernels/norm.py +675 -0
- aetherflow/lower/kernels/pool.py +650 -0
- aetherflow/lower/kernels/reduce.py +891 -0
- aetherflow/lower/kernels/scan.py +939 -0
- aetherflow/lower/kernels/sparse.py +680 -0
- aetherflow/lower/plan.py +884 -0
- aetherflow/lower/translate.py +382 -0
- aetherflow/models/__init__.py +227 -0
- aetherflow/models/cached_attention.py +1133 -0
- aetherflow/models/cnn.py +208 -0
- aetherflow/models/hf_export.py +363 -0
- aetherflow/models/llama.py +875 -0
- aetherflow/models/lm.py +2888 -0
- aetherflow/models/lm_bpe.py +812 -0
- aetherflow/models/lm_text.py +159 -0
- aetherflow/models/lm_tools.py +1048 -0
- aetherflow/models/lm_unigram.py +794 -0
- aetherflow/models/lm_wordpiece.py +429 -0
- aetherflow/models/mamba.py +917 -0
- aetherflow/models/mamba_reference.py +183 -0
- aetherflow/models/mlp.py +84 -0
- aetherflow/models/moe.py +158 -0
- aetherflow/models/quantize.py +775 -0
- aetherflow/models/rnn.py +157 -0
- aetherflow/models/snn.py +362 -0
- aetherflow/models/speculative.py +426 -0
- aetherflow/models/ssm.py +179 -0
- aetherflow/models/transformer.py +382 -0
- aetherflow/passes/__init__.py +73 -0
- aetherflow/passes/autocast.py +180 -0
- aetherflow/passes/base.py +92 -0
- aetherflow/passes/cse.py +85 -0
- aetherflow/passes/dce.py +57 -0
- aetherflow/passes/fold.py +158 -0
- aetherflow/passes/fusion.py +268 -0
- aetherflow/passes/layout.py +261 -0
- aetherflow/passes/registry.py +213 -0
- aetherflow/passes/simplify.py +42 -0
- aetherflow/plugin.py +75 -0
- aetherflow/runtime/__init__.py +48 -0
- aetherflow/runtime/bf16.py +83 -0
- aetherflow/runtime/device_control.py +472 -0
- aetherflow/runtime/events.py +251 -0
- aetherflow/runtime/executor.py +617 -0
- aetherflow/runtime/fp8.py +275 -0
- aetherflow/runtime/paged_cache.py +897 -0
- aetherflow/runtime/prefix_store.py +508 -0
- aetherflow/runtime/reference.py +27 -0
- aetherflow/runtime/telemetry.py +596 -0
- aetherflow/runtime/trace.py +256 -0
- aetherflow/serve/__init__.py +20 -0
- aetherflow/serve/openai.py +767 -0
- aetherflow/train/__init__.py +154 -0
- aetherflow/train/_arrays.py +150 -0
- aetherflow/train/amp.py +219 -0
- aetherflow/train/bn.py +224 -0
- aetherflow/train/checkpoint.py +480 -0
- aetherflow/train/data.py +219 -0
- aetherflow/train/dataset.py +544 -0
- aetherflow/train/distributed.py +394 -0
- aetherflow/train/ema.py +143 -0
- aetherflow/train/grads.py +293 -0
- aetherflow/train/host_collective.py +497 -0
- aetherflow/train/lm.py +117 -0
- aetherflow/train/loop.py +1860 -0
- aetherflow/train/loss.py +105 -0
- aetherflow/train/monitor.py +208 -0
- aetherflow/train/nccl.py +831 -0
- aetherflow/train/optim.py +456 -0
- aetherflow/train/parallel.py +1296 -0
- aetherflow/train/params.py +220 -0
- aetherflow/train/pipeline.py +532 -0
- aetherflow/train/recompute.py +344 -0
- aetherflow/train/schedule.py +212 -0
- aetherflow/train/shard_io.py +685 -0
- aetherflow/train/sharded.py +490 -0
- aetherflow/train/tensor_parallel.py +527 -0
- aetherflow/train/zero.py +847 -0
- aetherflow/train/zero2.py +410 -0
- aetherflow/train/zero3.py +529 -0
- aetherflow/tuning/__init__.py +95 -0
- aetherflow/tuning/cost.py +535 -0
- aetherflow/tuning/paired.py +991 -0
- aetherflow/tuning/policy.py +195 -0
- aetherflow/tuning/search.py +290 -0
- aetherflow/tuning/signature.py +90 -0
- aetherflow/tuning/space.py +124 -0
- aetherflow/tuning/store.py +280 -0
- aetherflow/weights.py +1271 -0
- aetherflow_ai-0.2.0.dist-info/METADATA +578 -0
- aetherflow_ai-0.2.0.dist-info/RECORD +175 -0
- aetherflow_ai-0.2.0.dist-info/WHEEL +5 -0
- aetherflow_ai-0.2.0.dist-info/licenses/LICENSE +201 -0
- aetherflow_ai-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
"""cuSPARSE SpMM:``sparse_linear`` 的一条可选快路径,不是唯一实现。
|
|
2
|
+
|
|
3
|
+
``sparse_linear`` 的三件套 ``(indices, values, offsets)`` 本来就是 CSR:
|
|
4
|
+
``offsets`` 是行起点、``indices`` 是列号、``values`` 是非零值。因此
|
|
5
|
+
"CSR 事件 × 稠密权重"与 cuSPARSE 的 SpMM 是同一个运算,5.173 已经在
|
|
6
|
+
``benchmarks/sparse_compare.py`` 里用 ``cupyx.scipy.sparse`` 做过内核级对照
|
|
7
|
+
(自研散射比 cuSPARSE 快 1.73×~2.38×);本模块把那条约对照用的路接成
|
|
8
|
+
**生产路径的可选实现**,让"事件规模大到自研核不再占优"时有另一条路可走。
|
|
9
|
+
|
|
10
|
+
**默认仍走自研核**(``sparse_impl="custom"``)。两个理由:
|
|
11
|
+
|
|
12
|
+
1. 自研核带越界检查——``indices`` 越界在设备端记 ``err``、主机侧抛错。
|
|
13
|
+
库不做逐元素检查,越界读在设备上是未定义行为。默认路径不能把这条
|
|
14
|
+
检查丢掉。
|
|
15
|
+
2. 5.173 的实测在四个形状上都是自研核更快;把库路径设成默认,等于用
|
|
16
|
+
一个"可能更慢、且少一道检查"的实现替换已验证的路径。
|
|
17
|
+
|
|
18
|
+
覆盖范围:**f16 / f32 值 + i32 索引 + 行主序稠密矩阵**。f16 在 V100 上与
|
|
19
|
+
自研核同形状对拍过;索引只认 i32(i64 索引需要单独的对拍数据)。f64 不
|
|
20
|
+
放开——自研核的 ``sparse_linear`` 只承接 f16 / f32,若库路径单独支持 f64,
|
|
21
|
+
同一张图换个 ``sparse_impl`` 就会从"能跑"变成"报错",实现优劣不该改变
|
|
22
|
+
算子的承接面。表外形态一律 ``CusparseUnsupported``。
|
|
23
|
+
|
|
24
|
+
计算类型(``computeType``)跟着值的 dtype 走,但**不总等于存储类型**:f16
|
|
25
|
+
的存储类型是 ``CUDA_R_16F``,累加必须用 ``CUDA_R_32F``(半个精度做累加会
|
|
26
|
+
掉有效位),alpha / beta 的 ctypes 类型必须与 computeType 一致。
|
|
27
|
+
|
|
28
|
+
与 ``cudnn.py`` 同一个定位:它仍然属于 ADR-004 的范畴——IR 里的
|
|
29
|
+
``sparse_linear`` 依旧是语义完整的 PORTABLE 算子,"用 cuSPARSE 实现它"
|
|
30
|
+
是后端内部的实现选择,不产生 LIBRARY 节点。
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import ctypes
|
|
36
|
+
import ctypes.util
|
|
37
|
+
from typing import Any, Dict, Optional, Tuple
|
|
38
|
+
|
|
39
|
+
import numpy as np
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"CusparseUnavailable",
|
|
43
|
+
"CusparseUnsupported",
|
|
44
|
+
"available",
|
|
45
|
+
"data_type",
|
|
46
|
+
"compute_type",
|
|
47
|
+
"index_type",
|
|
48
|
+
"CusparseSpMM",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
# cudaDataType_t(与 cublas.py 同一组数字,见 /usr/local/cuda/include/
|
|
52
|
+
# library_types.h:16F=2 / 32F=0)
|
|
53
|
+
_CUDA_R_16F = 2
|
|
54
|
+
_CUDA_R_32F = 0
|
|
55
|
+
# cusparseIndexType_t:16U=1 / 32I=2 / 64I=3 / 8I=4。写成 1 会被当成 uint16
|
|
56
|
+
# 去读 int32 的 rowOffsets,越界读在真机上就是 cudaErrorIllegalAddress。
|
|
57
|
+
_CUSPARSE_INDEX_32I = 2
|
|
58
|
+
# cusparseIndexBase_t
|
|
59
|
+
_CUSPARSE_INDEX_BASE_ZERO = 0
|
|
60
|
+
# cusparseOperation_t
|
|
61
|
+
_CUSPARSE_OPERATION_NON_TRANSPOSE = 0
|
|
62
|
+
# cusparseOrder_t
|
|
63
|
+
_CUSPARSE_ORDER_ROW = 2
|
|
64
|
+
# cusparseSpMMAlg_t:0 是跨版本都在的默认算法。CSR_ALG1 / ALG2 在新旧版本
|
|
65
|
+
# 之间编号有变动,选具体算法会让"同一份代码在 11.x 与 12.x 上跑不同的核"。
|
|
66
|
+
_CUSPARSE_SPMM_ALG_DEFAULT = 0
|
|
67
|
+
_CUSPARSE_STATUS_SUCCESS = 0
|
|
68
|
+
|
|
69
|
+
# 这张表就是本模块的覆盖声明:不在这里的 dtype / 索引类型显式拒绝。
|
|
70
|
+
_DATA_TYPES = {
|
|
71
|
+
np.dtype("float16"): _CUDA_R_16F,
|
|
72
|
+
np.dtype("float32"): _CUDA_R_32F,
|
|
73
|
+
}
|
|
74
|
+
_INDEX_TYPES = {np.dtype("int32"): _CUSPARSE_INDEX_32I}
|
|
75
|
+
|
|
76
|
+
_CANDIDATES = (
|
|
77
|
+
"libcusparse.so.12",
|
|
78
|
+
"libcusparse.so.11",
|
|
79
|
+
"libcusparse.so",
|
|
80
|
+
"cusparse64_12.dll",
|
|
81
|
+
"cusparse64_11.dll",
|
|
82
|
+
"cusparse64_10.dll",
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
_loaded: Optional[Tuple[Any, str]] = None
|
|
86
|
+
_load_error: Optional[str] = None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class CusparseUnavailable(RuntimeError):
|
|
90
|
+
"""系统里没有可用的 cuSPARSE(或版本太旧,缺 SPMM 接口)。"""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class CusparseUnsupported(ValueError):
|
|
94
|
+
"""库在,但这个 dtype / 索引类型不在本模块登记的覆盖范围内。"""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def data_type(dtype: Any) -> int:
|
|
98
|
+
"""numpy dtype → ``cudaDataType_t``;未登记的类型显式拒绝。"""
|
|
99
|
+
key = np.dtype(dtype)
|
|
100
|
+
try:
|
|
101
|
+
return _DATA_TYPES[key]
|
|
102
|
+
except KeyError:
|
|
103
|
+
raise CusparseUnsupported(
|
|
104
|
+
f"cuSPARSE 快路径只登记了 {sorted(str(k) for k in _DATA_TYPES)},"
|
|
105
|
+
f"收到 {key};请改用 sparse_impl='custom'"
|
|
106
|
+
) from None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def compute_type(dtype: Any) -> int:
|
|
110
|
+
"""值的 dtype → ``computeType``:f16 / f32 都收敛到 ``CUDA_R_32F``。
|
|
111
|
+
|
|
112
|
+
与 ``data_type`` 分开是因为两者不总是同一个枚举:f16 的**存储**类型是
|
|
113
|
+
``CUDA_R_16F``,但**累加**必须用 ``CUDA_R_32F``。未登记的值类型在这里
|
|
114
|
+
就拒绝,不等到 `cusparseSpMM` 返回参数错误。
|
|
115
|
+
"""
|
|
116
|
+
data_type(dtype)
|
|
117
|
+
return _CUDA_R_32F
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def index_type(dtype: Any) -> int:
|
|
121
|
+
"""numpy dtype → ``cusparseIndexType_t``;只认 int32。"""
|
|
122
|
+
key = np.dtype(dtype)
|
|
123
|
+
try:
|
|
124
|
+
return _INDEX_TYPES[key]
|
|
125
|
+
except KeyError:
|
|
126
|
+
raise CusparseUnsupported(
|
|
127
|
+
f"cuSPARSE 快路径的 CSR 索引只登记了 "
|
|
128
|
+
f"{sorted(str(k) for k in _INDEX_TYPES)},收到 {key};"
|
|
129
|
+
"i64 索引需要单独的对拍数据,当前不放开"
|
|
130
|
+
) from None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _load() -> Tuple[Any, str]:
|
|
134
|
+
"""加载 libcusparse;失败抛 ``CusparseUnavailable``(结果缓存,只试一次)。"""
|
|
135
|
+
global _loaded, _load_error
|
|
136
|
+
if _loaded is not None:
|
|
137
|
+
return _loaded
|
|
138
|
+
if _load_error is not None:
|
|
139
|
+
raise CusparseUnavailable(_load_error)
|
|
140
|
+
|
|
141
|
+
names = list(_CANDIDATES)
|
|
142
|
+
found = ctypes.util.find_library("cusparse")
|
|
143
|
+
if found:
|
|
144
|
+
names.insert(0, found)
|
|
145
|
+
try: # pip install nvidia-cusparse-cu12 的包内 so 不在 ldconfig 路径里
|
|
146
|
+
import nvidia.cusparse as _pkg
|
|
147
|
+
|
|
148
|
+
for root in list(getattr(_pkg, "__path__", []) or []):
|
|
149
|
+
names.append(root + "/lib/libcusparse.so.12")
|
|
150
|
+
except ImportError:
|
|
151
|
+
pass
|
|
152
|
+
|
|
153
|
+
tried = []
|
|
154
|
+
for name in names:
|
|
155
|
+
try:
|
|
156
|
+
_loaded = (ctypes.CDLL(name), name)
|
|
157
|
+
return _loaded
|
|
158
|
+
except OSError as exc:
|
|
159
|
+
tried.append(f"{name}: {exc}")
|
|
160
|
+
_load_error = "找不到 cuSPARSE 动态库,尝试过:\n " + "\n ".join(tried)
|
|
161
|
+
raise CusparseUnavailable(_load_error)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def available() -> bool:
|
|
165
|
+
"""只回答"能不能加载",不建 handle,也不碰 GPU。"""
|
|
166
|
+
try:
|
|
167
|
+
_load()
|
|
168
|
+
except CusparseUnavailable:
|
|
169
|
+
return False
|
|
170
|
+
return True
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class CusparseSpMM:
|
|
174
|
+
"""一个进程内复用的 cuSPARSE handle + workspace 缓存。
|
|
175
|
+
|
|
176
|
+
**描述符每次调用重建,workspace 按形状缓存。** 描述符里写死的是
|
|
177
|
+
``offsets`` / ``indices`` / ``values`` / 权重 / 输出的地址,而这些数组
|
|
178
|
+
每一步都可能换(同一张图换一批事件就是新数组);``cusparseCsrSetPointers``
|
|
179
|
+
能改地址,但那是另一条没有真机验证过的路径。workspace 的大小只由
|
|
180
|
+
``(行, 列, 宽, nnz, 算法)`` 决定,与地址无关,因此可以安全缓存。
|
|
181
|
+
"""
|
|
182
|
+
|
|
183
|
+
def __init__(self) -> None:
|
|
184
|
+
lib, self.name = _load()
|
|
185
|
+
self.lib = lib
|
|
186
|
+
vp = ctypes.c_void_p
|
|
187
|
+
i64 = ctypes.c_int64
|
|
188
|
+
|
|
189
|
+
required = (
|
|
190
|
+
"cusparseCreate",
|
|
191
|
+
"cusparseSetStream",
|
|
192
|
+
"cusparseCreateCsr",
|
|
193
|
+
"cusparseCreateDnMat",
|
|
194
|
+
"cusparseSpMM_bufferSize",
|
|
195
|
+
"cusparseSpMM",
|
|
196
|
+
"cusparseDestroySpMat",
|
|
197
|
+
"cusparseDestroyDnMat",
|
|
198
|
+
"cusparseDestroy",
|
|
199
|
+
)
|
|
200
|
+
missing = [name for name in required if not hasattr(lib, name)]
|
|
201
|
+
if missing:
|
|
202
|
+
raise CusparseUnavailable(
|
|
203
|
+
f"{self.name} 缺少 SpMM 接口 {missing};"
|
|
204
|
+
"cusparseCreateCsr / cusparseSpMM 需要 CUDA 11 及以上"
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
lib.cusparseCreate.argtypes = [ctypes.POINTER(vp)]
|
|
208
|
+
lib.cusparseSetStream.argtypes = [vp, vp]
|
|
209
|
+
lib.cusparseCreateCsr.argtypes = [
|
|
210
|
+
ctypes.POINTER(vp), i64, i64, i64,
|
|
211
|
+
vp, vp, vp, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int,
|
|
212
|
+
]
|
|
213
|
+
lib.cusparseCreateDnMat.argtypes = [
|
|
214
|
+
ctypes.POINTER(vp), i64, i64, i64, vp, ctypes.c_int, ctypes.c_int,
|
|
215
|
+
]
|
|
216
|
+
lib.cusparseSpMM_bufferSize.argtypes = [
|
|
217
|
+
vp, ctypes.c_int, ctypes.c_int, vp, vp, vp, vp, vp,
|
|
218
|
+
ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_size_t),
|
|
219
|
+
]
|
|
220
|
+
lib.cusparseSpMM.argtypes = [
|
|
221
|
+
vp, ctypes.c_int, ctypes.c_int, vp, vp, vp, vp, vp,
|
|
222
|
+
ctypes.c_int, ctypes.c_int, vp,
|
|
223
|
+
]
|
|
224
|
+
lib.cusparseDestroySpMat.argtypes = [vp]
|
|
225
|
+
lib.cusparseDestroyDnMat.argtypes = [vp]
|
|
226
|
+
lib.cusparseDestroy.argtypes = [vp]
|
|
227
|
+
|
|
228
|
+
self.handle = vp()
|
|
229
|
+
self._check(lib.cusparseCreate(ctypes.byref(self.handle)), "cusparseCreate")
|
|
230
|
+
self._stream_ptr: Optional[int] = None
|
|
231
|
+
# key -> 字节数;workspace 数组另存一份,避免每次 SpMM 都重新分配
|
|
232
|
+
self._sizes: Dict[tuple, int] = {}
|
|
233
|
+
self._workspaces: Dict[int, Any] = {}
|
|
234
|
+
|
|
235
|
+
# ------------------------------------------------------------------
|
|
236
|
+
|
|
237
|
+
@staticmethod
|
|
238
|
+
def _check(status: int, what: str) -> None:
|
|
239
|
+
if status != _CUSPARSE_STATUS_SUCCESS:
|
|
240
|
+
raise RuntimeError(f"cuSPARSE {what} 失败,cusparseStatus_t={status}")
|
|
241
|
+
|
|
242
|
+
@staticmethod
|
|
243
|
+
def plan_key(steps: int, rows: int, cols: int, nnz: int, dtype: Any) -> tuple:
|
|
244
|
+
"""workspace 的缓存键:只含决定 workspace 大小的量。
|
|
245
|
+
|
|
246
|
+
``nnz`` 进键是必须的——SpMM 的 workspace 随非零数增长,同一形状的
|
|
247
|
+
两张图事件数不同却命中同一个键,会拿到装不下的缓冲。
|
|
248
|
+
"""
|
|
249
|
+
return (int(steps), int(rows), int(cols), int(nnz), np.dtype(dtype))
|
|
250
|
+
|
|
251
|
+
def set_stream(self, ptr: int) -> None:
|
|
252
|
+
"""绑定 stream;与 cuBLAS / cuDNN 一样做缓存,减少驱动调用。"""
|
|
253
|
+
ptr = int(ptr or 0)
|
|
254
|
+
if ptr == self._stream_ptr:
|
|
255
|
+
return
|
|
256
|
+
self._check(
|
|
257
|
+
self.lib.cusparseSetStream(self.handle, ctypes.c_void_p(ptr)),
|
|
258
|
+
"cusparseSetStream",
|
|
259
|
+
)
|
|
260
|
+
self._stream_ptr = ptr
|
|
261
|
+
|
|
262
|
+
def _workspace(self, width: int):
|
|
263
|
+
if width == 0:
|
|
264
|
+
return None
|
|
265
|
+
buf = self._workspaces.get(width)
|
|
266
|
+
if buf is None:
|
|
267
|
+
import cupy as cp
|
|
268
|
+
|
|
269
|
+
buf = cp.empty(width, dtype=cp.uint8)
|
|
270
|
+
self._workspaces[width] = buf
|
|
271
|
+
return buf
|
|
272
|
+
|
|
273
|
+
def _descriptors(self, offsets, indices, values, weights, out, dtype: int,
|
|
274
|
+
rows: int, cols: int, steps: int, nnz: int):
|
|
275
|
+
"""建 A / B / C 三个描述符。调用方负责销毁。"""
|
|
276
|
+
lib, vp = self.lib, ctypes.c_void_p
|
|
277
|
+
a, b, c = vp(), vp(), vp()
|
|
278
|
+
self._check(
|
|
279
|
+
lib.cusparseCreateCsr(
|
|
280
|
+
ctypes.byref(a), steps, rows, nnz,
|
|
281
|
+
vp(int(offsets.data.ptr)), vp(int(indices.data.ptr)),
|
|
282
|
+
vp(int(values.data.ptr)),
|
|
283
|
+
_CUSPARSE_INDEX_32I, _CUSPARSE_INDEX_32I,
|
|
284
|
+
_CUSPARSE_INDEX_BASE_ZERO, dtype,
|
|
285
|
+
),
|
|
286
|
+
"cusparseCreateCsr",
|
|
287
|
+
)
|
|
288
|
+
try:
|
|
289
|
+
# B 是 (rows, cols) 的行主序稠密矩阵,C 是 (steps, cols):行主序
|
|
290
|
+
# 的 ld 就是列数。用行主序而不是"转置成列主序",是因为两个
|
|
291
|
+
# 操作数都已经是 C 连续——转置只会多一次主机侧的心算。
|
|
292
|
+
self._check(
|
|
293
|
+
lib.cusparseCreateDnMat(
|
|
294
|
+
ctypes.byref(b), rows, cols, cols,
|
|
295
|
+
vp(int(weights.data.ptr)), dtype, _CUSPARSE_ORDER_ROW,
|
|
296
|
+
),
|
|
297
|
+
"cusparseCreateDnMat(B)",
|
|
298
|
+
)
|
|
299
|
+
try:
|
|
300
|
+
self._check(
|
|
301
|
+
lib.cusparseCreateDnMat(
|
|
302
|
+
ctypes.byref(c), steps, cols, cols,
|
|
303
|
+
vp(int(out.data.ptr)), dtype, _CUSPARSE_ORDER_ROW,
|
|
304
|
+
),
|
|
305
|
+
"cusparseCreateDnMat(C)",
|
|
306
|
+
)
|
|
307
|
+
except Exception:
|
|
308
|
+
self._check(lib.cusparseDestroyDnMat(b), "cusparseDestroyDnMat(B)")
|
|
309
|
+
raise
|
|
310
|
+
except Exception:
|
|
311
|
+
self._check(lib.cusparseDestroySpMat(a), "cusparseDestroySpMat(A)")
|
|
312
|
+
raise
|
|
313
|
+
return a, b, c
|
|
314
|
+
|
|
315
|
+
# ------------------------------------------------------------------
|
|
316
|
+
|
|
317
|
+
def spmm(self, offsets, indices, values, weights, *,
|
|
318
|
+
steps: int, rows: int, cols: int):
|
|
319
|
+
"""``out = A(steps×rows) · weights(rows×cols)``,返回新的 ``out``。
|
|
320
|
+
|
|
321
|
+
三件套与权重必须是**已经连续**的设备数组:本模块不做布局转换,
|
|
322
|
+
非连续输入在 ``.data.ptr`` 上会读错。dtype / 索引类型先过登记表,
|
|
323
|
+
未登记的形态在碰驱动之前就抛 ``CusparseUnsupported``。
|
|
324
|
+
"""
|
|
325
|
+
import cupy as cp
|
|
326
|
+
|
|
327
|
+
dtype = data_type(values.dtype)
|
|
328
|
+
compute = compute_type(values.dtype)
|
|
329
|
+
index_type(indices.dtype)
|
|
330
|
+
index_type(offsets.dtype)
|
|
331
|
+
nnz = int(values.size)
|
|
332
|
+
out = cp.empty((steps, cols), dtype=values.dtype)
|
|
333
|
+
if steps == 0 or cols == 0:
|
|
334
|
+
return out
|
|
335
|
+
|
|
336
|
+
self.set_stream(int(cp.cuda.get_current_stream().ptr))
|
|
337
|
+
a, b, c = self._descriptors(
|
|
338
|
+
offsets, indices, values, weights, out, dtype,
|
|
339
|
+
rows, cols, steps, nnz,
|
|
340
|
+
)
|
|
341
|
+
try:
|
|
342
|
+
key = self.plan_key(steps, rows, cols, nnz, values.dtype)
|
|
343
|
+
width = self._sizes.get(key)
|
|
344
|
+
# alpha / beta 的 ctypes 类型必须与 computeType 一致:compute 是
|
|
345
|
+
# CUDA_R_32F 时只能是 c_float(传 double 会被按 32 位截断读)。
|
|
346
|
+
alpha = ctypes.c_float(1.0)
|
|
347
|
+
beta = ctypes.c_float(0.0)
|
|
348
|
+
if width is None:
|
|
349
|
+
size = ctypes.c_size_t(0)
|
|
350
|
+
self._check(
|
|
351
|
+
self.lib.cusparseSpMM_bufferSize(
|
|
352
|
+
self.handle,
|
|
353
|
+
_CUSPARSE_OPERATION_NON_TRANSPOSE,
|
|
354
|
+
_CUSPARSE_OPERATION_NON_TRANSPOSE,
|
|
355
|
+
ctypes.byref(alpha), a, b, ctypes.byref(beta), c,
|
|
356
|
+
compute, _CUSPARSE_SPMM_ALG_DEFAULT,
|
|
357
|
+
ctypes.byref(size),
|
|
358
|
+
),
|
|
359
|
+
"cusparseSpMM_bufferSize",
|
|
360
|
+
)
|
|
361
|
+
width = int(size.value)
|
|
362
|
+
self._sizes[key] = width
|
|
363
|
+
workspace = self._workspace(width)
|
|
364
|
+
self._check(
|
|
365
|
+
self.lib.cusparseSpMM(
|
|
366
|
+
self.handle,
|
|
367
|
+
_CUSPARSE_OPERATION_NON_TRANSPOSE,
|
|
368
|
+
_CUSPARSE_OPERATION_NON_TRANSPOSE,
|
|
369
|
+
ctypes.byref(alpha), a, b,
|
|
370
|
+
ctypes.byref(beta), c,
|
|
371
|
+
compute, _CUSPARSE_SPMM_ALG_DEFAULT,
|
|
372
|
+
ctypes.c_void_p(0) if workspace is None
|
|
373
|
+
else ctypes.c_void_p(int(workspace.data.ptr)),
|
|
374
|
+
),
|
|
375
|
+
"cusparseSpMM",
|
|
376
|
+
)
|
|
377
|
+
finally:
|
|
378
|
+
self._check(self.lib.cusparseDestroySpMat(a), "cusparseDestroySpMat(A)")
|
|
379
|
+
self._check(self.lib.cusparseDestroyDnMat(b), "cusparseDestroyDnMat(B)")
|
|
380
|
+
self._check(self.lib.cusparseDestroyDnMat(c), "cusparseDestroyDnMat(C)")
|
|
381
|
+
return out
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""CUDA 方言:C 语法 + bf16 / f16 的存取(f16 走 PTX,bf16 走按位)。
|
|
2
|
+
|
|
3
|
+
方言是**数据**:类型映射、存取函数名、辅助函数源码。打印逻辑在
|
|
4
|
+
``aetherflow/lower/cstyle.py``,因此新增一家硬件只需要在这里换数据,
|
|
5
|
+
不用碰 L2 的节点,也不用碰打印器。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from ...ir.types import DType
|
|
11
|
+
from ...lower.cstyle import CStyleDialect
|
|
12
|
+
from . import codegen
|
|
13
|
+
|
|
14
|
+
__all__ = ["CUDA_DIALECT", "CAST_DIALECT", "BOOL_DIALECT"]
|
|
15
|
+
|
|
16
|
+
CUDA_DIALECT = CStyleDialect(
|
|
17
|
+
"cuda",
|
|
18
|
+
storage={
|
|
19
|
+
DType.F32: "float",
|
|
20
|
+
DType.F16: "unsigned short",
|
|
21
|
+
DType.BF16: "unsigned short",
|
|
22
|
+
},
|
|
23
|
+
load={DType.F32: "af_ld_f", DType.F16: "af_ld_h", DType.BF16: "af_ld_b"},
|
|
24
|
+
store={DType.F32: "af_st_f", DType.F16: "af_st_h", DType.BF16: "af_st_b"},
|
|
25
|
+
atomic={DType.F32: "af_add_f", DType.F16: "af_add_h", DType.BF16: "af_add_b"},
|
|
26
|
+
helpers={
|
|
27
|
+
DType.F32: codegen._F32_HELPERS + codegen._EXPR_HELPERS,
|
|
28
|
+
DType.F16: codegen._F16_HELPERS + codegen._EXPR_HELPERS,
|
|
29
|
+
DType.BF16: codegen._BF16_HELPERS + codegen._EXPR_HELPERS,
|
|
30
|
+
},
|
|
31
|
+
reduce_helpers=codegen._REDUCE,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
# ``cast`` 是唯一"输入与输出存储类型不同"的内核:按源 dtype 渲染决定用哪一套
|
|
35
|
+
# 读取 helper,写回的目标类型由张量参数自己声明。因此它需要所有可能用到的
|
|
36
|
+
# helper 同时在场(f32 / f16 / bf16 任意方向)。只给这一个内核用,不并进
|
|
37
|
+
# ``CUDA_DIALECT``——那会让所有内核的源码多出几十行,而 5.42 起有"生产源码
|
|
38
|
+
# 与手写模板逐 token 相等"的对照用例盯着每一个字。
|
|
39
|
+
_CAST_HELPERS = (
|
|
40
|
+
codegen._F32_HELPERS
|
|
41
|
+
+ codegen._F16_HELPERS
|
|
42
|
+
+ codegen._BF16_HELPERS
|
|
43
|
+
# 表达式级 helper(af_rem)与 dtype 无关:三块拼起来只追加一次,
|
|
44
|
+
# 否则同一个生成单元里会重复定义。
|
|
45
|
+
+ codegen._EXPR_HELPERS
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
CAST_DIALECT = CStyleDialect(
|
|
49
|
+
"cuda",
|
|
50
|
+
storage=CUDA_DIALECT.storage,
|
|
51
|
+
load=CUDA_DIALECT.load,
|
|
52
|
+
store=CUDA_DIALECT.store,
|
|
53
|
+
atomic=CUDA_DIALECT.atomic,
|
|
54
|
+
helpers={
|
|
55
|
+
DType.F32: _CAST_HELPERS,
|
|
56
|
+
DType.F16: _CAST_HELPERS,
|
|
57
|
+
DType.BF16: _CAST_HELPERS,
|
|
58
|
+
},
|
|
59
|
+
reduce_helpers=CUDA_DIALECT.reduce_helpers,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# 比较这类"输入数值、输出 bool"的内核同时需要两套 helper:源 dtype 的读取
|
|
63
|
+
# 与 bool 的读出/写回。与 CAST_DIALECT 同理,只给这一族内核用,不并进
|
|
64
|
+
# CUDA_DIALECT——否则每个普通内核都会多带一份用不到的 bool 存取。
|
|
65
|
+
_BOOL_HELPERS = _CAST_HELPERS + codegen._BOOL_HELPERS
|
|
66
|
+
|
|
67
|
+
BOOL_DIALECT = CStyleDialect(
|
|
68
|
+
"cuda",
|
|
69
|
+
storage={**CUDA_DIALECT.storage, DType.BOOL: "unsigned char"},
|
|
70
|
+
load={**CUDA_DIALECT.load, DType.BOOL: "af_ld_q"},
|
|
71
|
+
store={**CUDA_DIALECT.store, DType.BOOL: "af_st_q"},
|
|
72
|
+
atomic={**CUDA_DIALECT.atomic, DType.BOOL: "af_add_q"},
|
|
73
|
+
helpers={
|
|
74
|
+
DType.F32: _BOOL_HELPERS,
|
|
75
|
+
DType.F16: _BOOL_HELPERS,
|
|
76
|
+
DType.BF16: _BOOL_HELPERS,
|
|
77
|
+
DType.BOOL: _BOOL_HELPERS,
|
|
78
|
+
},
|
|
79
|
+
reduce_helpers=CUDA_DIALECT.reduce_helpers,
|
|
80
|
+
)
|