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,1023 @@
|
|
|
1
|
+
"""CUDA 后端插件:只放厂商相关的部分。
|
|
2
|
+
|
|
3
|
+
执行计划(分块、融合分组、调优、``_op_*`` 派发)在 ``..device_backend``,
|
|
4
|
+
HIP 与 CUDA 是兄弟关系而不是父子关系。这里留下的是只有 NVIDIA 才成立的
|
|
5
|
+
东西:cuBLAS、cuDNN、cupy 的 pinned 缓冲与内存池、CUDA Graph 捕获。
|
|
6
|
+
|
|
7
|
+
``CUDA_OPS`` 仍然定义在这里而不是基类:能力面属于厂商声明,HIP 将来若要
|
|
8
|
+
收窄,改自己的那份即可,不必动这里的代码。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import time
|
|
15
|
+
from contextlib import contextmanager, nullcontext
|
|
16
|
+
from typing import Any, Dict, FrozenSet, List, Mapping, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from ...ir.graph import Node
|
|
21
|
+
from ...ir.ops import fft_axes
|
|
22
|
+
from ...lower.plan import CONV_CUDNN_MIN_GFLOPS
|
|
23
|
+
from ...runtime.executor import _HostCopy
|
|
24
|
+
from ..base import BackendCapabilityError
|
|
25
|
+
from ..contracts import DeviceInfo
|
|
26
|
+
from ..device_backend import DeviceBackend, GPU_OPS
|
|
27
|
+
from ..kernel_cache import KernelCache, kernel_cache_key
|
|
28
|
+
from . import codegen
|
|
29
|
+
from .cublas import Cublas
|
|
30
|
+
from .cudnn import CudnnConv, CudnnUnavailable
|
|
31
|
+
from .cufft import CufftPlan, CufftUnavailable, available as cufft_available
|
|
32
|
+
from .cusparse import CusparseSpMM, CusparseUnavailable
|
|
33
|
+
from .memory import Arena
|
|
34
|
+
|
|
35
|
+
# 类级能力声明。它存在的唯一理由:**不建 CUDA 上下文也能读到**。构图的工具、
|
|
36
|
+
# 预检脚本、"这张图这个后端接不接得住"的判断,都不该为了问一句能力而初始化
|
|
37
|
+
# 一块显卡。运行期的事实来源是 ``self.kernels``;构造时两者对账,不一致直接
|
|
38
|
+
# 抛错(见 ``_register_kernels``),所以不存在"声明与实现分叉"的中间状态。
|
|
39
|
+
CUDA_OPS: FrozenSet[str] = GPU_OPS
|
|
40
|
+
|
|
41
|
+
# bf16 的支持面:先开"逐元素 + 搬运 + 归约 + 矩阵乘"这四类,覆盖 Transformer
|
|
42
|
+
# 推理的主干。卷积 / 池化 / scan / sparse 仍留在 f32/f16——它们的内核里有权重
|
|
43
|
+
# 布局与分块假设,bf16 版本要逐个验证数值,不能只靠模板替换就宣布支持。
|
|
44
|
+
# 不在表里的 bf16 算子会被 ``invoke`` 明确拒绝(不做隐式降级)。
|
|
45
|
+
BF16_OPS: FrozenSet[str] = frozenset({
|
|
46
|
+
"add", "sub", "mul", "div", "eq", "ne", "lt", "le", "gt", "ge", "where",
|
|
47
|
+
"relu", "silu", "exp", "log", "sqrt", "sin", "cos", "neg",
|
|
48
|
+
"tanh", "sigmoid", "erf", "gelu", "clamp", "step", "spike",
|
|
49
|
+
"sign", "round", "floor", "ceil",
|
|
50
|
+
"constant", "cast", "broadcast_to", "reshape", "transpose", "slice",
|
|
51
|
+
"concat", "pad",
|
|
52
|
+
"matmul",
|
|
53
|
+
"softmax", "layernorm", "rmsnorm",
|
|
54
|
+
"reduce_sum", "reduce_max", "reduce_mean",
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
_CONV_IMPLS = (
|
|
58
|
+
"auto", "im2col", "tiled", "implicit", "winograd", "winograd_fused",
|
|
59
|
+
"cudnn", "grouped",
|
|
60
|
+
)
|
|
61
|
+
_SPARSE_IMPLS = ("custom", "auto", "cusparse")
|
|
62
|
+
|
|
63
|
+
# fft / rfft 由 cuFFT 承接。它们不在 ``CUDA_OPS`` 里:那张表是"自研内核模板
|
|
64
|
+
# 承接面"的声明,而 FFT 没有自研内核——它是厂商库能力,与 cuDNN 一样只作为
|
|
65
|
+
# 实现细节存在。``invoke`` 在 dtype 门禁之前拦下这两个名字。
|
|
66
|
+
_FFT_OPS: FrozenSet[str] = frozenset({"fft", "rfft"})
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class CudaBackend(DeviceBackend):
|
|
70
|
+
"""NVIDIA 上的后端。构造失败时抛出带原因的错误,不静默退回 CPU。"""
|
|
71
|
+
|
|
72
|
+
name = "cuda"
|
|
73
|
+
GEMM_TRANSPOSE = True
|
|
74
|
+
_LABEL = "CUDA 后端"
|
|
75
|
+
_OPS = CUDA_OPS
|
|
76
|
+
_BF16_OPS = BF16_OPS
|
|
77
|
+
CONV_IMPLS = _CONV_IMPLS
|
|
78
|
+
SPARSE_IMPLS = _SPARSE_IMPLS
|
|
79
|
+
# 中等 K 的 3x3/5x5 交给隐式 GEMM:A800 上比 im2col 快 7~13%(5.252)。
|
|
80
|
+
# 与 HIP 的整体开关不同,这里的甜点区有物化规模与 K 上界,具体判据在
|
|
81
|
+
# ``plan.conv_implicit_preferred``。
|
|
82
|
+
CONV_AUTO_IMPLICIT_MID = True
|
|
83
|
+
# 3x3/stride1/dilation1 且 K 超过分块阈值时改走 Winograd:A800 上
|
|
84
|
+
# 0.133~0.136 ms,同形状 im2col 0.16~0.31 ms(5.255)。判据在
|
|
85
|
+
# ``plan.conv_winograd_preferred``。
|
|
86
|
+
CONV_AUTO_WINOGRAD = True
|
|
87
|
+
# W8A8 的点积走 ``__dp4a``:sm_61+ 的 4 路 int8 乘加指令,V100(sm_70)
|
|
88
|
+
# 与 A800(sm_80)都支持。HIP 的 hipRTC 不带 ``hip_runtime.h``,保持
|
|
89
|
+
# 标量乘加;两条路都是精确整数运算,累加结果逐位相同。
|
|
90
|
+
_I8A8_DOT4 = True
|
|
91
|
+
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
block: Optional[int] = None,
|
|
95
|
+
max_blocks: int = 1024,
|
|
96
|
+
conv_impl: str = "auto",
|
|
97
|
+
graph_mode: str = "off",
|
|
98
|
+
max_graph_plans: int = 4,
|
|
99
|
+
min_graph_nodes: int = 2,
|
|
100
|
+
chunked_scan: Optional[int] = None,
|
|
101
|
+
memory_mode: str = "container",
|
|
102
|
+
sparse_impl: str = "custom",
|
|
103
|
+
device: int = 0,
|
|
104
|
+
) -> None:
|
|
105
|
+
import cupy as cp # 延迟导入:没有 CUDA 的机器上仍可 import 本模块
|
|
106
|
+
|
|
107
|
+
self.cp = cp
|
|
108
|
+
# 编译产物按「源码 + 架构 + NVRTC 版本」落盘:同一台机器第二次启动
|
|
109
|
+
# 不再调 NVRTC。缓存只加速,损坏或不可写时自动退回编译。
|
|
110
|
+
self._kernel_cache = KernelCache()
|
|
111
|
+
# 方言由实例持有:HIP 插件复用同一批模板,只把 f16 的存取换成
|
|
112
|
+
# clang 的 `_Float16`。放在实例上而不是模块全局,两个后端才能同时
|
|
113
|
+
# 存在而不互相污染。
|
|
114
|
+
self.codegen = codegen
|
|
115
|
+
# 先选卡再问属性:SM 数是**当前设备**的属性,顺序反了就会拿 0 号卡
|
|
116
|
+
# 的数值去铺别的卡。越界索引在这里显式报错,不留到第一次分配。
|
|
117
|
+
count = int(cp.cuda.runtime.getDeviceCount())
|
|
118
|
+
if isinstance(device, bool) or not isinstance(device, int):
|
|
119
|
+
raise BackendCapabilityError(f"设备索引必须是 int,收到 {device!r}")
|
|
120
|
+
if not 0 <= device < count:
|
|
121
|
+
raise BackendCapabilityError(
|
|
122
|
+
f"设备索引 {device} 越界:进程可见 {count} 块设备(0..{count - 1})"
|
|
123
|
+
)
|
|
124
|
+
cp.cuda.Device(device).use()
|
|
125
|
+
# 自动 block 的目标块数:一块 SM 至少排到一个块。查设备属性是一次
|
|
126
|
+
# 主机侧查询,构造时就做完,捕获期不再查。
|
|
127
|
+
self.sm_count = max(
|
|
128
|
+
1,
|
|
129
|
+
int(
|
|
130
|
+
cp.cuda.runtime.getDeviceProperties(device)["multiProcessorCount"]
|
|
131
|
+
),
|
|
132
|
+
)
|
|
133
|
+
# pinned 暂存池:捕获后的 replay 靠它把 H2D 变成真异步(见 pinned_array)
|
|
134
|
+
self._pinned: Dict[Tuple[str, Tuple[int, ...], np.dtype], np.ndarray] = {}
|
|
135
|
+
# 执行期分层分配器;只在显式 memory_mode="tiered" 时惰性创建
|
|
136
|
+
self._tiered: Any = None
|
|
137
|
+
# cuDNN 惰性创建;_cudnn_broken 存"第一次失败的原因",非空就不再重试
|
|
138
|
+
self._cudnn: Any = None
|
|
139
|
+
self._cudnn_broken: Optional[str] = None
|
|
140
|
+
# cuSPARSE 同样惰性创建;失败原因只记一次,auto 下不反复 try/except
|
|
141
|
+
self._cusparse: Any = None
|
|
142
|
+
self._cusparse_broken: Optional[str] = None
|
|
143
|
+
# cuFFT 同样是惰性创建 + 失败只记一次
|
|
144
|
+
self._cufft: Any = None
|
|
145
|
+
self._cufft_broken: Optional[str] = None
|
|
146
|
+
super().__init__(
|
|
147
|
+
block=block,
|
|
148
|
+
max_blocks=max_blocks,
|
|
149
|
+
conv_impl=conv_impl,
|
|
150
|
+
graph_mode=graph_mode,
|
|
151
|
+
max_graph_plans=max_graph_plans,
|
|
152
|
+
min_graph_nodes=min_graph_nodes,
|
|
153
|
+
chunked_scan=chunked_scan,
|
|
154
|
+
memory_mode=memory_mode,
|
|
155
|
+
sparse_impl=sparse_impl,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
def _memory_scope(self):
|
|
159
|
+
"""执行期分层内存:把 cupy 的分配器临时换成本后端的 ``Arena``。
|
|
160
|
+
|
|
161
|
+
``Arena`` 本来就是捕获期用的分层分配器——chunk 切分、best-fit、相邻
|
|
162
|
+
块合并,返回值是 cupy 分配器接口要求的 ``MemoryPointer``(底层的
|
|
163
|
+
``UnownedMemory`` 正是为此留的)。执行期复用它有两个直接后果:
|
|
164
|
+
|
|
165
|
+
- ``run`` 固定用 ``release=True``,``dispose`` 会把不再被读的中间值
|
|
166
|
+
立刻还给 arena,峰值因此接近"这张图的显存下界",而不是"所有中间值
|
|
167
|
+
同时活着";
|
|
168
|
+
- 统计口径与捕获期完全一致:``memory_stats()`` 读到的是最近一次的
|
|
169
|
+
arena 快照,不需要区分"这是哪一段的峰值"。
|
|
170
|
+
|
|
171
|
+
进程级的 ``set_allocator`` 必须严格成对还原——捕获期用的是同一套
|
|
172
|
+
机制(``capture`` 里 install/restore)。
|
|
173
|
+
"""
|
|
174
|
+
if self.memory_mode != "tiered":
|
|
175
|
+
return nullcontext()
|
|
176
|
+
cp = self.cp
|
|
177
|
+
if self._tiered is None:
|
|
178
|
+
self._tiered = Arena(cp)
|
|
179
|
+
previous = cp.cuda.get_allocator()
|
|
180
|
+
|
|
181
|
+
@contextmanager
|
|
182
|
+
def scope():
|
|
183
|
+
cp.cuda.set_allocator(self._tiered.malloc)
|
|
184
|
+
self._active_arena = self._tiered
|
|
185
|
+
try:
|
|
186
|
+
yield
|
|
187
|
+
finally:
|
|
188
|
+
self._active_arena = None
|
|
189
|
+
cp.cuda.set_allocator(previous)
|
|
190
|
+
self._last_arena = self._tiered
|
|
191
|
+
|
|
192
|
+
return scope()
|
|
193
|
+
|
|
194
|
+
def pinned_array(self, key: str, arr: np.ndarray, dtype: np.dtype) -> np.ndarray:
|
|
195
|
+
"""把主机数组拷进一块复用的 pinned 缓冲,返回它的 numpy 视图。
|
|
196
|
+
|
|
197
|
+
直接 ``buf.set(pageable_array)`` 会退化成同步拷贝:主机要等这次 H2D
|
|
198
|
+
真正完成才能继续,CUDA Graph 省下来的下发时间又被这一次等待吃掉。
|
|
199
|
+
先拷进 pinned 内存(几微秒的 CPU 拷贝),H2D 才是真异步的。
|
|
200
|
+
|
|
201
|
+
缓冲按 ``(key, 形状, dtype)`` 复用:训练里的输入形状固定,种类有限。
|
|
202
|
+
调用方要保证上一轮拷贝已经同步过(``run`` / ``run_device`` 都会同步),
|
|
203
|
+
否则会覆盖正在传输的内容。
|
|
204
|
+
"""
|
|
205
|
+
shape = tuple(arr.shape)
|
|
206
|
+
ident = (key, shape, np.dtype(dtype))
|
|
207
|
+
count = int(np.prod(shape, dtype=np.int64))
|
|
208
|
+
view = self._pinned.get(ident)
|
|
209
|
+
if view is None:
|
|
210
|
+
nbytes = max(count * np.dtype(dtype).itemsize, 1)
|
|
211
|
+
mem = self.cp.cuda.alloc_pinned_memory(nbytes)
|
|
212
|
+
view = np.frombuffer(mem, dtype=dtype, count=count).reshape(shape)
|
|
213
|
+
self._pinned[ident] = view
|
|
214
|
+
np.copyto(view, arr, casting="unsafe")
|
|
215
|
+
return view
|
|
216
|
+
|
|
217
|
+
def _host_copy(self, value: Any, stream: Any) -> Any:
|
|
218
|
+
"""pinned 缓冲上的异步 D2H,不等拷贝完成。
|
|
219
|
+
|
|
220
|
+
D2H 只有落在 pinned 内存上才是真异步:普通页内存要求驱动在拷贝期间
|
|
221
|
+
锁页,主机线程会一直等到传输结束。这里每次分配一块(张量小、cupy 的
|
|
222
|
+
pinned 分配器有缓存),``dest[...] = value`` 在**指定流**上排队,
|
|
223
|
+
句柄里记一个事件,``value()`` 才同步。
|
|
224
|
+
|
|
225
|
+
必须用调用方给的流:replay 排在自定义流上时,默认流上的拷贝与它之间
|
|
226
|
+
没有任何顺序保证,读到的会是上一轮的内容。
|
|
227
|
+
"""
|
|
228
|
+
cp = self.cp
|
|
229
|
+
if not isinstance(value, cp.ndarray):
|
|
230
|
+
return None
|
|
231
|
+
nbytes = max(int(value.nbytes), 1)
|
|
232
|
+
host = cp.cuda.alloc_pinned_memory(nbytes)
|
|
233
|
+
view = np.frombuffer(host, dtype=value.dtype, count=value.size).reshape(
|
|
234
|
+
value.shape
|
|
235
|
+
)
|
|
236
|
+
target = cp.cuda.get_current_stream() if stream is None else stream
|
|
237
|
+
# 直接调 runtime 的 memcpyAsync,而不是 ``dest[...] = value``:pinned
|
|
238
|
+
# 指针不能塞进 ``cp.ndarray``(``alloc_pinned_memory`` 给的是
|
|
239
|
+
# PinnedMemoryPointer,``ndarray`` 只收 MemoryPointer),而这次拷贝
|
|
240
|
+
# 本来也不需要数组语义——只要"源地址、目标地址、字节数、流"。
|
|
241
|
+
cp.cuda.runtime.memcpyAsync(
|
|
242
|
+
int(host.ptr), int(value.data.ptr), nbytes,
|
|
243
|
+
cp.cuda.runtime.memcpyDeviceToHost, int(target.ptr),
|
|
244
|
+
)
|
|
245
|
+
return _HostCopy(view, target.record())
|
|
246
|
+
|
|
247
|
+
def dispose(self, value: Any) -> None:
|
|
248
|
+
"""把中间值的地址立刻还给 arena(只在捕获期有效)。
|
|
249
|
+
|
|
250
|
+
cupy 14 的 ``MemoryPointer`` 析构时不会回调自定义分配器,所以
|
|
251
|
+
arena 的回收点只能由执行器显式给出。非捕获期是空操作。
|
|
252
|
+
|
|
253
|
+
``reshape`` / ``transpose`` / ``slice`` 的输出是共享底层缓冲的视图。
|
|
254
|
+
视图不拥有内存,所以这里不能按地址还块:源数组的回收要等最后一个
|
|
255
|
+
视图死掉。两个方向都靠 ``Arena`` 的引用计数兜住——创建视图时
|
|
256
|
+
``alias`` 记账,这里 ``unalias`` 扣账,源数组的 ``free`` 记账成"待回收"。
|
|
257
|
+
|
|
258
|
+
扣账必须用**最底层源数组**的地址:``alias`` 登记的是它,而视图的
|
|
259
|
+
``data.ptr`` 是"源地址 + 偏移"——slice 从第 2 行开始时两者不等,
|
|
260
|
+
按视图自己的地址扣账会一条也匹配不上,源地址就永久挂住。
|
|
261
|
+
"""
|
|
262
|
+
arena = self._active_arena
|
|
263
|
+
if arena is None or not isinstance(value, self.cp.ndarray):
|
|
264
|
+
return
|
|
265
|
+
base = value.base
|
|
266
|
+
if base is not None:
|
|
267
|
+
while base.base is not None:
|
|
268
|
+
base = base.base
|
|
269
|
+
arena.unalias(base.data)
|
|
270
|
+
return
|
|
271
|
+
if arena.pending(value.data):
|
|
272
|
+
# 整段切片 / 同形状 reshape 返回的就是源数组本身,但执行器看到
|
|
273
|
+
# 两条 Value:第一次 dispose 已把地址记成待回收,这一次扣掉自己
|
|
274
|
+
# 那份视图登记,而不是把 free 再走一遍(那样永远不归零)。
|
|
275
|
+
arena.unalias(value.data)
|
|
276
|
+
return
|
|
277
|
+
arena.free(value.data, value.nbytes)
|
|
278
|
+
|
|
279
|
+
# ------------------------------------------------------------------
|
|
280
|
+
# 设备驻留
|
|
281
|
+
# ------------------------------------------------------------------
|
|
282
|
+
|
|
283
|
+
def device_info(self) -> DeviceInfo:
|
|
284
|
+
"""``DeviceContract``:这块设备是什么。
|
|
285
|
+
|
|
286
|
+
只报三项:名字、CUDA 运行时版本、显存总量。多设备选择、stream 管理
|
|
287
|
+
在 ``DeviceManagerContract`` 与 ``StreamContract`` 里,不混进来。
|
|
288
|
+
"""
|
|
289
|
+
cp = self.cp
|
|
290
|
+
index = int(cp.cuda.Device().id)
|
|
291
|
+
props = cp.cuda.runtime.getDeviceProperties(index)
|
|
292
|
+
name = props["name"]
|
|
293
|
+
return DeviceInfo(
|
|
294
|
+
name=name.decode() if isinstance(name, bytes) else name,
|
|
295
|
+
runtime=cp.cuda.runtime.runtimeGetVersion(),
|
|
296
|
+
total_memory_bytes=cp.cuda.Device(index).mem_info[1],
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
def enumerate_devices(self) -> Tuple[DeviceInfo, ...]:
|
|
300
|
+
"""``DeviceManagerContract``:按索引顺序列出全部设备。
|
|
301
|
+
|
|
302
|
+
``mem_info`` 只认当前设备,所以每块卡都在自己的上下文里读;``with``
|
|
303
|
+
退出时会还原到调用前的设备,枚举本身不改变"现在用哪块卡"。
|
|
304
|
+
"""
|
|
305
|
+
cp = self.cp
|
|
306
|
+
version = cp.cuda.runtime.runtimeGetVersion()
|
|
307
|
+
devices = []
|
|
308
|
+
for index in range(int(cp.cuda.runtime.getDeviceCount())):
|
|
309
|
+
props = cp.cuda.runtime.getDeviceProperties(index)
|
|
310
|
+
name = props["name"]
|
|
311
|
+
with cp.cuda.Device(index):
|
|
312
|
+
total = cp.cuda.Device(index).mem_info[1]
|
|
313
|
+
devices.append(
|
|
314
|
+
DeviceInfo(
|
|
315
|
+
name=name.decode() if isinstance(name, bytes) else name,
|
|
316
|
+
runtime=version,
|
|
317
|
+
total_memory_bytes=total,
|
|
318
|
+
)
|
|
319
|
+
)
|
|
320
|
+
return tuple(devices)
|
|
321
|
+
|
|
322
|
+
def current_device(self) -> int:
|
|
323
|
+
return int(self.cp.cuda.Device().id)
|
|
324
|
+
|
|
325
|
+
def set_device(self, index: int) -> None:
|
|
326
|
+
"""切换当前设备,并让自动 block 的 SM 数跟着换。"""
|
|
327
|
+
cp = self.cp
|
|
328
|
+
count = int(cp.cuda.runtime.getDeviceCount())
|
|
329
|
+
if isinstance(index, bool) or not isinstance(index, int):
|
|
330
|
+
raise BackendCapabilityError(f"设备索引必须是 int,收到 {index!r}")
|
|
331
|
+
if not 0 <= index < count:
|
|
332
|
+
raise BackendCapabilityError(
|
|
333
|
+
f"设备索引 {index} 越界:进程可见 {count} 块设备(0..{count - 1})"
|
|
334
|
+
)
|
|
335
|
+
previous = int(cp.cuda.Device().id)
|
|
336
|
+
if index != previous and self._tiered is not None:
|
|
337
|
+
# 分层池的块属于旧卡:必须在旧 context 里 free,切走之后
|
|
338
|
+
# runtime.free 会落到新卡的上下文上。
|
|
339
|
+
self._tiered.close()
|
|
340
|
+
self._tiered = None
|
|
341
|
+
cp.cuda.Device(index).use()
|
|
342
|
+
self.sm_count = max(
|
|
343
|
+
1,
|
|
344
|
+
int(cp.cuda.runtime.getDeviceProperties(index)["multiProcessorCount"]),
|
|
345
|
+
)
|
|
346
|
+
if index == previous:
|
|
347
|
+
return
|
|
348
|
+
# 换卡之后旧设备上的一切都不能再用:NVRTC 编译出的模块绑在编译时的
|
|
349
|
+
# context,cuBLAS handle 绑在设备,驻留数组带 device id,捕获计划里的
|
|
350
|
+
# 地址属于旧卡的内存池。不清掉就会"在新卡上执行旧计划",报错点离
|
|
351
|
+
# 真正的原因很远。驻留参数直接清空:它们本来就在旧卡的显存里,
|
|
352
|
+
# 保留一个跨设备的数组只会把错误推迟到下一次 execute。
|
|
353
|
+
self._modules.clear()
|
|
354
|
+
self._functions.clear()
|
|
355
|
+
self._kernel_handles.clear()
|
|
356
|
+
self._blas = None
|
|
357
|
+
self._blas_workspace = None
|
|
358
|
+
# cuSPARSE handle 与 workspace 都绑在旧卡的 context 上,和 cuBLAS 同理
|
|
359
|
+
self._cusparse = None
|
|
360
|
+
# cuFFT 的 plan 绑在旧卡的 context 上
|
|
361
|
+
if self._cufft is not None:
|
|
362
|
+
self._cufft.close()
|
|
363
|
+
self._cufft = None
|
|
364
|
+
self._resident.clear()
|
|
365
|
+
self._invalidate_plans()
|
|
366
|
+
# 计划里缓存的常量设备副本也属于旧卡(5.172):计划结构照旧有效,
|
|
367
|
+
# 但里面的地址不能再用,清掉值,下次执行在计划重建时重新上传。
|
|
368
|
+
self._clear_plan_values()
|
|
369
|
+
|
|
370
|
+
def allocator(self) -> Arena:
|
|
371
|
+
"""``MemoryContract``:新建一个捕获期分配器(``AllocatorContract``)。
|
|
372
|
+
|
|
373
|
+
每次捕获都要一个新的:arena 里切出来的地址被写死进图,两张图共用
|
|
374
|
+
一个 arena 就会让各自的中间值互相踩。所以这里是工厂,不是缓存。
|
|
375
|
+
"""
|
|
376
|
+
return Arena(self.cp)
|
|
377
|
+
|
|
378
|
+
def _cudnn_engine(self):
|
|
379
|
+
"""惰性建 cuDNN handle;失败一次就不再重试。
|
|
380
|
+
|
|
381
|
+
"失败只试一次"很关键:每步都 try/except 会把派发常数抬回去,而缺少
|
|
382
|
+
cuDNN 的机器上这个异常是**必然**发生的。失败原因留在 ``_cudnn_broken``
|
|
383
|
+
里,显式 ``conv_impl="cudnn"`` 时用它报一条能看懂的错。
|
|
384
|
+
"""
|
|
385
|
+
if self._cudnn is not None:
|
|
386
|
+
return self._cudnn
|
|
387
|
+
if self._cudnn_broken:
|
|
388
|
+
return None
|
|
389
|
+
try:
|
|
390
|
+
self._cudnn = CudnnConv()
|
|
391
|
+
except (CudnnUnavailable, OSError, AttributeError) as exc:
|
|
392
|
+
# AttributeError 是"库在、符号没了":cuDNN 版本不匹配时
|
|
393
|
+
# ``CudnnConv.__init__`` 里取 legacy 符号(如
|
|
394
|
+
# ``cudnnGetConvolutionForwardAlgorithm_v7``)会抛它。它和"库不在"
|
|
395
|
+
# 是同一类事实(这台机器用不了这条快路径),auto 必须回落;
|
|
396
|
+
# 漏在这里会让默认 ``conv_impl="auto"`` 在构造期就整体失败。
|
|
397
|
+
if self.conv_impl == "cudnn":
|
|
398
|
+
raise BackendCapabilityError(
|
|
399
|
+
f"{self._LABEL} 的 conv_impl='cudnn' 需要可用的 cuDNN:{exc}"
|
|
400
|
+
) from exc
|
|
401
|
+
self._cudnn_broken = f"{type(exc).__name__}: {exc}"
|
|
402
|
+
return None
|
|
403
|
+
return self._cudnn
|
|
404
|
+
|
|
405
|
+
def _pick_cudnn(self, dtype, groups: int, flops: float = 0.0) -> bool:
|
|
406
|
+
"""这一层 conv 走不走 cuDNN。
|
|
407
|
+
|
|
408
|
+
只覆盖 groups=1 的 f32/f16:分组卷积与 f64 仍走自研路径,不为此多开
|
|
409
|
+
一条只在部分机器上验证过的分支。
|
|
410
|
+
|
|
411
|
+
auto 还要过规模门槛:1 GFLOP 以下 cuDNN 的固定开销(描述符、算法查询、
|
|
412
|
+
独立 bias 核)比省下的卷积时间更贵(5.252)。
|
|
413
|
+
"""
|
|
414
|
+
if groups != 1:
|
|
415
|
+
return False
|
|
416
|
+
supported = np.dtype(dtype) in (np.float32, np.float16)
|
|
417
|
+
if self.conv_impl == "cudnn":
|
|
418
|
+
if not supported:
|
|
419
|
+
raise BackendCapabilityError(
|
|
420
|
+
f"conv_impl='cudnn' 只支持 float32 / float16,收到 {np.dtype(dtype)}"
|
|
421
|
+
)
|
|
422
|
+
if self._capturing:
|
|
423
|
+
raise BackendCapabilityError(
|
|
424
|
+
"CUDA Graph 捕获期不支持 conv_impl='cudnn'(algo 查询是 host API);"
|
|
425
|
+
"捕获请用 conv_impl='auto' 或 'tiled'"
|
|
426
|
+
)
|
|
427
|
+
return True
|
|
428
|
+
if self.conv_impl != "auto" or not supported:
|
|
429
|
+
return False
|
|
430
|
+
if flops < CONV_CUDNN_MIN_GFLOPS:
|
|
431
|
+
return False
|
|
432
|
+
if self._capturing:
|
|
433
|
+
# 捕获期内不换实现:cuDNN 的 algo 查询是 host API,在捕获里调用
|
|
434
|
+
# 不安全,而且"平时走 cuDNN、捕获时走自研核"会让两条路径的数值
|
|
435
|
+
# 与显存布局不一致。捕获要的是路径固定,这里就保持固定。
|
|
436
|
+
return False
|
|
437
|
+
if self._cudnn_broken is not None:
|
|
438
|
+
return False
|
|
439
|
+
return self._cudnn_engine() is not None
|
|
440
|
+
|
|
441
|
+
def _conv2d_cudnn(self, x, weight, bias, *, n, c, h, w, o, kh, kw, ho, wo,
|
|
442
|
+
sh, sw, ph, pw, dh, dw, k):
|
|
443
|
+
"""cuDNN 前向;返回 ``None`` 表示"这一步没走成,请回落"。
|
|
444
|
+
|
|
445
|
+
auto 模式下任何 cuDNN 异常都降级而不是冒泡:使用者要的是"能算对",
|
|
446
|
+
不是"必须用 cuDNN"。显式 ``conv_impl="cudnn"`` 时异常照常抛出,
|
|
447
|
+
否则排障时会被静默换实现误导。
|
|
448
|
+
"""
|
|
449
|
+
cp = self.cp
|
|
450
|
+
engine = self._cudnn_engine()
|
|
451
|
+
if engine is None:
|
|
452
|
+
return None
|
|
453
|
+
out = cp.empty((n, o, ho, wo), dtype=x.dtype)
|
|
454
|
+
try:
|
|
455
|
+
engine.convolution(
|
|
456
|
+
self._contig(x),
|
|
457
|
+
self._contig(weight),
|
|
458
|
+
None if bias is None else self._contig(bias),
|
|
459
|
+
out,
|
|
460
|
+
pad=(ph, pw),
|
|
461
|
+
stride=(sh, sw),
|
|
462
|
+
dilation=(dh, dw),
|
|
463
|
+
)
|
|
464
|
+
except Exception as exc: # noqa: BLE001 —— 见上面的降级说明
|
|
465
|
+
if self.conv_impl == "cudnn":
|
|
466
|
+
raise
|
|
467
|
+
self._cudnn_broken = f"{type(exc).__name__}: {exc}"
|
|
468
|
+
return None
|
|
469
|
+
return out
|
|
470
|
+
|
|
471
|
+
def _cusparse_engine(self):
|
|
472
|
+
"""惰性建 cuSPARSE handle;失败一次就不再重试(与 cuDNN 同一条理由)。"""
|
|
473
|
+
if self._cusparse is not None:
|
|
474
|
+
return self._cusparse
|
|
475
|
+
if self._cusparse_broken:
|
|
476
|
+
return None
|
|
477
|
+
try:
|
|
478
|
+
self._cusparse = CusparseSpMM()
|
|
479
|
+
except (CusparseUnavailable, OSError) as exc:
|
|
480
|
+
if self.sparse_impl == "cusparse":
|
|
481
|
+
raise BackendCapabilityError(
|
|
482
|
+
f"{self._LABEL} 的 sparse_impl='cusparse' 需要可用的 "
|
|
483
|
+
f"cuSPARSE:{exc}"
|
|
484
|
+
) from exc
|
|
485
|
+
self._cusparse_broken = str(exc)
|
|
486
|
+
return None
|
|
487
|
+
return self._cusparse
|
|
488
|
+
|
|
489
|
+
def _pick_cusparse(self, values, indices, offsets) -> bool:
|
|
490
|
+
"""这一次 ``sparse_linear`` 走不走 cuSPARSE。
|
|
491
|
+
|
|
492
|
+
只覆盖登记过的形态:f16 / f32 值 + i32 的 ``indices`` / ``offsets``。
|
|
493
|
+
``auto`` 在捕获期与库缺失时回落到自研核;显式 ``cusparse`` 则把
|
|
494
|
+
这两种情况变成明确错误,而不是"悄悄换了个实现"。
|
|
495
|
+
|
|
496
|
+
**不覆盖越界检查**:自研核在设备端记 ``err`` 后由主机侧抛错,库不做
|
|
497
|
+
逐元素检查。因此显式走库路径时,下标合法性回到调用方责任——这也是
|
|
498
|
+
默认值仍是 ``custom`` 的原因。
|
|
499
|
+
"""
|
|
500
|
+
supported = (
|
|
501
|
+
np.dtype(values.dtype) in (np.dtype("float16"), np.dtype("float32"))
|
|
502
|
+
and np.dtype(indices.dtype) == np.dtype("int32")
|
|
503
|
+
and np.dtype(offsets.dtype) == np.dtype("int32")
|
|
504
|
+
)
|
|
505
|
+
if self.sparse_impl == "cusparse":
|
|
506
|
+
if not supported:
|
|
507
|
+
raise BackendCapabilityError(
|
|
508
|
+
"sparse_impl='cusparse' 只支持 float16/float32 值 + int32 索引,"
|
|
509
|
+
f"收到 values={np.dtype(values.dtype)}、"
|
|
510
|
+
f"indices={np.dtype(indices.dtype)}、"
|
|
511
|
+
f"offsets={np.dtype(offsets.dtype)}"
|
|
512
|
+
)
|
|
513
|
+
if self._capturing:
|
|
514
|
+
raise BackendCapabilityError(
|
|
515
|
+
"CUDA Graph 捕获期不支持 sparse_impl='cusparse'"
|
|
516
|
+
"(SpMM 的 workspace 查询是 host API);"
|
|
517
|
+
"捕获请用 sparse_impl='auto' 或 'custom'"
|
|
518
|
+
)
|
|
519
|
+
return True
|
|
520
|
+
if self.sparse_impl != "auto" or not supported:
|
|
521
|
+
return False
|
|
522
|
+
if self._capturing or self._cusparse_broken is not None:
|
|
523
|
+
return False
|
|
524
|
+
return self._cusparse_engine() is not None
|
|
525
|
+
|
|
526
|
+
def _sparse_linear_cusparse(self, weights, indices, values, offsets, *,
|
|
527
|
+
steps: int, rows: int, cols: int):
|
|
528
|
+
"""cuSPARSE SpMM;返回 ``None`` 表示"没走成,请回落"。
|
|
529
|
+
|
|
530
|
+
与 cuDNN 的 ``_conv2d_cudnn`` 同一条策略:auto 模式下任何异常都
|
|
531
|
+
降级(先把 ``_cusparse_broken`` 记下来,后续步骤不再重试),显式
|
|
532
|
+
``cusparse`` 时异常照常抛出。失败时已经写进 ``out`` 的内容不会被
|
|
533
|
+
使用——调用方会重新走自研核,那条路先把输出清零。
|
|
534
|
+
"""
|
|
535
|
+
engine = self._cusparse_engine()
|
|
536
|
+
if engine is None:
|
|
537
|
+
return None
|
|
538
|
+
try:
|
|
539
|
+
return engine.spmm(
|
|
540
|
+
offsets, indices, values, weights,
|
|
541
|
+
steps=steps, rows=rows, cols=cols,
|
|
542
|
+
)
|
|
543
|
+
except Exception as exc: # noqa: BLE001 —— 见上面的降级说明
|
|
544
|
+
if self.sparse_impl == "cusparse":
|
|
545
|
+
raise
|
|
546
|
+
self._cusparse_broken = f"{type(exc).__name__}: {exc}"
|
|
547
|
+
return None
|
|
548
|
+
|
|
549
|
+
# ------------------------------------------------------------------
|
|
550
|
+
# cuFFT
|
|
551
|
+
# ------------------------------------------------------------------
|
|
552
|
+
|
|
553
|
+
def _cufft_engine(self) -> CufftPlan:
|
|
554
|
+
"""惰性建 cuFFT plan 池;失败一次就不再重试(与 cuDNN 同一条理由)。
|
|
555
|
+
|
|
556
|
+
``fft`` / ``rfft`` 没有自研内核可回落,所以这里不设"auto 降级":
|
|
557
|
+
库不可用就是明确错误。捕获期单独拒绝——``cufftPlanMany`` 是 host API,
|
|
558
|
+
在 CUDA Graph 捕获里调用不安全。
|
|
559
|
+
"""
|
|
560
|
+
if self._cufft is not None:
|
|
561
|
+
return self._cufft
|
|
562
|
+
if self._cufft_broken:
|
|
563
|
+
raise BackendCapabilityError(
|
|
564
|
+
f"{self._LABEL} 的 fft/rfft 需要可用的 cuFFT:{self._cufft_broken}"
|
|
565
|
+
)
|
|
566
|
+
if self._capturing:
|
|
567
|
+
raise BackendCapabilityError(
|
|
568
|
+
"CUDA Graph 捕获期不支持 fft/rfft(cufftPlanMany 是 host API);"
|
|
569
|
+
"含 FFT 的图请用 graph_mode='off'"
|
|
570
|
+
)
|
|
571
|
+
try:
|
|
572
|
+
self._cufft = CufftPlan()
|
|
573
|
+
except (CufftUnavailable, OSError) as exc:
|
|
574
|
+
self._cufft_broken = str(exc)
|
|
575
|
+
raise BackendCapabilityError(
|
|
576
|
+
f"{self._LABEL} 的 fft/rfft 需要可用的 cuFFT:{exc}"
|
|
577
|
+
) from exc
|
|
578
|
+
return self._cufft
|
|
579
|
+
|
|
580
|
+
def invoke(self, node: Node, args: List[Any], attrs: dict) -> Any:
|
|
581
|
+
"""``fft`` / ``rfft`` 走 cuFFT,其余交给基类。
|
|
582
|
+
|
|
583
|
+
这两个算子的输入 dtype(c64 / c128 / f32 / f64)不在基类的"f32 或
|
|
584
|
+
f16"门禁里,必须在门禁之前拦下。dtype 与形状仍按 IR 声明核对:
|
|
585
|
+
入口已在 ``run_device`` 对齐过,这里再确认一次是为了让"直接调
|
|
586
|
+
``invoke``"的路径同样严格。
|
|
587
|
+
"""
|
|
588
|
+
name = node.op.name
|
|
589
|
+
if name not in _FFT_OPS:
|
|
590
|
+
return super().invoke(node, args, attrs)
|
|
591
|
+
x = self._contig(args[0])
|
|
592
|
+
if x.dtype != np.dtype(node.inputs[0].type.dtype.np_dtype):
|
|
593
|
+
raise BackendCapabilityError(
|
|
594
|
+
f"{self._LABEL} 的 {name} 输入 dtype {x.dtype} 与 IR 声明的 "
|
|
595
|
+
f"{node.inputs[0].type.dtype.value} 不一致"
|
|
596
|
+
)
|
|
597
|
+
axes = fft_axes(x.ndim, attrs)
|
|
598
|
+
sizes = tuple(int(x.shape[axis]) for axis in axes)
|
|
599
|
+
total = 1
|
|
600
|
+
for size in sizes:
|
|
601
|
+
total *= size
|
|
602
|
+
rows = int(x.size // total) if total else 0
|
|
603
|
+
inverse = bool(attrs.get("inverse", False)) if name == "fft" else False
|
|
604
|
+
return self._cufft_engine().transform(
|
|
605
|
+
x,
|
|
606
|
+
sizes=sizes,
|
|
607
|
+
rows=rows,
|
|
608
|
+
inverse=inverse,
|
|
609
|
+
norm=attrs.get("norm", "backward"),
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
def capabilities(self) -> FrozenSet[str]:
|
|
613
|
+
"""自研内核 + 可用的 cuFFT。
|
|
614
|
+
|
|
615
|
+
``fft`` / ``rfft`` 不是内核表里的条目,但能力声明必须如实反映"这个
|
|
616
|
+
后端能不能算"。cuFFT 缺失时**不声明**:宁可让一致性套件把它记为
|
|
617
|
+
"未声明算子"从而拒绝,也不要声明一个执行时才失败的算子。
|
|
618
|
+
"""
|
|
619
|
+
caps = super().capabilities()
|
|
620
|
+
if cufft_available():
|
|
621
|
+
return caps | _FFT_OPS
|
|
622
|
+
return caps
|
|
623
|
+
|
|
624
|
+
# ------------------------------------------------------------------
|
|
625
|
+
# 编译与 BLAS
|
|
626
|
+
# ------------------------------------------------------------------
|
|
627
|
+
|
|
628
|
+
def _kernel(self, key: Any, source, func: str):
|
|
629
|
+
# 连函数句柄一起缓存:``get_function`` 本身有可观的 Python 开销,
|
|
630
|
+
# 而这一段在每次 execute 的每个节点上都会走到。
|
|
631
|
+
#
|
|
632
|
+
# ``source`` 允许是"返回源码的函数":源码生成(L2 → C)比编译便宜,
|
|
633
|
+
# 但同样在每一步重复——conv2d 一次 0.4 ms,逐元素链上叠得更多;
|
|
634
|
+
# 传函数进来,命中缓存时连源码都不会生成了。
|
|
635
|
+
fn = self._functions.get(key)
|
|
636
|
+
if fn is None:
|
|
637
|
+
text = source() if callable(source) else source
|
|
638
|
+
module = self._load_module(text)
|
|
639
|
+
fn = module.get_function(func)
|
|
640
|
+
self._modules[key] = module
|
|
641
|
+
self._functions[key] = fn
|
|
642
|
+
return fn
|
|
643
|
+
|
|
644
|
+
def _load_module(self, text: str):
|
|
645
|
+
"""编译并装载一个源码模块,命中磁盘缓存时不再调 NVRTC。
|
|
646
|
+
|
|
647
|
+
产物是 cubin(SASS),与设备架构、NVRTC 版本强绑定——两者都进缓存
|
|
648
|
+
键;换卡或升级 CUDA 后旧条目自然失效,不会装出非法指令。架构按
|
|
649
|
+
"当前设备"取,和原先 ``RawModule`` 的默认行为一致。
|
|
650
|
+
"""
|
|
651
|
+
arch = str(self.cp.cuda.Device().compute_capability)
|
|
652
|
+
cache_key = kernel_cache_key(
|
|
653
|
+
"cuda", text, "-std=c++11", arch, self._nvrtc_version()
|
|
654
|
+
)
|
|
655
|
+
blob = self._kernel_cache.lookup(cache_key)
|
|
656
|
+
if blob is None:
|
|
657
|
+
blob = self.cp.cuda.compiler.compile_using_nvrtc(
|
|
658
|
+
text, options=("-std=c++11",), arch=arch
|
|
659
|
+
)[0]
|
|
660
|
+
self._kernel_cache.store(cache_key, blob)
|
|
661
|
+
module = self.cp.cuda.function.Module()
|
|
662
|
+
module.load(blob)
|
|
663
|
+
return module
|
|
664
|
+
|
|
665
|
+
def _nvrtc_version(self) -> str:
|
|
666
|
+
major, minor = self.cp.cuda.nvrtc.getVersion()
|
|
667
|
+
return f"{int(major)}.{int(minor)}"
|
|
668
|
+
|
|
669
|
+
def current_stream_ptr(self) -> int:
|
|
670
|
+
"""当前流的地址,供 cuBLAS 绑定。"""
|
|
671
|
+
return int(self.cp.cuda.get_current_stream().ptr)
|
|
672
|
+
|
|
673
|
+
def gpu_clock(self) -> "_CudaGpuClock":
|
|
674
|
+
"""逐节点 GPU 计时的时钟(见 ``runtime/telemetry.py``)。"""
|
|
675
|
+
return _CudaGpuClock(self)
|
|
676
|
+
|
|
677
|
+
def _cublas(self) -> Cublas:
|
|
678
|
+
if self._blas is None:
|
|
679
|
+
try:
|
|
680
|
+
self._blas = Cublas()
|
|
681
|
+
except OSError as exc:
|
|
682
|
+
raise BackendCapabilityError(f"{self._LABEL}无法加载 cuBLAS:{exc}") from exc
|
|
683
|
+
size_mb = int(os.environ.get("AETHERFLOW_CUBLAS_WORKSPACE_MB", "0"))
|
|
684
|
+
if size_mb > 0:
|
|
685
|
+
# 常驻一块 workspace,让图捕获与 eager 走同一条算法路径;
|
|
686
|
+
# 显式请求才会分配,默认不改变原有行为。
|
|
687
|
+
buf = self.cp.zeros(size_mb << 20, dtype=self.cp.uint8)
|
|
688
|
+
self._blas_workspace = buf
|
|
689
|
+
self._blas.set_workspace(int(buf.data.ptr), int(buf.nbytes))
|
|
690
|
+
return self._blas
|
|
691
|
+
|
|
692
|
+
# ------------------------------------------------------------------
|
|
693
|
+
# 运行期计划:CUDA Graph
|
|
694
|
+
# ------------------------------------------------------------------
|
|
695
|
+
|
|
696
|
+
def new_stream(self):
|
|
697
|
+
"""一条非阻塞流:捕获必须发生在非默认流上,replay 也跑在它上面。"""
|
|
698
|
+
return self.cp.cuda.Stream(non_blocking=True)
|
|
699
|
+
|
|
700
|
+
def capture(
|
|
701
|
+
self,
|
|
702
|
+
graph,
|
|
703
|
+
sample_inputs: Mapping[str, Any],
|
|
704
|
+
reuse_memory: bool = True,
|
|
705
|
+
shared_buffers: Optional[Mapping[str, Any]] = None,
|
|
706
|
+
stream: Optional[Any] = None,
|
|
707
|
+
) -> "CudaGraphPlan":
|
|
708
|
+
"""把整张图捕获成一个 CUDA Graph,返回可重复 replay 的计划。
|
|
709
|
+
|
|
710
|
+
``sample_inputs`` 只用于确定形状并写入静态缓冲;捕获后再调
|
|
711
|
+
``plan.run(inputs)`` 只更新输入缓冲、replay 整图,CPU 侧只剩一次
|
|
712
|
+
下发,不再逐节点走 Python。
|
|
713
|
+
|
|
714
|
+
规则与 ``execute`` 一致:名字出现在 ``sample_inputs`` 里的输入视为
|
|
715
|
+
可变(每次 run 都要传),只从设备驻留表取到的输入视为固定(权重)。
|
|
716
|
+
|
|
717
|
+
``reuse_memory`` 打开时用 ``Arena`` 代替 cupy 池:图里的地址是写死的,
|
|
718
|
+
中间张量的复用必须在捕获期完成,否则每个节点都独占一块显存。
|
|
719
|
+
|
|
720
|
+
``shared_buffers`` 直接把这些显存数组当作静态输入缓冲,而不是另申请
|
|
721
|
+
一块再拷一遍。设备态训练靠它让前向、反向两张图共用同一块权重:优化器
|
|
722
|
+
原地改的就是图里写死的那段地址,每步既不需要 H2D 也不需要重捕获。
|
|
723
|
+
计划**不持有**这些数组的所有权,调用方必须让它们活到计划释放为止。
|
|
724
|
+
|
|
725
|
+
``stream`` 缺省时新建一条非阻塞流。同一组图传同一条流时,replay 之间
|
|
726
|
+
天然有序,不必再建跨流事件依赖(激活重算的分段模式就是这样用的)。
|
|
727
|
+
"""
|
|
728
|
+
cp = self.cp
|
|
729
|
+
declared = [v.name for v in graph.inputs]
|
|
730
|
+
shared = dict(shared_buffers or {})
|
|
731
|
+
unknown = sorted(set(shared) - set(declared))
|
|
732
|
+
if unknown:
|
|
733
|
+
raise KeyError(f"shared_buffers 里这些名字不是图输入: {unknown}")
|
|
734
|
+
|
|
735
|
+
buffers: Dict[str, Any] = {}
|
|
736
|
+
mutable: List[str] = []
|
|
737
|
+
pending: List[Tuple[Any, Any]] = []
|
|
738
|
+
for name in declared:
|
|
739
|
+
if name in sample_inputs:
|
|
740
|
+
src = self.to_array(sample_inputs[name])
|
|
741
|
+
mutable.append(name)
|
|
742
|
+
elif name in self._resident:
|
|
743
|
+
src = self._resident[name]
|
|
744
|
+
else:
|
|
745
|
+
raise KeyError(f"capture 缺少图输入: {name}")
|
|
746
|
+
buf = shared.get(name)
|
|
747
|
+
if buf is None:
|
|
748
|
+
# 静态缓冲:捕获记录的是固定地址,之后每次 run 往这里拷新值。
|
|
749
|
+
# 拷贝本身留到预热用的那条流上做——``to_array`` 出来的是主机
|
|
750
|
+
# 数组,在默认流上异步 H2D,非阻塞流上的预热会先读到未就绪的
|
|
751
|
+
# 内存(表现为 embedding 拿随机 ids)。共享缓冲由调用方负责
|
|
752
|
+
# 填好,这里不重复拷。
|
|
753
|
+
buf = cp.empty(src.shape, dtype=src.dtype)
|
|
754
|
+
pending.append((buf, src))
|
|
755
|
+
elif tuple(buf.shape) != tuple(src.shape) or buf.dtype != src.dtype:
|
|
756
|
+
raise ValueError(
|
|
757
|
+
f"共享缓冲 %{name} 的形状/dtype 是 {tuple(buf.shape)}/{buf.dtype},"
|
|
758
|
+
f"与传入值的 {tuple(src.shape)}/{src.dtype} 不一致"
|
|
759
|
+
)
|
|
760
|
+
buffers[name] = buf
|
|
761
|
+
|
|
762
|
+
allocator = self.allocator() if reuse_memory else cp.cuda.MemoryPool()
|
|
763
|
+
previous_allocator = cp.cuda.get_allocator()
|
|
764
|
+
stream = stream if stream is not None else self.new_stream()
|
|
765
|
+
# 静态缓冲的填充必须在换分配器之前完成:``to_array`` 出来的是主机
|
|
766
|
+
# 数组,H2D 在默认流上异步进行,而预热跑在非阻塞流上——不建立这条
|
|
767
|
+
# 依赖,预热会先读到未就绪的内存(表现为 embedding 拿随机 ids)。
|
|
768
|
+
# 放在换分配器之前也让这次 H2D 的临时分配不落进捕获 arena,
|
|
769
|
+
# ``capture_reports_memory_budget`` 的预算因此只反映图本身。
|
|
770
|
+
for buf, src in pending:
|
|
771
|
+
buf[...] = src
|
|
772
|
+
ready = cp.cuda.Event()
|
|
773
|
+
ready.record()
|
|
774
|
+
stream.wait_event(ready)
|
|
775
|
+
cp.cuda.set_allocator(allocator.malloc)
|
|
776
|
+
self._active_arena = allocator if isinstance(allocator, Arena) else None
|
|
777
|
+
self._last_arena = self._active_arena
|
|
778
|
+
try:
|
|
779
|
+
# 预热:NVRTC 编译与 cuBLAS workspace 分配都不能发生在捕获期间。
|
|
780
|
+
# 两轮都要按"用完即回收"跑:否则预热结束时 arena 里全是活着的块,
|
|
781
|
+
# 捕获阶段拿不到可复用地址,图里就会给每个中间值各留一块显存。
|
|
782
|
+
with stream:
|
|
783
|
+
self.run_device(graph, buffers, release=True)
|
|
784
|
+
stream.synchronize()
|
|
785
|
+
if isinstance(allocator, Arena):
|
|
786
|
+
allocator.reset_stats()
|
|
787
|
+
# 常量副本在预热轮上传进了这次捕获的 arena;捕获轮要把它们重新
|
|
788
|
+
# 上传一遍,让图里记录的是本轮地址(HIP 的 recycle 会收回预热
|
|
789
|
+
# 期地址,CUDA 这里同样按"捕获轮的地址才算数"处理,两家一致)。
|
|
790
|
+
self._drop_plan(graph)
|
|
791
|
+
# 重建必须在 ``begin_capture`` **之前**:重建会走 ``_prepare_plan``
|
|
792
|
+
# → ``_op_constant``,那一遍是 ``cudaMemcpyAsync`` 的 H2D,而捕获
|
|
793
|
+
# 流上任何 H2D 都会被驱动拒绝("H2D transfers are disallowed"),
|
|
794
|
+
# 整张图随即退回逐节点执行。这里让它在默认流上完成,再让捕获流
|
|
795
|
+
# 等一次事件,图里读到的就是本轮上传的那份常量。
|
|
796
|
+
self._plan(graph)
|
|
797
|
+
ensure = cp.cuda.Event()
|
|
798
|
+
ensure.record()
|
|
799
|
+
stream.wait_event(ensure)
|
|
800
|
+
with stream:
|
|
801
|
+
stream.begin_capture()
|
|
802
|
+
# 捕获期禁止任何 D2H 同步(embedding 的越界回读会破坏捕获),
|
|
803
|
+
# 因此这里只登记标志,replay 之后由计划复查
|
|
804
|
+
guards: List[Tuple[Any, str, str]] = []
|
|
805
|
+
self._capture_guards = guards
|
|
806
|
+
self._capturing = True
|
|
807
|
+
# 图输出必须独占一块(见 ``_shared_view``):捕获图把地址写死,
|
|
808
|
+
# 输出若与源共用一段,源被回收后地址会分给后面的算子。
|
|
809
|
+
self._capture_outputs = frozenset(v.id for v in graph.outputs)
|
|
810
|
+
try:
|
|
811
|
+
env = self.run_device(graph, buffers, release=True)
|
|
812
|
+
finally:
|
|
813
|
+
self._capturing = False
|
|
814
|
+
self._capture_outputs = frozenset()
|
|
815
|
+
self._capture_guards = None
|
|
816
|
+
cg = stream.end_capture()
|
|
817
|
+
finally:
|
|
818
|
+
self._active_arena = None
|
|
819
|
+
cp.cuda.set_allocator(previous_allocator)
|
|
820
|
+
|
|
821
|
+
outputs = {
|
|
822
|
+
name: env[v.id] for v, name in zip(graph.outputs, graph.output_names)
|
|
823
|
+
}
|
|
824
|
+
return CudaGraphPlan(
|
|
825
|
+
self, cg, stream, buffers, outputs, mutable, allocator, guards
|
|
826
|
+
)
|
|
827
|
+
|
|
828
|
+
class CudaGraphPlan:
|
|
829
|
+
"""一次捕获、多次 replay 的运行期计划。
|
|
830
|
+
|
|
831
|
+
``allocator`` 必须被计划持有:图里写死的是捕获时那些显存的地址,
|
|
832
|
+
arena 一旦被回收,replay 就会写到已经属于别人的内存上。
|
|
833
|
+
"""
|
|
834
|
+
|
|
835
|
+
def __init__(
|
|
836
|
+
self,
|
|
837
|
+
backend: CudaBackend,
|
|
838
|
+
graph,
|
|
839
|
+
stream,
|
|
840
|
+
buffers: Dict[str, Any],
|
|
841
|
+
outputs: Dict[str, Any],
|
|
842
|
+
mutable: List[str],
|
|
843
|
+
allocator,
|
|
844
|
+
guards: Optional[List[Tuple[Any, str, str]]] = None,
|
|
845
|
+
) -> None:
|
|
846
|
+
self.backend = backend
|
|
847
|
+
self._cg = graph
|
|
848
|
+
self._stream = stream
|
|
849
|
+
self._buffers = buffers
|
|
850
|
+
self._outputs = outputs
|
|
851
|
+
self._mutable = tuple(mutable)
|
|
852
|
+
self._allocator = allocator
|
|
853
|
+
# 捕获期登记的越界标志(embedding 一类按下标访存的算子)。
|
|
854
|
+
# 图里写死的是这些设备标量的地址,每次 replay 都会重新置位。
|
|
855
|
+
self._guards = tuple(guards or ())
|
|
856
|
+
# 分段计时默认关闭:四次 perf_counter 会污染 0.7 ms 级的对照。
|
|
857
|
+
# 基准脚本设 AETHERFLOW_GRAPH_PROFILE=1 打开,走的是同一条执行路径。
|
|
858
|
+
self._profile = os.environ.get("AETHERFLOW_GRAPH_PROFILE") == "1"
|
|
859
|
+
self.profile_stats = {"upload": 0.0, "launch": 0.0,
|
|
860
|
+
"sync": 0.0, "guards": 0.0, "steps": 0}
|
|
861
|
+
|
|
862
|
+
@property
|
|
863
|
+
def buffers(self) -> Dict[str, Any]:
|
|
864
|
+
"""图里写死的输入缓冲(名字 → 数组对象)。
|
|
865
|
+
|
|
866
|
+
返回的是字典的副本、数组本身的引用:调用方拿它做**身份**校验
|
|
867
|
+
("优化器改的是不是图读的那一块"),而不是拿来替换缓冲。
|
|
868
|
+
"""
|
|
869
|
+
return dict(self._buffers)
|
|
870
|
+
|
|
871
|
+
@property
|
|
872
|
+
def input_shapes(self) -> Dict[str, tuple]:
|
|
873
|
+
return {name: tuple(buf.shape) for name, buf in self._buffers.items()}
|
|
874
|
+
|
|
875
|
+
@property
|
|
876
|
+
def mutable_inputs(self) -> tuple:
|
|
877
|
+
return self._mutable
|
|
878
|
+
|
|
879
|
+
@property
|
|
880
|
+
def memory_bytes(self) -> int:
|
|
881
|
+
"""这张图实际占用的显存(中间缓冲 + 输出)。"""
|
|
882
|
+
if isinstance(self._allocator, Arena):
|
|
883
|
+
return self._allocator.total_bytes
|
|
884
|
+
return self._allocator.total_bytes()
|
|
885
|
+
|
|
886
|
+
@property
|
|
887
|
+
def peak_bytes(self) -> int:
|
|
888
|
+
"""捕获期同时存活的峰值字节,即这张图绕不过去的显存下界。
|
|
889
|
+
|
|
890
|
+
与 ``memory_bytes`` 的差额就是分配器本身的浪费(块内碎片、对齐)。
|
|
891
|
+
"""
|
|
892
|
+
if isinstance(self._allocator, Arena):
|
|
893
|
+
return self._allocator.peak_live_bytes
|
|
894
|
+
return self.memory_bytes
|
|
895
|
+
|
|
896
|
+
def run(self, inputs: Mapping[str, Any]) -> Dict[str, np.ndarray]:
|
|
897
|
+
"""更新可变输入后 replay,返回主机侧输出。"""
|
|
898
|
+
self.replay(inputs)
|
|
899
|
+
# 必须显式同步捕获流:输出缓冲由该流上的图写入,
|
|
900
|
+
# 而 to_host 走的是默认流,不建依赖就会读到上一轮的结果。
|
|
901
|
+
self._stream.synchronize()
|
|
902
|
+
self._check_guards()
|
|
903
|
+
return {name: self.backend.to_host(v) for name, v in self._outputs.items()}
|
|
904
|
+
|
|
905
|
+
def run_device(self, inputs: Mapping[str, Any]) -> Dict[str, Any]:
|
|
906
|
+
"""replay 后同步,返回**设备上**的输出,不做 D2H。
|
|
907
|
+
|
|
908
|
+
设备态训练用它把梯度留在显存直接交给优化器:一步只把损失标量搬回
|
|
909
|
+
主机,权重与梯度的往返彻底消失。
|
|
910
|
+
"""
|
|
911
|
+
if not self._profile:
|
|
912
|
+
self.replay(inputs)
|
|
913
|
+
self._stream.synchronize()
|
|
914
|
+
self._check_guards()
|
|
915
|
+
return dict(self._outputs)
|
|
916
|
+
self.replay(inputs)
|
|
917
|
+
uploaded = time.perf_counter()
|
|
918
|
+
self._stream.synchronize()
|
|
919
|
+
synced = time.perf_counter()
|
|
920
|
+
self._check_guards()
|
|
921
|
+
done = time.perf_counter()
|
|
922
|
+
stats = self.profile_stats
|
|
923
|
+
stats["sync"] += synced - uploaded
|
|
924
|
+
stats["guards"] += done - synced
|
|
925
|
+
stats["steps"] += 1
|
|
926
|
+
return dict(self._outputs)
|
|
927
|
+
|
|
928
|
+
def _check_guards(self) -> None:
|
|
929
|
+
"""复查捕获期登记的设备标量,把 replay 里的越界下标变成异常。
|
|
930
|
+
|
|
931
|
+
读回是 D2H 同步——捕获早已结束,这条约束不再适用,但必须等
|
|
932
|
+
``synchronize()`` 之后才读得到本次 replay 的结果。同一个计划还会被
|
|
933
|
+
继续使用,所以报错前先把标量清零,否则下一次合法 replay 会误报。
|
|
934
|
+
"""
|
|
935
|
+
for err, op, allowed in self._guards:
|
|
936
|
+
if int(err.item()) == 0:
|
|
937
|
+
continue
|
|
938
|
+
with self._stream:
|
|
939
|
+
err[...] = 0
|
|
940
|
+
self.backend._raise_bad_ids(op, allowed)
|
|
941
|
+
|
|
942
|
+
def replay(self, inputs: Mapping[str, Any]) -> None:
|
|
943
|
+
"""只下拷输入并 replay,不等 GPU 结束(输出留在设备上)。"""
|
|
944
|
+
# 捕获流是非阻塞流,和默认流(优化器原地更新权重的地方)之间没有
|
|
945
|
+
# 隐式同步。进流之前记下当前流,显式建一条依赖,保证 replay 读到的
|
|
946
|
+
# 是主机侧刚刚更新过的权重。
|
|
947
|
+
previous = self.backend.cp.cuda.get_current_stream()
|
|
948
|
+
start = time.perf_counter() if self._profile else 0.0
|
|
949
|
+
with self._stream:
|
|
950
|
+
self._stream.wait_event(previous.record())
|
|
951
|
+
for name in self._mutable:
|
|
952
|
+
if name not in inputs:
|
|
953
|
+
raise KeyError(f"缺少图输入: {name}")
|
|
954
|
+
buf = self._buffers[name]
|
|
955
|
+
value = inputs[name]
|
|
956
|
+
if tuple(np.shape(value)) != tuple(buf.shape):
|
|
957
|
+
raise ValueError(
|
|
958
|
+
f"输入 %{name} 形状 {tuple(np.shape(value))} 与捕获时的 "
|
|
959
|
+
f"{tuple(buf.shape)} 不一致:一张 CUDA Graph 只对应一组固定形状"
|
|
960
|
+
)
|
|
961
|
+
if value is buf:
|
|
962
|
+
# 共享缓冲:调用方(设备态训练)已经把它写在这块地址上了
|
|
963
|
+
continue
|
|
964
|
+
if isinstance(value, np.ndarray):
|
|
965
|
+
# 主机数组:先进 pinned 暂存再异步 H2D,主机不必等这次拷贝完
|
|
966
|
+
buf.set(
|
|
967
|
+
self.backend.pinned_array(name, value, buf.dtype),
|
|
968
|
+
stream=self._stream,
|
|
969
|
+
)
|
|
970
|
+
else: # 已在显存:设备内拷贝,当前流由上面的 with 保证
|
|
971
|
+
buf[...] = value
|
|
972
|
+
if self._profile:
|
|
973
|
+
uploaded = time.perf_counter()
|
|
974
|
+
self._cg.launch(stream=self._stream)
|
|
975
|
+
if self._profile:
|
|
976
|
+
stats = self.profile_stats
|
|
977
|
+
stats["upload"] += uploaded - start
|
|
978
|
+
stats["launch"] += time.perf_counter() - uploaded
|
|
979
|
+
|
|
980
|
+
def device_outputs(self) -> Dict[str, Any]:
|
|
981
|
+
"""当前设备上的输出(下一次 replay 会被覆盖)。"""
|
|
982
|
+
return dict(self._outputs)
|
|
983
|
+
|
|
984
|
+
|
|
985
|
+
class _CudaGpuClock:
|
|
986
|
+
"""逐节点 GPU 计时:起点/终点各记一个 cupy 事件。
|
|
987
|
+
|
|
988
|
+
``elapsed`` 只在两个事件都完成之后才成立,所以调用方必须在读取前统一
|
|
989
|
+
同步一次。逐节点插同步是另一回事:那样测到的是同步开销本身。
|
|
990
|
+
"""
|
|
991
|
+
|
|
992
|
+
def __init__(self, backend: "CudaBackend") -> None:
|
|
993
|
+
self._backend = backend
|
|
994
|
+
self._cp = backend.cp
|
|
995
|
+
|
|
996
|
+
def _mark(self):
|
|
997
|
+
event = self._cp.cuda.Event()
|
|
998
|
+
event.record()
|
|
999
|
+
return event
|
|
1000
|
+
|
|
1001
|
+
def begin(self):
|
|
1002
|
+
return self._mark()
|
|
1003
|
+
|
|
1004
|
+
def end(self):
|
|
1005
|
+
return self._mark()
|
|
1006
|
+
|
|
1007
|
+
def synchronize(self) -> None:
|
|
1008
|
+
self._cp.cuda.Device().synchronize()
|
|
1009
|
+
|
|
1010
|
+
def elapsed(self, start, stop) -> float:
|
|
1011
|
+
# cupy 13 起 ``Event.elapsed_time`` 被移除,只剩 runtime 的
|
|
1012
|
+
# ``eventElapsedTime``;不兼容这一条会让逐节点 GPU 计时静默失效
|
|
1013
|
+
# (调用方把异常当"没有计时"处理),整块归因能力都用不上。
|
|
1014
|
+
method = getattr(start, "elapsed_time", None)
|
|
1015
|
+
if method is not None:
|
|
1016
|
+
return float(method(stop))
|
|
1017
|
+
return float(self._cp.cuda.runtime.eventElapsedTime(start.ptr, stop.ptr))
|
|
1018
|
+
|
|
1019
|
+
def release(self, start, stop) -> None:
|
|
1020
|
+
for event in (start, stop):
|
|
1021
|
+
close = getattr(event, "close", None)
|
|
1022
|
+
if close is not None:
|
|
1023
|
+
close()
|