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.
Files changed (175) hide show
  1. aetherflow/__init__.py +322 -0
  2. aetherflow/agent_api.py +234 -0
  3. aetherflow/backends/__init__.py +69 -0
  4. aetherflow/backends/base.py +74 -0
  5. aetherflow/backends/capabilities.py +286 -0
  6. aetherflow/backends/contracts.py +278 -0
  7. aetherflow/backends/cuda/__init__.py +16 -0
  8. aetherflow/backends/cuda/backend.py +1023 -0
  9. aetherflow/backends/cuda/codegen.py +2874 -0
  10. aetherflow/backends/cuda/cublas.py +428 -0
  11. aetherflow/backends/cuda/cudnn.py +305 -0
  12. aetherflow/backends/cuda/cufft.py +384 -0
  13. aetherflow/backends/cuda/cusparse.py +381 -0
  14. aetherflow/backends/cuda/dialect.py +80 -0
  15. aetherflow/backends/cuda/memory.py +243 -0
  16. aetherflow/backends/device_attention.py +257 -0
  17. aetherflow/backends/device_backend.py +1569 -0
  18. aetherflow/backends/device_conv.py +970 -0
  19. aetherflow/backends/device_elementwise.py +629 -0
  20. aetherflow/backends/device_index.py +230 -0
  21. aetherflow/backends/device_linear.py +1301 -0
  22. aetherflow/backends/device_loss.py +109 -0
  23. aetherflow/backends/device_misc.py +249 -0
  24. aetherflow/backends/device_norm.py +197 -0
  25. aetherflow/backends/device_plan.py +1062 -0
  26. aetherflow/backends/device_pool.py +592 -0
  27. aetherflow/backends/device_reduce.py +512 -0
  28. aetherflow/backends/device_scan.py +457 -0
  29. aetherflow/backends/device_shape.py +108 -0
  30. aetherflow/backends/device_shared.py +1107 -0
  31. aetherflow/backends/device_sparse.py +373 -0
  32. aetherflow/backends/discovery.py +286 -0
  33. aetherflow/backends/hardware.py +784 -0
  34. aetherflow/backends/hip/__init__.py +15 -0
  35. aetherflow/backends/hip/backend.py +567 -0
  36. aetherflow/backends/hip/blas.py +227 -0
  37. aetherflow/backends/hip/codegen.py +109 -0
  38. aetherflow/backends/hip/dialect.py +62 -0
  39. aetherflow/backends/hip/memory.py +418 -0
  40. aetherflow/backends/hip/rtc.py +126 -0
  41. aetherflow/backends/hip/runtime.py +2018 -0
  42. aetherflow/backends/kernel_cache.py +240 -0
  43. aetherflow/backends/reference_backend.py +76 -0
  44. aetherflow/backends/registry.py +224 -0
  45. aetherflow/conformance.py +2791 -0
  46. aetherflow/deploy.py +259 -0
  47. aetherflow/dynamic.py +252 -0
  48. aetherflow/frontend/__init__.py +39 -0
  49. aetherflow/frontend/compat.py +118 -0
  50. aetherflow/frontend/eager.py +345 -0
  51. aetherflow/frontend/module.py +320 -0
  52. aetherflow/frontend/torch_export.py +2047 -0
  53. aetherflow/fuzz.py +1093 -0
  54. aetherflow/gguf.py +693 -0
  55. aetherflow/ir/__init__.py +144 -0
  56. aetherflow/ir/control.py +444 -0
  57. aetherflow/ir/grad.py +240 -0
  58. aetherflow/ir/grad_rules.py +1814 -0
  59. aetherflow/ir/graph.py +370 -0
  60. aetherflow/ir/liveness.py +227 -0
  61. aetherflow/ir/loop.py +437 -0
  62. aetherflow/ir/ops.py +6333 -0
  63. aetherflow/ir/second_order.py +111 -0
  64. aetherflow/ir/serialize.py +180 -0
  65. aetherflow/ir/shape_contract.py +146 -0
  66. aetherflow/ir/types.py +363 -0
  67. aetherflow/ir/verifier.py +130 -0
  68. aetherflow/ir/version.py +196 -0
  69. aetherflow/lower/__init__.py +202 -0
  70. aetherflow/lower/cstyle.py +354 -0
  71. aetherflow/lower/elementwise.py +346 -0
  72. aetherflow/lower/indexing.py +170 -0
  73. aetherflow/lower/kernel.py +448 -0
  74. aetherflow/lower/kernels/__init__.py +262 -0
  75. aetherflow/lower/kernels/attention.py +390 -0
  76. aetherflow/lower/kernels/common.py +95 -0
  77. aetherflow/lower/kernels/conv.py +2927 -0
  78. aetherflow/lower/kernels/elementwise.py +676 -0
  79. aetherflow/lower/kernels/image.py +97 -0
  80. aetherflow/lower/kernels/interpolate.py +381 -0
  81. aetherflow/lower/kernels/misc.py +154 -0
  82. aetherflow/lower/kernels/norm.py +675 -0
  83. aetherflow/lower/kernels/pool.py +650 -0
  84. aetherflow/lower/kernels/reduce.py +891 -0
  85. aetherflow/lower/kernels/scan.py +939 -0
  86. aetherflow/lower/kernels/sparse.py +680 -0
  87. aetherflow/lower/plan.py +884 -0
  88. aetherflow/lower/translate.py +382 -0
  89. aetherflow/models/__init__.py +227 -0
  90. aetherflow/models/cached_attention.py +1133 -0
  91. aetherflow/models/cnn.py +208 -0
  92. aetherflow/models/hf_export.py +363 -0
  93. aetherflow/models/llama.py +875 -0
  94. aetherflow/models/lm.py +2888 -0
  95. aetherflow/models/lm_bpe.py +812 -0
  96. aetherflow/models/lm_text.py +159 -0
  97. aetherflow/models/lm_tools.py +1048 -0
  98. aetherflow/models/lm_unigram.py +794 -0
  99. aetherflow/models/lm_wordpiece.py +429 -0
  100. aetherflow/models/mamba.py +917 -0
  101. aetherflow/models/mamba_reference.py +183 -0
  102. aetherflow/models/mlp.py +84 -0
  103. aetherflow/models/moe.py +158 -0
  104. aetherflow/models/quantize.py +775 -0
  105. aetherflow/models/rnn.py +157 -0
  106. aetherflow/models/snn.py +362 -0
  107. aetherflow/models/speculative.py +426 -0
  108. aetherflow/models/ssm.py +179 -0
  109. aetherflow/models/transformer.py +382 -0
  110. aetherflow/passes/__init__.py +73 -0
  111. aetherflow/passes/autocast.py +180 -0
  112. aetherflow/passes/base.py +92 -0
  113. aetherflow/passes/cse.py +85 -0
  114. aetherflow/passes/dce.py +57 -0
  115. aetherflow/passes/fold.py +158 -0
  116. aetherflow/passes/fusion.py +268 -0
  117. aetherflow/passes/layout.py +261 -0
  118. aetherflow/passes/registry.py +213 -0
  119. aetherflow/passes/simplify.py +42 -0
  120. aetherflow/plugin.py +75 -0
  121. aetherflow/runtime/__init__.py +48 -0
  122. aetherflow/runtime/bf16.py +83 -0
  123. aetherflow/runtime/device_control.py +472 -0
  124. aetherflow/runtime/events.py +251 -0
  125. aetherflow/runtime/executor.py +617 -0
  126. aetherflow/runtime/fp8.py +275 -0
  127. aetherflow/runtime/paged_cache.py +897 -0
  128. aetherflow/runtime/prefix_store.py +508 -0
  129. aetherflow/runtime/reference.py +27 -0
  130. aetherflow/runtime/telemetry.py +596 -0
  131. aetherflow/runtime/trace.py +256 -0
  132. aetherflow/serve/__init__.py +20 -0
  133. aetherflow/serve/openai.py +767 -0
  134. aetherflow/train/__init__.py +154 -0
  135. aetherflow/train/_arrays.py +150 -0
  136. aetherflow/train/amp.py +219 -0
  137. aetherflow/train/bn.py +224 -0
  138. aetherflow/train/checkpoint.py +480 -0
  139. aetherflow/train/data.py +219 -0
  140. aetherflow/train/dataset.py +544 -0
  141. aetherflow/train/distributed.py +394 -0
  142. aetherflow/train/ema.py +143 -0
  143. aetherflow/train/grads.py +293 -0
  144. aetherflow/train/host_collective.py +497 -0
  145. aetherflow/train/lm.py +117 -0
  146. aetherflow/train/loop.py +1860 -0
  147. aetherflow/train/loss.py +105 -0
  148. aetherflow/train/monitor.py +208 -0
  149. aetherflow/train/nccl.py +831 -0
  150. aetherflow/train/optim.py +456 -0
  151. aetherflow/train/parallel.py +1296 -0
  152. aetherflow/train/params.py +220 -0
  153. aetherflow/train/pipeline.py +532 -0
  154. aetherflow/train/recompute.py +344 -0
  155. aetherflow/train/schedule.py +212 -0
  156. aetherflow/train/shard_io.py +685 -0
  157. aetherflow/train/sharded.py +490 -0
  158. aetherflow/train/tensor_parallel.py +527 -0
  159. aetherflow/train/zero.py +847 -0
  160. aetherflow/train/zero2.py +410 -0
  161. aetherflow/train/zero3.py +529 -0
  162. aetherflow/tuning/__init__.py +95 -0
  163. aetherflow/tuning/cost.py +535 -0
  164. aetherflow/tuning/paired.py +991 -0
  165. aetherflow/tuning/policy.py +195 -0
  166. aetherflow/tuning/search.py +290 -0
  167. aetherflow/tuning/signature.py +90 -0
  168. aetherflow/tuning/space.py +124 -0
  169. aetherflow/tuning/store.py +280 -0
  170. aetherflow/weights.py +1271 -0
  171. aetherflow_ai-0.2.0.dist-info/METADATA +578 -0
  172. aetherflow_ai-0.2.0.dist-info/RECORD +175 -0
  173. aetherflow_ai-0.2.0.dist-info/WHEEL +5 -0
  174. aetherflow_ai-0.2.0.dist-info/licenses/LICENSE +201 -0
  175. aetherflow_ai-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,286 @@
1
+ """后端能力契约:从"算子名集合"到"算子 × 形态"。
2
+
3
+ 5.9 的准入面只要求 ``capabilities()`` 返回算子名集合。那能回答"有没有这个
4
+ 算子",回答不了"这个 dtype 行不行""是不是只支持最后一维""能不能进反向图
5
+ 或图捕获"。只声明名字时,跑通一种形态就会被读成全面支持——这是审计 AF-32
6
+ 第二点指出的缺口。
7
+
8
+ 这里的做法是**扩展而不替换**:
9
+
10
+ - ``BackendCapabilities`` 是 ``frozenset`` 的子类。``set(caps)``、``len``、
11
+ ``in``、与普通 ``frozenset`` 的相等比较全部照旧;后端仍可只返回一个普通
12
+ 集合,含义是"只承诺算子名"。
13
+ - 想说得更细的后端,为算子附一份 ``OpCapability``:dtype / axis / layout
14
+ 是**排除项**,``None`` 表示未声明限制;backward / capture / deterministic
15
+ 是**用途承诺**,默认全为 True。
16
+ - ``refined`` / ``unrefined`` 把"哪些算子说了形态细节、哪些只说了名字"
17
+ 暴露给调用方,避免把"没有排除"当成"已经验证"。
18
+
19
+ 明细不参与相等与哈希:同一个算子集合可以有不同细粒度,但``==`` 仍按集合
20
+ 比较。这是为了不打断既有的对账代码(如 CUDA 后端把 ``capabilities()`` 与
21
+ 静态算子表直接比较)。需要比较细粒度时用 ``describe()``。
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from dataclasses import dataclass
27
+ from types import MappingProxyType
28
+ from typing import (
29
+ TYPE_CHECKING,
30
+ FrozenSet,
31
+ Iterable,
32
+ List,
33
+ Mapping,
34
+ Optional,
35
+ Tuple,
36
+ Union,
37
+ )
38
+
39
+ from ..ir.types import DType
40
+
41
+ if TYPE_CHECKING: # 只用于注解,避免运行时把 ir 的图对象拖进来
42
+ from ..ir.graph import Graph, Node
43
+
44
+ DTypeLike = Union[DType, str]
45
+ Axes = Union[int, Iterable[int]]
46
+
47
+
48
+ def _dtype_set(values: Optional[Iterable[DTypeLike]]) -> Optional[FrozenSet[DType]]:
49
+ if values is None:
50
+ return None
51
+ return frozenset(v if isinstance(v, DType) else DType(v) for v in values)
52
+
53
+
54
+ def _axis_set(values: Optional[Axes]) -> Optional[FrozenSet[int]]:
55
+ if values is None:
56
+ return None
57
+ if isinstance(values, int):
58
+ return frozenset((values,))
59
+ return frozenset(int(v) for v in values)
60
+
61
+
62
+ def _string_set(values: Optional[Iterable[str]]) -> Optional[FrozenSet[str]]:
63
+ if values is None:
64
+ return None
65
+ if isinstance(values, str):
66
+ return frozenset((values,))
67
+ return frozenset(str(v) for v in values)
68
+
69
+
70
+ def _norm_axes(axes: Axes, rank: Optional[int]) -> Tuple[int, ...]:
71
+ """把轴集合规范到 ``[0, rank)``;没有秩时原样返回。"""
72
+ items = (axes,) if isinstance(axes, int) else tuple(axes)
73
+ if rank is None or rank <= 0:
74
+ return tuple(int(a) for a in items)
75
+ return tuple(int(a) % rank for a in items)
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class OpCapability:
80
+ """单个算子的形态明细。
81
+
82
+ 字段分两类,混在一起看会误读:
83
+
84
+ - ``dtypes`` / ``axes`` / ``layouts`` 是**排除项**。``None`` 表示这个
85
+ 维度没有声明限制(不是"已验证全部取值");给了集合就表示只接收集合
86
+ 里的取值,其余在构图期/执行前就该被拒绝。
87
+ - ``backward`` / ``capture`` / ``deterministic`` 是**承诺**,默认 True。
88
+ 它们不来自图,而是来自用途:训练要看 backward,图捕获要看 capture,
89
+ 一致性基准要看 deterministic。
90
+
91
+ ``axes`` 只约束归约/归一化类算子的 ``axis`` / ``axes`` 属性,且声明里
92
+ 写正向或负向下标都可以(判定时按节点输入的秩一起规范化)。
93
+ """
94
+
95
+ dtypes: Optional[FrozenSet[DType]] = None
96
+ axes: Optional[FrozenSet[int]] = None
97
+ layouts: Optional[FrozenSet[str]] = None
98
+ backward: bool = True
99
+ capture: bool = True
100
+ deterministic: bool = True
101
+
102
+ def __post_init__(self) -> None:
103
+ object.__setattr__(self, "dtypes", _dtype_set(self.dtypes))
104
+ object.__setattr__(self, "axes", _axis_set(self.axes))
105
+ object.__setattr__(self, "layouts", _string_set(self.layouts))
106
+
107
+ def explain(
108
+ self,
109
+ *,
110
+ dtype: Optional[DTypeLike] = None,
111
+ axis: Optional[Axes] = None,
112
+ layout: Optional[str] = None,
113
+ rank: Optional[int] = None,
114
+ backward: bool = False,
115
+ capture: bool = False,
116
+ deterministic: bool = False,
117
+ ) -> Optional[str]:
118
+ """说明这一形态为什么不满足声明;全部满足返回 ``None``。
119
+
120
+ ``dtype`` / ``axis`` / ``layout`` 传 ``None`` 表示"这一维没有问",
121
+ 未声明的维度也不会拒绝。三个布尔参数表示"这次用途需要该能力"。
122
+ """
123
+ if dtype is not None and self.dtypes is not None:
124
+ want = dtype if isinstance(dtype, DType) else DType(dtype)
125
+ if want not in self.dtypes:
126
+ allowed = sorted(d.value for d in self.dtypes)
127
+ return f"dtype {want.value} 不在支持范围 {allowed}"
128
+
129
+ if axis is not None and self.axes is not None:
130
+ want_axes = _norm_axes(axis, rank)
131
+ allowed_axes = _norm_axes(self.axes, rank)
132
+ bad = sorted({a for a in want_axes if a not in allowed_axes})
133
+ if bad:
134
+ return f"axis {bad} 不在支持范围 {sorted(allowed_axes)}"
135
+
136
+ if layout is not None and self.layouts is not None and layout not in self.layouts:
137
+ return f"layout {layout!r} 不在支持范围 {sorted(self.layouts)}"
138
+
139
+ if backward and not self.backward:
140
+ return "不支持反向(backward)"
141
+ if capture and not self.capture:
142
+ return "不支持图捕获(capture)"
143
+ if deterministic and not self.deterministic:
144
+ return "不保证确定性(deterministic)"
145
+ return None
146
+
147
+
148
+ class BackendCapabilities(frozenset):
149
+ """算子名集合+可选的形态明细。
150
+
151
+ 集合语义保持不变,明细是附加信息。没有明细的算子仍然算"已承接",只是
152
+ 承诺粒度停留在算子名;``unrefined`` 会把这些算子单独列出来。
153
+ """
154
+
155
+ def __new__(
156
+ cls,
157
+ ops: Iterable[str] = (),
158
+ details: Optional[Mapping[str, OpCapability]] = None,
159
+ ) -> "BackendCapabilities":
160
+ names = frozenset(ops)
161
+ if details is None and isinstance(ops, BackendCapabilities):
162
+ details = ops.details
163
+ clean = dict(details or {})
164
+
165
+ extra = sorted(set(clean) - names)
166
+ if extra:
167
+ raise ValueError(f"能力明细里出现了未声明承接的算子: {extra}")
168
+ wrong = sorted(name for name, cap in clean.items() if not isinstance(cap, OpCapability))
169
+ if wrong:
170
+ raise TypeError(f"能力明细必须是 OpCapability,这些不是: {wrong}")
171
+
172
+ obj = super().__new__(cls, names)
173
+ # frozenset 子类实例带 __dict__,用 object.__setattr__ 绕开不可变限制;
174
+ # 包成 MappingProxyType 是为了让"明细"也跟集合一样只读。
175
+ object.__setattr__(obj, "_details", MappingProxyType(clean))
176
+ return obj
177
+
178
+ # -- 集合之外的只读面 ---------------------------------------------
179
+
180
+ @property
181
+ def details(self) -> Mapping[str, OpCapability]:
182
+ return self._details
183
+
184
+ @property
185
+ def refined(self) -> FrozenSet[str]:
186
+ """给了形态明细的算子。"""
187
+ return frozenset(self._details)
188
+
189
+ @property
190
+ def unrefined(self) -> FrozenSet[str]:
191
+ """只声明了名字、没有形态明细的算子。"""
192
+ return frozenset(self) - self.refined
193
+
194
+ def describe(self, op_name: str) -> Optional[OpCapability]:
195
+ return self._details.get(op_name)
196
+
197
+ def explain(self, op_name: str, **features) -> Optional[str]:
198
+ """按给定形态检查某个算子;未承接或未细化返回 ``None`` / 原因。"""
199
+ if op_name not in self:
200
+ return f"未承接算子 {op_name}"
201
+ detail = self._details.get(op_name)
202
+ if detail is None:
203
+ return None
204
+ return detail.explain(**features)
205
+
206
+ def supports(self, op_name: str, **features) -> bool:
207
+ """True 只表示声明没有排除这一形态,不代表已被用例覆盖。"""
208
+ return self.explain(op_name, **features) is None
209
+
210
+ def explain_node(self, node: "Node") -> Optional[str]:
211
+ """按节点实际形态(输出 dtype、axis/axes、layout)给出拒绝原因。"""
212
+ name = node.op.name
213
+ if name not in self:
214
+ return f"未承接算子 {name}"
215
+ detail = self._details.get(name)
216
+ if detail is None:
217
+ return None
218
+
219
+ attrs = node.attrs
220
+ rank = node.inputs[0].type.rank if node.inputs else None
221
+ reason = detail.explain(
222
+ dtype=node.output.type.dtype,
223
+ axis=attrs.get("axis", attrs.get("axes")),
224
+ layout=attrs.get("layout"),
225
+ rank=rank,
226
+ )
227
+ if reason is None:
228
+ return None
229
+ return f"{name}: {reason}"
230
+
231
+ def supports_node(
232
+ self,
233
+ node: "Node",
234
+ *,
235
+ backward: bool = False,
236
+ capture: bool = False,
237
+ deterministic: bool = False,
238
+ ) -> bool:
239
+ """节点形态与用途同时满足声明时返回 True。"""
240
+ if self.explain_node(node) is not None:
241
+ return False
242
+ detail = self._details.get(node.op.name)
243
+ if detail is None:
244
+ return True
245
+ return (
246
+ detail.explain(
247
+ backward=backward, capture=capture, deterministic=deterministic
248
+ )
249
+ is None
250
+ )
251
+
252
+ # -- 杂项 ---------------------------------------------------------
253
+
254
+ def __repr__(self) -> str:
255
+ return f"BackendCapabilities({len(self)} 个算子,细化 {len(self._details)} 个)"
256
+
257
+ def __reduce__(self):
258
+ # pickle 默认只会还原 frozenset 的元素,明细会静默丢失
259
+ return (type(self), (frozenset(self), dict(self._details)))
260
+
261
+
262
+ def to_capabilities(capabilities: Iterable[str]) -> BackendCapabilities:
263
+ """把后端交出的能力声明统一成 ``BackendCapabilities``(不复制明细)。"""
264
+ if isinstance(capabilities, BackendCapabilities):
265
+ return capabilities
266
+ return BackendCapabilities(capabilities)
267
+
268
+
269
+ def capability_gaps(
270
+ graph: "Graph", capabilities: Iterable[str]
271
+ ) -> List[Tuple[str, str]]:
272
+ """返回 ``(算子名, 原因)``,按节点出现顺序、按算子名去重。
273
+
274
+ 只声明算子名的后端,gap 只有"未承接算子"一种;给了明细的后端还会因为
275
+ dtype / axis / layout 不匹配产生 gap。
276
+ """
277
+ caps = to_capabilities(capabilities)
278
+ gaps: List[Tuple[str, str]] = []
279
+ seen = set()
280
+ for node in graph.nodes:
281
+ reason = caps.explain_node(node)
282
+ if reason is None or node.op.name in seen:
283
+ continue
284
+ seen.add(node.op.name)
285
+ gaps.append((node.op.name, reason))
286
+ return gaps
@@ -0,0 +1,278 @@
1
+ """插件契约的可选层。
2
+
3
+ ``base.Backend`` 是准入面,只有三个成员:``name`` / ``capabilities()`` /
4
+ ``execute()``。任何后端都必须有,缺一个就不算后端。这里是它之外的**可选契约**:
5
+ 后端具备对应能力才实现,不具备就不实现,前端与工具靠探测决定用不用。
6
+
7
+ 为什么拆成独立协议,而不是继续往 ``Backend`` 上加方法:
8
+
9
+ - 生命周期不同。设备信息是"启动时问一次",内存统计是"每次运行后关心",
10
+ 而调优是离线的事,codegen 是编译期的事。混在一个接口里,最小准入面会变成
11
+ 所有插件都必须假装填满的巨型接口——第二个后端接入时,第一件事是写一堆
12
+ 返回空值的占位实现,那等于没有契约。
13
+ - 不实现的后端不受影响。``ReferenceBackend`` 一个可选契约都不实现,
14
+ 照样跑全部用例、照样通过 conformance。
15
+
16
+ **只在两个实现共享同一语义时才写契约。** ``CodegenContract`` / ``TuningContract``
17
+ 在 5.163 提炼:CUDA 与 HIP 的 ``_kernel(key, source, func)`` 签名与语义一致,
18
+ 调优面(``tunable_ops`` / ``tuning_space`` / ``set_tuning`` / ``clear_tuning`` /
19
+ ``tuning_config``)也由同一个 ``DeviceBackend`` 提供。两者都是"离线/编译期"的
20
+ 能力,和运行期的设备信息、内存统计生命周期不同,所以仍然分协议。
21
+
22
+ 不写进契约的部分同样是刻意的:codegen 不约束句柄类型(CUDA 是
23
+ ``cupy.RawKernel``,HIP 是模块函数),调优不约束搜索策略与存储格式——那些是
24
+ 工具层的事,写进契约就等于要求每个后端自带一套调优器。
25
+
26
+ **探测的语义必须说清楚。** ``isinstance(obj, Protocol)`` 只检查方法**是否存在**,
27
+ 不检查签名,更不检查返回值含义。所以 ``implemented_contracts()`` 的结论是
28
+ "这个后端声称有这项能力",不是"这项能力是对的"。后者只能靠实际调用与
29
+ conformance 证明。
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from dataclasses import dataclass
35
+ from typing import (
36
+ TYPE_CHECKING,
37
+ Any,
38
+ FrozenSet,
39
+ Mapping,
40
+ Optional,
41
+ Protocol,
42
+ Tuple,
43
+ runtime_checkable,
44
+ )
45
+
46
+ if TYPE_CHECKING: # 只为注解,避免 contracts 在导入期把 tuning 的 numpy 依赖带进来
47
+ from ..tuning.space import TuningSpace
48
+
49
+ __all__ = [
50
+ "DeviceInfo",
51
+ "MemoryStats",
52
+ "DeviceContract",
53
+ "DeviceManagerContract",
54
+ "CodegenContract",
55
+ "TuningContract",
56
+ "MemoryContract",
57
+ "StreamContract",
58
+ "AllocatorContract",
59
+ "CONTRACTS",
60
+ "supports",
61
+ "implemented_contracts",
62
+ ]
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class DeviceInfo:
67
+ """一块可用于计算的设备的静态信息。
68
+
69
+ 只收"插件自己知道、且上层真的会看"的三项。显存总量用字节而不是 GB,
70
+ 格式化是展示层的事,契约里不做四舍五入。
71
+ """
72
+
73
+ name: str
74
+ runtime: int
75
+ total_memory_bytes: int
76
+
77
+ @property
78
+ def total_memory_gb(self) -> float:
79
+ return round(self.total_memory_bytes / 1024**3, 2)
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class MemoryStats:
84
+ """分层分配器的一次快照,单位字节。
85
+
86
+ 四个数各有各的用途,缺一个都会让结论失真:
87
+
88
+ - ``live_bytes``:当前仍被占用的量
89
+ - ``peak_bytes``:历史峰值存活量,即这张图绕不过去的显存下界
90
+ - ``total_bytes``:向驱动实际申请的总量(真实占用)
91
+ - ``requested_bytes``:累计请求量,即"完全不复用需要多少"
92
+
93
+ ``total_bytes`` 与 ``peak_bytes`` 的差额是分配器自身的浪费(块内碎片、对齐)。
94
+ """
95
+
96
+ live_bytes: int
97
+ peak_bytes: int
98
+ total_bytes: int
99
+ requested_bytes: int
100
+
101
+
102
+ @runtime_checkable
103
+ class DeviceContract(Protocol):
104
+ """设备管理器:能被询问"你用的是什么设备"。"""
105
+
106
+ def device_info(self) -> DeviceInfo:
107
+ ...
108
+
109
+
110
+ @runtime_checkable
111
+ class DeviceManagerContract(Protocol):
112
+ """多设备:枚举、查询当前设备、切换。
113
+
114
+ 5.164 提炼。此前 ``StreamContract`` 的注释明确写着"不写多设备枚举与
115
+ 切换:HIP 侧没有对应实现"。HIP 侧补上之后,两家在三个方法上语义一致:
116
+
117
+ - ``enumerate_devices()``:按索引顺序返回进程可见的全部设备;
118
+ - ``current_device()``:当前上下文所在的设备索引;
119
+ - ``set_device(index)``:切换当前设备,越界或类型不对**当场**报错。
120
+
121
+ 切换之后 ``device_info()`` 与自动 block 用的 SM 数必须跟着走——否则
122
+ "切了设备但仍在旧卡上铺块"是最难查的一类错。这条要求写在契约说明里,
123
+ 因为协议只查方法存在性,查不到语义。
124
+
125
+ 与 ``DeviceContract`` 分开:单设备后端也能回答"我用的是什么设备",
126
+ 但回答不了"还有哪几块"。生命周期上两者都是启动时问一次,拆开只是
127
+ 为了让能力粒度如实反映实现。
128
+ """
129
+
130
+ def enumerate_devices(self) -> Tuple[DeviceInfo, ...]:
131
+ ...
132
+
133
+ def current_device(self) -> int:
134
+ ...
135
+
136
+ def set_device(self, index: int) -> None:
137
+ ...
138
+
139
+
140
+ @runtime_checkable
141
+ class CodegenContract(Protocol):
142
+ """编译期:能把渲染好的厂商源码编成可调用句柄。
143
+
144
+ CUDA 与 HIP 的私有实现是 ``_kernel(key, source, func)``;公开入口是
145
+ ``DeviceBackend.kernel``,签名完全相同:
146
+
147
+ - ``key``:编译缓存键,必须可哈希且稳定(通常是算子的渲染签名)。同一
148
+ key 重复调用返回同一个句柄,不重复走编译器。
149
+ - ``source``:厂商语言源码。CUDA 是 CUDA C,HIP 是它接受的 HIP C++——
150
+ 契约不要求两者同一种方言,只要求"这个后端的源码"。
151
+ - ``func``:入口函数名。
152
+
153
+ 返回值的类型由后端决定,契约只承诺"可调用且能按该后端的启动方式使用"。
154
+ 公开入口 ``DeviceBackend.kernel()`` 把两种后端的形态收成一个带
155
+ ``launch(...)`` 的包装句柄(同时保留 ``__call__``),跨后端工具因此不必
156
+ 关心"这个后端靠 ``__call__`` 还是 ``launch`` 启动"。
157
+ 编译失败必须抛异常,不要返回 ``None``——``None`` 会让失败延后到启动时,
158
+ 那时的报错已经不知道是哪段源码。
159
+ """
160
+
161
+ def kernel(self, key: Any, source: Any, func: str) -> Any:
162
+ ...
163
+
164
+
165
+ @runtime_checkable
166
+ class TuningContract(Protocol):
167
+ """调优面:枚举可调算子、给出搜索空间、读写覆盖配置。
168
+
169
+ 这是一组**离线**接口:调优工具在进程里反复改配置、重测,正式执行时只读
170
+ ``tuning_config()``。它不负责搜索算法,也不负责任何测量——那些在
171
+ ``aetherflow.tuning`` 里,对任何实现了本契约的后端都通用。
172
+
173
+ 配置的语义由后端定义(块大小、线程铺法、tile 形状……),契约只要求
174
+ "``set_tuning`` 接受的东西,``tuning_config`` 能原样读回",以及非法配置
175
+ 在 ``set_tuning`` 当场报错,而不是等到执行时才发现。
176
+ """
177
+
178
+ def tunable_ops(self) -> FrozenSet[str]:
179
+ ...
180
+
181
+ def tuning_space(self, op: str) -> "TuningSpace":
182
+ ...
183
+
184
+ def set_tuning(self, op: str, config: Mapping[str, Any]) -> None:
185
+ ...
186
+
187
+ def clear_tuning(self, op: Optional[str] = None) -> None:
188
+ ...
189
+
190
+ def tuning_config(self) -> Mapping[str, Mapping[str, Any]]:
191
+ ...
192
+
193
+
194
+ @runtime_checkable
195
+ class StreamContract(Protocol):
196
+ """流管理:能开一条用于捕获与 replay 的非阻塞流。
197
+
198
+ 5.89 把这半件事从 CUDA 插件内部提出来:CUDA 与 HIP 现在都已实现,且
199
+ 语义一致(非阻塞;图捕获必须发生在它上面,默认流上捕获会被驱动拒绝)。
200
+ 它和 ``DeviceContract`` 分开,是模块头那条"生命周期不同就拆协议"的直接
201
+ 应用——设备信息是启动时问一次,流是每个捕获/每步训练都要开的东西。
202
+
203
+ 仍然不写多设备枚举与切换:那三项在 5.164 独立成 ``DeviceManagerContract``,
204
+ 而不是塞进流契约——开流与选卡是两件事。
205
+ """
206
+
207
+ def new_stream(self) -> Any:
208
+ ...
209
+
210
+
211
+ @runtime_checkable
212
+ class MemoryContract(Protocol):
213
+ """内存分层:能被询问"上一次运行用了多少、峰值多少",并能交出一个分配器。
214
+
215
+ 没有可报告的对象时返回 ``None``,不要返回一串 0——0 是一个具体的观测值,
216
+ 会让"没有统计"和"用了 0 字节"混为一谈。
217
+
218
+ ``allocator()`` 返回的是一个**新**的分配器(不与上一次捕获共享地址:
219
+ 地址写死在图里,共享会让两张图的中间值互相踩),它的形状由
220
+ ``AllocatorContract`` 描述。
221
+ """
222
+
223
+ def memory_stats(self) -> Optional[MemoryStats]:
224
+ ...
225
+
226
+ def allocator(self) -> Any:
227
+ ...
228
+
229
+
230
+ @runtime_checkable
231
+ class AllocatorContract(Protocol):
232
+ """一次捕获期内的显存规划器。
233
+
234
+ 只在两个真实实现共享的那五个方法上提炼(``cuda/memory.Arena`` 与
235
+ ``hip/memory.Arena``)。``alias`` / ``unalias`` 不在契约里——那是 cupy
236
+ 零拷贝视图特有的记账,HIP 的 ``DeviceArray`` 没有这一层。
237
+
238
+ ``recycle`` 也不在契约里:只有 HIP 需要它(CUDA 侧预热轮的块由池回收),
239
+ 把它写进契约就等于要求 CUDA 实现一个永远不用的方法。
240
+
241
+ 注意它**不挂在后端上**,所以不进 ``CONTRACTS`` 表:那张表回答的是
242
+ "这个后端能做什么",而分配器是后端交出来的对象。
243
+ """
244
+
245
+ def malloc(self, size: int) -> Any:
246
+ ...
247
+
248
+ def free(self, ptr: Any) -> None:
249
+ ...
250
+
251
+ def stats(self) -> MemoryStats:
252
+ ...
253
+
254
+ def reset_stats(self) -> None:
255
+ ...
256
+
257
+ def close(self) -> None:
258
+ ...
259
+
260
+
261
+ CONTRACTS: Mapping[str, type] = {
262
+ "device": DeviceContract,
263
+ "device_manager": DeviceManagerContract,
264
+ "codegen": CodegenContract,
265
+ "tuning": TuningContract,
266
+ "memory": MemoryContract,
267
+ "stream": StreamContract,
268
+ }
269
+
270
+
271
+ def supports(backend: object, contract: type) -> bool:
272
+ """后端是否**声称**实现了某个契约(只查方法存在性)。"""
273
+ return isinstance(backend, contract)
274
+
275
+
276
+ def implemented_contracts(backend: object) -> Tuple[str, ...]:
277
+ """按 ``CONTRACTS`` 的声明顺序,返回后端声称实现的契约名。"""
278
+ return tuple(name for name, proto in CONTRACTS.items() if supports(backend, proto))
@@ -0,0 +1,16 @@
1
+ """CUDA 后端插件。
2
+
3
+ ``cupy`` 是可选依赖:在本模块层面不导入它,
4
+ 所以没有 CUDA 的机器上 ``import aetherflow.backends.cuda`` 仍然可用,
5
+ 只是 ``CudaBackend()`` 会带着明确原因失败。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import importlib.util
11
+
12
+ from .backend import BF16_OPS, CUDA_OPS, CudaBackend
13
+
14
+ CUDA_AVAILABLE = importlib.util.find_spec("cupy") is not None
15
+
16
+ __all__ = ["CudaBackend", "CUDA_OPS", "BF16_OPS", "CUDA_AVAILABLE"]