nvmath-python 1.0.0__cp314-cp314t-win_amd64.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 (332) hide show
  1. nvmath/__init__.pxd +0 -0
  2. nvmath/__init__.py +45 -0
  3. nvmath/_internal/__init__.py +0 -0
  4. nvmath/_internal/attribute_ifc_factory.py +330 -0
  5. nvmath/_internal/layout.py +70 -0
  6. nvmath/_internal/templates.py +130 -0
  7. nvmath/_internal/threadsafe.py +106 -0
  8. nvmath/_internal/utils.py +43 -0
  9. nvmath/_internal/workspace.py +490 -0
  10. nvmath/_utils.py +147 -0
  11. nvmath/bindings/__init__.py +60 -0
  12. nvmath/bindings/_internal/__init__.pxd +0 -0
  13. nvmath/bindings/_internal/__init__.py +0 -0
  14. nvmath/bindings/_internal/common_types.pxd +31 -0
  15. nvmath/bindings/_internal/cublas.cp314t-win_amd64.pyd +0 -0
  16. nvmath/bindings/_internal/cublas.pxd +530 -0
  17. nvmath/bindings/_internal/cublasLt.cp314t-win_amd64.pyd +0 -0
  18. nvmath/bindings/_internal/cublasLt.pxd +59 -0
  19. nvmath/bindings/_internal/cublasMp.pxd +52 -0
  20. nvmath/bindings/_internal/cudss.cp314t-win_amd64.pyd +0 -0
  21. nvmath/bindings/_internal/cudss.pxd +54 -0
  22. nvmath/bindings/_internal/cufft.cp314t-win_amd64.pyd +0 -0
  23. nvmath/bindings/_internal/cufft.pxd +70 -0
  24. nvmath/bindings/_internal/cufftMp.pxd +77 -0
  25. nvmath/bindings/_internal/curand.cp314t-win_amd64.pyd +0 -0
  26. nvmath/bindings/_internal/curand.pxd +42 -0
  27. nvmath/bindings/_internal/cusolver.cp314t-win_amd64.pyd +0 -0
  28. nvmath/bindings/_internal/cusolver.pxd +15 -0
  29. nvmath/bindings/_internal/cusolverDn.cp314t-win_amd64.pyd +0 -0
  30. nvmath/bindings/_internal/cusolverDn.pxd +406 -0
  31. nvmath/bindings/_internal/cusolverMp.pxd +71 -0
  32. nvmath/bindings/_internal/cusolverSp.cp314t-win_amd64.pyd +0 -0
  33. nvmath/bindings/_internal/cusolverSp.pxd +75 -0
  34. nvmath/bindings/_internal/cusparse.cp314t-win_amd64.pyd +0 -0
  35. nvmath/bindings/_internal/cusparse.pxd +471 -0
  36. nvmath/bindings/_internal/cusparseLt.cp314t-win_amd64.pyd +0 -0
  37. nvmath/bindings/_internal/cusparseLt.pxd +48 -0
  38. nvmath/bindings/_internal/cutensor.cp314t-win_amd64.pyd +0 -0
  39. nvmath/bindings/_internal/cutensor.pxd +58 -0
  40. nvmath/bindings/_internal/mathdx.cp314t-win_amd64.pyd +0 -0
  41. nvmath/bindings/_internal/mathdx.pxd +116 -0
  42. nvmath/bindings/_internal/nvshmem.pxd +29 -0
  43. nvmath/bindings/_internal/utils.cp314t-win_amd64.pyd +0 -0
  44. nvmath/bindings/_internal/utils.pxd +174 -0
  45. nvmath/bindings/_internal/utils.pyi +10 -0
  46. nvmath/bindings/cublas.cp314t-win_amd64.pyd +0 -0
  47. nvmath/bindings/cublas.pxd +558 -0
  48. nvmath/bindings/cublas.pyi +812 -0
  49. nvmath/bindings/cublasLt.cp314t-win_amd64.pyd +0 -0
  50. nvmath/bindings/cublasLt.pxd +109 -0
  51. nvmath/bindings/cublasLt.pyi +1461 -0
  52. nvmath/bindings/cublasMp.pxd +85 -0
  53. nvmath/bindings/cublasMp.pyi +267 -0
  54. nvmath/bindings/cudss.cp314t-win_amd64.pyd +0 -0
  55. nvmath/bindings/cudss.pxd +98 -0
  56. nvmath/bindings/cudss.pyi +443 -0
  57. nvmath/bindings/cufft.cp314t-win_amd64.pyd +0 -0
  58. nvmath/bindings/cufft.pxd +118 -0
  59. nvmath/bindings/cufft.pyi +301 -0
  60. nvmath/bindings/cufftMp.pxd +124 -0
  61. nvmath/bindings/cufftMp.pyi +326 -0
  62. nvmath/bindings/curand.cp314t-win_amd64.pyd +0 -0
  63. nvmath/bindings/curand.pxd +71 -0
  64. nvmath/bindings/curand.pyi +189 -0
  65. nvmath/bindings/cusolver.cp314t-win_amd64.pyd +0 -0
  66. nvmath/bindings/cusolver.pxd +62 -0
  67. nvmath/bindings/cusolver.pyi +320 -0
  68. nvmath/bindings/cusolverDn.cp314t-win_amd64.pyd +0 -0
  69. nvmath/bindings/cusolverDn.pxd +430 -0
  70. nvmath/bindings/cusolverDn.pyi +422 -0
  71. nvmath/bindings/cusolverMp.pxd +98 -0
  72. nvmath/bindings/cusolverMp.pyi +114 -0
  73. nvmath/bindings/cusolverSp.cp314t-win_amd64.pyd +0 -0
  74. nvmath/bindings/cusolverSp.pxd +95 -0
  75. nvmath/bindings/cusolverSp.pyi +70 -0
  76. nvmath/bindings/cusparse.cp314t-win_amd64.pyd +0 -0
  77. nvmath/bindings/cusparse.pxd +546 -0
  78. nvmath/bindings/cusparse.pyi +1017 -0
  79. nvmath/bindings/cusparseLt.cp314t-win_amd64.pyd +0 -0
  80. nvmath/bindings/cusparseLt.pxd +99 -0
  81. nvmath/bindings/cusparseLt.pyi +252 -0
  82. nvmath/bindings/cutensor.cp314t-win_amd64.pyd +0 -0
  83. nvmath/bindings/cutensor.pxd +98 -0
  84. nvmath/bindings/cutensor.pyi +324 -0
  85. nvmath/bindings/cycublas.cp314t-win_amd64.pyd +0 -0
  86. nvmath/bindings/cycublas.pxd +664 -0
  87. nvmath/bindings/cycublasLt.cp314t-win_amd64.pyd +0 -0
  88. nvmath/bindings/cycublasLt.pxd +1045 -0
  89. nvmath/bindings/cycublasMp.pxd +171 -0
  90. nvmath/bindings/cycudss.cp314t-win_amd64.pyd +0 -0
  91. nvmath/bindings/cycudss.pxd +277 -0
  92. nvmath/bindings/cycufft.cp314t-win_amd64.pyd +0 -0
  93. nvmath/bindings/cycufft.pxd +333 -0
  94. nvmath/bindings/cycufftMp.pxd +342 -0
  95. nvmath/bindings/cycurand.cp314t-win_amd64.pyd +0 -0
  96. nvmath/bindings/cycurand.pxd +141 -0
  97. nvmath/bindings/cycusolver.cp314t-win_amd64.pyd +0 -0
  98. nvmath/bindings/cycusolver.pxd +137 -0
  99. nvmath/bindings/cycusolverDn.cp314t-win_amd64.pyd +0 -0
  100. nvmath/bindings/cycusolverDn.pxd +443 -0
  101. nvmath/bindings/cycusolverMp.pxd +107 -0
  102. nvmath/bindings/cycusolverSp.cp314t-win_amd64.pyd +0 -0
  103. nvmath/bindings/cycusolverSp.pxd +93 -0
  104. nvmath/bindings/cycusparse.cp314t-win_amd64.pyd +0 -0
  105. nvmath/bindings/cycusparse.pxd +679 -0
  106. nvmath/bindings/cycusparseLt.cp314t-win_amd64.pyd +0 -0
  107. nvmath/bindings/cycusparseLt.pxd +135 -0
  108. nvmath/bindings/cycutensor.cp314t-win_amd64.pyd +0 -0
  109. nvmath/bindings/cycutensor.pxd +189 -0
  110. nvmath/bindings/cymathdx.cp314t-win_amd64.pyd +0 -0
  111. nvmath/bindings/cymathdx.pxd +552 -0
  112. nvmath/bindings/cynvshmem.pxd +118 -0
  113. nvmath/bindings/mathdx.cp314t-win_amd64.pyd +0 -0
  114. nvmath/bindings/mathdx.pxd +182 -0
  115. nvmath/bindings/mathdx.pyi +1562 -0
  116. nvmath/bindings/nvpl/__init__.pxd +0 -0
  117. nvmath/bindings/nvpl/__init__.py +13 -0
  118. nvmath/bindings/nvpl/_internal/__init__.pxd +0 -0
  119. nvmath/bindings/nvpl/_internal/__init__.py +0 -0
  120. nvmath/bindings/nvpl/_internal/blas.cp314t-win_amd64.pyd +0 -0
  121. nvmath/bindings/nvpl/_internal/blas.pxd +237 -0
  122. nvmath/bindings/nvpl/_internal/fft.cp314t-win_amd64.pyd +0 -0
  123. nvmath/bindings/nvpl/_internal/fft.pxd +36 -0
  124. nvmath/bindings/nvpl/blas.cp314t-win_amd64.pyd +0 -0
  125. nvmath/bindings/nvpl/blas.pxd +131 -0
  126. nvmath/bindings/nvpl/blas.pyi +168 -0
  127. nvmath/bindings/nvpl/cyblas.cp314t-win_amd64.pyd +0 -0
  128. nvmath/bindings/nvpl/cyblas.pxd +280 -0
  129. nvmath/bindings/nvpl/cyfft.cp314t-win_amd64.pyd +0 -0
  130. nvmath/bindings/nvpl/cyfft.pxd +93 -0
  131. nvmath/bindings/nvpl/fft.cp314t-win_amd64.pyd +0 -0
  132. nvmath/bindings/nvpl/fft.pxd +100 -0
  133. nvmath/bindings/nvpl/fft.pyi +168 -0
  134. nvmath/bindings/nvshmem.pxd +54 -0
  135. nvmath/bindings/nvshmem.pyi +191 -0
  136. nvmath/device/__init__.py +38 -0
  137. nvmath/device/_deprecated.py +33 -0
  138. nvmath/device/common.py +315 -0
  139. nvmath/device/common_backend.py +131 -0
  140. nvmath/device/common_cuda.py +201 -0
  141. nvmath/device/common_numba.py +300 -0
  142. nvmath/device/common_numba_cuda_mlir.py +202 -0
  143. nvmath/device/common_opaque_tensor.py +201 -0
  144. nvmath/device/cublasdx.py +1606 -0
  145. nvmath/device/cublasdx_backend.py +860 -0
  146. nvmath/device/cublasdx_numba.py +1534 -0
  147. nvmath/device/cublasdx_numba_cuda_mlir.py +208 -0
  148. nvmath/device/cufftdx.py +373 -0
  149. nvmath/device/cufftdx_backend.py +220 -0
  150. nvmath/device/cufftdx_numba.py +140 -0
  151. nvmath/device/cufftdx_numba_cuda_mlir.py +79 -0
  152. nvmath/device/curand_kernel.py +9147 -0
  153. nvmath/device/cusolverdx.py +2708 -0
  154. nvmath/device/cusolverdx_backend.py +440 -0
  155. nvmath/device/cusolverdx_numba.py +567 -0
  156. nvmath/device/cusolverdx_numba_cuda_mlir.py +604 -0
  157. nvmath/device/cusolverdx_overload_backend.py +1029 -0
  158. nvmath/device/llvm_array.py +29 -0
  159. nvmath/device/random.py +441 -0
  160. nvmath/device/random_helpers.py +23 -0
  161. nvmath/device/random_states.py +187 -0
  162. nvmath/device/types.py +138 -0
  163. nvmath/device/vector_types_numba.py +259 -0
  164. nvmath/distributed/__init__.py +200 -0
  165. nvmath/distributed/_internal/__init__.py +0 -0
  166. nvmath/distributed/_internal/nccl.py +86 -0
  167. nvmath/distributed/_internal/nvshmem.py +307 -0
  168. nvmath/distributed/_internal/symmetric_memory.py +35 -0
  169. nvmath/distributed/_internal/tensor_ifc.py +70 -0
  170. nvmath/distributed/_internal/tensor_ifc_cupy.py +68 -0
  171. nvmath/distributed/_internal/tensor_ifc_host_device.py +172 -0
  172. nvmath/distributed/_internal/tensor_ifc_numpy.py +46 -0
  173. nvmath/distributed/_internal/tensor_ifc_torch.py +162 -0
  174. nvmath/distributed/_internal/tensor_wrapper.py +81 -0
  175. nvmath/distributed/_utils.py +167 -0
  176. nvmath/distributed/distribution/__init__.py +30 -0
  177. nvmath/distributed/distribution/_configuration.py +39 -0
  178. nvmath/distributed/distribution/distributions.py +1024 -0
  179. nvmath/distributed/distribution/redistribute.py +1284 -0
  180. nvmath/distributed/fft/__init__.py +7 -0
  181. nvmath/distributed/fft/_configuration.py +82 -0
  182. nvmath/distributed/fft/fft.py +2742 -0
  183. nvmath/distributed/linalg/__init__.py +22 -0
  184. nvmath/distributed/linalg/_internal/__init__.py +3 -0
  185. nvmath/distributed/linalg/_internal/epilog_protocol.py +586 -0
  186. nvmath/distributed/linalg/_internal/matmul_desc_ifc.py +28 -0
  187. nvmath/distributed/linalg/advanced/__init__.py +8 -0
  188. nvmath/distributed/linalg/advanced/_configuration.py +171 -0
  189. nvmath/distributed/linalg/advanced/matmulmod.py +3573 -0
  190. nvmath/distributed/linalg/generic/__init__.py +8 -0
  191. nvmath/distributed/linalg/generic/_caching.py +66 -0
  192. nvmath/distributed/linalg/generic/_configuration.py +61 -0
  193. nvmath/distributed/linalg/generic/_factorization.py +172 -0
  194. nvmath/distributed/linalg/generic/_initialization.py +966 -0
  195. nvmath/distributed/linalg/generic/_problem_spec.py +511 -0
  196. nvmath/distributed/linalg/generic/solvermod.py +1368 -0
  197. nvmath/distributed/process_group.py +408 -0
  198. nvmath/fft/__init__.py +7 -0
  199. nvmath/fft/_configuration.py +189 -0
  200. nvmath/fft/_exec_utils.py +82 -0
  201. nvmath/fft/_helpers.py +237 -0
  202. nvmath/fft/fft.py +3122 -0
  203. nvmath/internal/__init__.pxd +3 -0
  204. nvmath/internal/__init__.py +10 -0
  205. nvmath/internal/_bindings.cp314t-win_amd64.pyd +0 -0
  206. nvmath/internal/_bindings.pxd +18 -0
  207. nvmath/internal/_device_utils.py +45 -0
  208. nvmath/internal/_layout/__init__.pxd +3 -0
  209. nvmath/internal/_layout/__init__.py +7 -0
  210. nvmath/internal/_layout/_layout.cp314t-win_amd64.pyd +0 -0
  211. nvmath/internal/_layout/_layout.pxd +1303 -0
  212. nvmath/internal/_layout/_layout.pyi +1145 -0
  213. nvmath/internal/enum_utils.py +142 -0
  214. nvmath/internal/formatters.py +87 -0
  215. nvmath/internal/mem_limit.py +51 -0
  216. nvmath/internal/memory.cp314t-win_amd64.pyd +0 -0
  217. nvmath/internal/memory.pxd +13 -0
  218. nvmath/internal/memory.pyi +50 -0
  219. nvmath/internal/ndbuffer/__init__.pxd +3 -0
  220. nvmath/internal/ndbuffer/__init__.py +9 -0
  221. nvmath/internal/ndbuffer/_copy_kernel.cp314t-win_amd64.pyd +0 -0
  222. nvmath/internal/ndbuffer/_copy_kernel.pxd +10 -0
  223. nvmath/internal/ndbuffer/_jit.cp314t-win_amd64.pyd +0 -0
  224. nvmath/internal/ndbuffer/_jit.pxd +7 -0
  225. nvmath/internal/ndbuffer/_ndbuffer.cp314t-win_amd64.pyd +0 -0
  226. nvmath/internal/ndbuffer/_ndbuffer.pxd +40 -0
  227. nvmath/internal/ndbuffer/_ndbuffer.pyi +463 -0
  228. nvmath/internal/ndbuffer/copy_kernel/args.h +34 -0
  229. nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/array_view.h +52 -0
  230. nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/elementwise.h +68 -0
  231. nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/grid_indexer.h +69 -0
  232. nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/transposed.h +242 -0
  233. nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/type_utils.h +39 -0
  234. nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/utils.h +132 -0
  235. nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/vec.h +159 -0
  236. nvmath/internal/ndbuffer/copy_kernel/elementwise.h +53 -0
  237. nvmath/internal/ndbuffer/copy_kernel/transposed.h +58 -0
  238. nvmath/internal/package_ifc.py +168 -0
  239. nvmath/internal/package_ifc_cuda.py +57 -0
  240. nvmath/internal/package_ifc_cupy.py +67 -0
  241. nvmath/internal/package_ifc_torch.py +69 -0
  242. nvmath/internal/package_wrapper.py +14 -0
  243. nvmath/internal/tensor_ifc.py +179 -0
  244. nvmath/internal/tensor_ifc_cupy.py +234 -0
  245. nvmath/internal/tensor_ifc_ndbuffer.py +147 -0
  246. nvmath/internal/tensor_ifc_numpy.py +184 -0
  247. nvmath/internal/tensor_ifc_torch.py +178 -0
  248. nvmath/internal/tensor_wrapper.py +160 -0
  249. nvmath/internal/typemaps.py +113 -0
  250. nvmath/internal/utils.py +805 -0
  251. nvmath/linalg/__init__.py +56 -0
  252. nvmath/linalg/_internal/__init__.py +3 -0
  253. nvmath/linalg/_internal/algo_cap_ifc.py +82 -0
  254. nvmath/linalg/_internal/algo_config_ifc.py +43 -0
  255. nvmath/linalg/_internal/batch.py +234 -0
  256. nvmath/linalg/_internal/enum_to_tuples.py +64 -0
  257. nvmath/linalg/_internal/epilog_protocol.py +766 -0
  258. nvmath/linalg/_internal/layout.py +624 -0
  259. nvmath/linalg/_internal/matmul_desc_ifc.py +28 -0
  260. nvmath/linalg/_internal/matmul_pref_ifc.py +27 -0
  261. nvmath/linalg/_internal/matrix_layout_ifc.py +26 -0
  262. nvmath/linalg/_internal/solver_utils.py +432 -0
  263. nvmath/linalg/_internal/typemaps.py +144 -0
  264. nvmath/linalg/_internal/utils.py +157 -0
  265. nvmath/linalg/advanced/__init__.py +8 -0
  266. nvmath/linalg/advanced/_algorithmmod.py +170 -0
  267. nvmath/linalg/advanced/_configuration.py +351 -0
  268. nvmath/linalg/advanced/helpers/__init__.py +5 -0
  269. nvmath/linalg/advanced/helpers/matmul.py +1316 -0
  270. nvmath/linalg/advanced/matmulmod.py +3734 -0
  271. nvmath/linalg/generic/__init__.py +53 -0
  272. nvmath/linalg/generic/_configuration/__init__.py +39 -0
  273. nvmath/linalg/generic/_configuration/layout.py +263 -0
  274. nvmath/linalg/generic/_configuration/match.py +734 -0
  275. nvmath/linalg/generic/_configuration/qualifiers.py +493 -0
  276. nvmath/linalg/generic/_configuration/solver_configuration.py +59 -0
  277. nvmath/linalg/generic/_configuration/wrap.py +217 -0
  278. nvmath/linalg/generic/_dtype.py +15 -0
  279. nvmath/linalg/generic/matmulmod.py +2094 -0
  280. nvmath/linalg/generic/solvermod.py +1301 -0
  281. nvmath/memory.py +279 -0
  282. nvmath/sparse/__init__.py +38 -0
  283. nvmath/sparse/_internal/__init__.py +21 -0
  284. nvmath/sparse/_internal/common_utils.py +147 -0
  285. nvmath/sparse/_internal/cudss_config_ifc.py +702 -0
  286. nvmath/sparse/_internal/cudss_data_ifc.py +399 -0
  287. nvmath/sparse/_internal/cudss_utils.py +506 -0
  288. nvmath/sparse/_internal/cusparse_utils.py +382 -0
  289. nvmath/sparse/_internal/sparse_bsc_ifc.py +303 -0
  290. nvmath/sparse/_internal/sparse_bsr_ifc.py +305 -0
  291. nvmath/sparse/_internal/sparse_coo_ifc.py +256 -0
  292. nvmath/sparse/_internal/sparse_csc_ifc.py +268 -0
  293. nvmath/sparse/_internal/sparse_csr_ifc.py +288 -0
  294. nvmath/sparse/_internal/sparse_dia_ifc.py +242 -0
  295. nvmath/sparse/_internal/sparse_format_helpers.py +601 -0
  296. nvmath/sparse/_internal/sparse_tensor_ifc.py +133 -0
  297. nvmath/sparse/_internal/sparse_ust_ifc.py +141 -0
  298. nvmath/sparse/_internal/utils.py +56 -0
  299. nvmath/sparse/advanced/__init__.py +7 -0
  300. nvmath/sparse/advanced/_configuration.py +227 -0
  301. nvmath/sparse/advanced/direct_solver.py +2069 -0
  302. nvmath/sparse/generic/__init__.py +7 -0
  303. nvmath/sparse/generic/_configuration.py +129 -0
  304. nvmath/sparse/generic/_helpers.py +137 -0
  305. nvmath/sparse/generic/_thunks.py +21 -0
  306. nvmath/sparse/generic/matmulmod.py +2353 -0
  307. nvmath/sparse/ust/__init__.py +7 -0
  308. nvmath/sparse/ust/_converters.py +422 -0
  309. nvmath/sparse/ust/_cpp.py +28 -0
  310. nvmath/sparse/ust/_drawer.py +565 -0
  311. nvmath/sparse/ust/_emitter.py +1033 -0
  312. nvmath/sparse/ust/_jit.py +188 -0
  313. nvmath/sparse/ust/_kernel.py +282 -0
  314. nvmath/sparse/ust/_utils.py +149 -0
  315. nvmath/sparse/ust/interfaces/__init__.py +0 -0
  316. nvmath/sparse/ust/interfaces/torch_interface.py +476 -0
  317. nvmath/sparse/ust/tensor.py +1016 -0
  318. nvmath/sparse/ust/tensor_format.py +957 -0
  319. nvmath/tensor/__init__.py +6 -0
  320. nvmath/tensor/_configuration.py +120 -0
  321. nvmath/tensor/_internal/__init__.py +3 -0
  322. nvmath/tensor/_internal/cutensor_config_ifc.py +279 -0
  323. nvmath/tensor/_internal/cutensor_utils.py +230 -0
  324. nvmath/tensor/_internal/data.py +43 -0
  325. nvmath/tensor/_internal/einsum_parser.py +444 -0
  326. nvmath/tensor/_internal/typemaps.py +96 -0
  327. nvmath/tensor/contract.py +1900 -0
  328. nvmath_python-1.0.0.dist-info/METADATA +134 -0
  329. nvmath_python-1.0.0.dist-info/RECORD +332 -0
  330. nvmath_python-1.0.0.dist-info/WHEEL +5 -0
  331. nvmath_python-1.0.0.dist-info/licenses/LICENSE +177 -0
  332. nvmath_python-1.0.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,3734 @@
1
+ # Copyright (c) 2024-2026, NVIDIA CORPORATION & AFFILIATES. ALL RIGHTS RESERVED.
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ __all__ = ["MatmulComputeType", "Matmul", "matmul"]
6
+
7
+ import copy
8
+ import dataclasses
9
+ import functools
10
+ import logging
11
+ import operator
12
+ import random
13
+ import typing
14
+ from collections import namedtuple
15
+ from collections.abc import MutableSequence, Sequence
16
+ from dataclasses import dataclass
17
+
18
+ import numpy as np
19
+ from cuda.core import Device
20
+
21
+ from nvmath import memory
22
+ from nvmath._internal.workspace import Workspace
23
+ from nvmath._utils import CudaDataType
24
+ from nvmath.bindings import cublas
25
+ from nvmath.bindings import cublasLt as cublaslt # type: ignore
26
+ from nvmath.internal import formatters, tensor_wrapper, typemaps, utils
27
+ from nvmath.internal._layout import StridedLayout
28
+ from nvmath.linalg._internal import matmul_desc_ifc, matmul_pref_ifc, matrix_layout_ifc
29
+ from nvmath.linalg._internal.epilog_protocol import (
30
+ BATCHED_EPILOG_MINIMUM_VERSIONS_MAP,
31
+ EPILOG_INPUT_HANDLERS_MAP,
32
+ EPILOG_MINIMUM_VERSIONS_MAP,
33
+ EPILOG_OUTPUT_HANDLERS_MAP,
34
+ EpilogOutputHandler,
35
+ )
36
+ from nvmath.linalg._internal.typemaps import (
37
+ COMPUTE_TYPE_TO_DEFAULT_SCALE_TYPE,
38
+ NAMES_TO_DEFAULT_COMPUTE_TYPE,
39
+ NAMES_TO_DEFAULT_SCALE_TYPE,
40
+ SCALE_TYPE_TO_DEFAULT_COMPUTE_TYPE,
41
+ SUPPORTED_TYPES,
42
+ )
43
+ from nvmath.linalg._internal.utils import (
44
+ axis_order_in_memory,
45
+ calculate_strides,
46
+ check_batch_tileable,
47
+ get_handle,
48
+ pointer_aligned_to,
49
+ )
50
+ from nvmath.linalg.advanced import _algorithmmod, _configuration
51
+
52
+ MatmulComputeType = cublas.ComputeType
53
+
54
+ EpilogInputTraits = namedtuple("EpilogInputTraits", ["dtype", "extents", "strides"])
55
+
56
+
57
+ @dataclass
58
+ class MatrixLayout:
59
+ """An internal data class for capturing the tensor layout."""
60
+
61
+ shape: Sequence[int]
62
+ strides: Sequence[int]
63
+ is_conjugate: bool = False # Used to support is_conjugate via conjugate_transpose.
64
+
65
+
66
+ @dataclass
67
+ class LayoutTraits:
68
+ """An internal data class for capturing the matrix multiplication traits."""
69
+
70
+ order: cublaslt.Order
71
+ ld: int
72
+ batch_offset: int # Based on strides
73
+ is_conjugate: bool # Used to support is_conjugate via conjugate_transpose.
74
+ mm_shape: Sequence[int] | None = None
75
+ mm_strides: Sequence[int] | None = None
76
+
77
+ def get_mm_layout(self, transpose=False):
78
+ if self.is_conjugate:
79
+ transpose = True
80
+ if not transpose:
81
+ return *self.mm_shape, self.ld, self.order
82
+
83
+ # Use of transpose is supported only for A and B for two specific use cases till the
84
+ # C library directly supports these use cases:
85
+ #
86
+ # 1. When A or B has the conjugate qualifier, we transpose it internally and then
87
+ # use conjugate transpose in the MM (A @ B.conj() == A @ B.T.H).
88
+ #
89
+ # 2. When the epilog is BGRADB, we transpose B internally and use transpose in the
90
+ # MM since this epilog requires B to be transposed (A @ B == A @ B.T.T).
91
+ #
92
+ # This requires that the layout order be ROW or COL (no special layouts such as
93
+ # structured or hierarchical).
94
+ assert self.mm_shape is not None and self.mm_strides is not None, "Internal Error."
95
+ assert self.ld != 0, "Internal Error."
96
+
97
+ mm_shape = self.mm_shape[1], self.mm_shape[0]
98
+ if self.order == cublaslt.Order.ROW:
99
+ order = cublaslt.Order.COL
100
+ ld = max(self.mm_shape[1], self.mm_strides[0])
101
+ elif self.order == cublaslt.Order.COL:
102
+ order = cublaslt.Order.ROW
103
+ ld = max(self.mm_shape[0], self.mm_strides[1])
104
+ else:
105
+ raise AssertionError("Internal Error. Invalid layout order.")
106
+
107
+ return *mm_shape, ld, order
108
+
109
+
110
+ @dataclass
111
+ class MMTraits:
112
+ """An internal data class for capturing the matrix multiplication traits. The
113
+ result traits are captured separately, because we need to wait for the
114
+ epilog to be provided.
115
+ """
116
+
117
+ M: int
118
+ N: int
119
+ K: int
120
+ d_mm_shape: Sequence[int]
121
+ inplace: bool
122
+ c_layout: MatrixLayout
123
+ a_layout_traits: LayoutTraits
124
+ b_layout_traits: LayoutTraits
125
+ c_layout_traits: LayoutTraits
126
+ batch_count: int
127
+ batch_shape: Sequence[int]
128
+ batch_axis_order: Sequence[int]
129
+
130
+
131
+ @dataclass
132
+ class ResultTraits:
133
+ """An internal data class for capturing the result matrix's traits."""
134
+
135
+ d_layout_traits: LayoutTraits
136
+ result_shape: Sequence[int]
137
+ result_strides: Sequence[int]
138
+
139
+
140
+ def get_matrix_layout_traits(
141
+ mm_shape: Sequence[int],
142
+ mm_strides: Sequence[int],
143
+ batch_strides: Sequence[int],
144
+ col_bcast: bool,
145
+ ordering: cublaslt.Order | None = None,
146
+ orientation: cublaslt.Order | None = None,
147
+ ) -> tuple[cublaslt.Order, int, int]:
148
+ """
149
+ The 'ordering' option specifies the layout order, if it's not None, as in the case of
150
+ the D matrix whose layout is determined by the other operands' layout. It is required if
151
+ the matrix is degenerate (a vector or scalar: len(mm_shape) < 2).
152
+
153
+ The 'orientation' option (ROW or COL) is required to infer the correct leading dimension
154
+ for degenerate matrices (a vector or scalar: len(mm_shape) < 2).
155
+ """
156
+ if len(mm_shape) < 2: # The result D can be a scalar or vector.
157
+ assert ordering is not None, "Internal Error: 'ordering' must be specified for degenerate matrices."
158
+ assert orientation is not None, "Internal Error: 'orientation' must be specified for degenerate matrices."
159
+ batch_offset = min(batch_strides) if batch_strides else 0
160
+ order = ordering
161
+ if len(mm_shape) < 1:
162
+ ld = 1
163
+ elif order != orientation:
164
+ # For a ROW vector in COL order, the LD should be 1 since we promote the row
165
+ # vector to a matrix as (1, M). Similarly, for a COL vector in ROW order, the LD
166
+ # should be 1 as well since we promote the column vector to a matrix as (M, 1).
167
+ ld = 1
168
+ else:
169
+ ld = max(mm_strides[0], mm_shape[0])
170
+ return order, ld, batch_offset
171
+
172
+ M, N = mm_shape
173
+
174
+ if ordering is not None:
175
+ order = ordering
176
+ message = f"Internal Error: incompatible ordering '{ordering}' and strides {mm_strides}"
177
+ if order == cublaslt.Order.ROW:
178
+ assert mm_strides[0] >= mm_strides[1] and mm_strides[1] == 1, message
179
+ else:
180
+ assert mm_strides[1] >= mm_strides[0] and mm_strides[0] == 1, message
181
+ else:
182
+ # Important: start with the first dimension so that cases like (M, 1) : (1, 1) or
183
+ # (1, M) : (1, 1) in CuTe notation map to COL.
184
+ if mm_strides[0] == 1:
185
+ order = cublaslt.Order.COL
186
+ elif mm_strides[1] == 1:
187
+ order = cublaslt.Order.ROW
188
+ else:
189
+ if M == 1:
190
+ order = cublaslt.Order.COL
191
+ elif N == 1:
192
+ order = cublaslt.Order.ROW
193
+ else:
194
+ raise ValueError("Unsupported layout.")
195
+
196
+ # We need to handle broadcast dimensions with zero-stride for the c matrix.
197
+ if col_bcast and N == 1:
198
+ ld = 0
199
+ else:
200
+ ld = max(M, mm_strides[1]) if order == cublaslt.Order.COL else max(N, mm_strides[0])
201
+
202
+ # Batch dimensions should be contiguous in memory, which we have already checked. The
203
+ # batch_offset should be based on the lowest stride in the batch dimension to account
204
+ # for embedded matrices.
205
+ batch_offset = min(batch_strides) if batch_strides else 0
206
+
207
+ return order, ld, batch_offset
208
+
209
+
210
+ def get_mm_traits(a_layout, b_layout, c_layout, inplace, logger):
211
+ """
212
+ First check A and B compatibility:
213
+
214
+ 1. Check MM compatibility (K):
215
+ a. First pad A and/or B MM dimensions if 1-D according to NumPy convention.
216
+ b. The padding is used to determine M, N, and K but should not appear in the output
217
+ dimensions.
218
+ c. If both A and B are N-D, the dimensions must match.
219
+ 2. Check batch dimensions:
220
+ a. One of A or B can have missing batch extents, in which case it is broadcast,
221
+ otherwise
222
+ b. A and B must have the same batch ordering.
223
+ c. In addition, the batch dimensions must be tileable (contiguous in memory).
224
+
225
+ Then check C:
226
+
227
+ C can be None. If C is passed in, it must be a matrix. The batching rule is the
228
+ same as above.
229
+
230
+ For the inplace option (result == C), C cannot be broadcast and so must have batch
231
+ dimensions (if batched).
232
+ """
233
+ inplace_addendum = ""
234
+ if inplace:
235
+ inplace_addendum = "This is required for inplace operations."
236
+
237
+ a_shape, a_strides = list(a_layout.shape), list(a_layout.strides)
238
+ b_shape, b_strides = list(b_layout.shape), list(b_layout.strides)
239
+
240
+ a_batch_shape, a_mm_shape = a_shape[:-2], a_shape[-2:]
241
+ b_batch_shape, b_mm_shape = b_shape[:-2], b_shape[-2:]
242
+
243
+ a_batch_strides, a_mm_strides = a_strides[:-2], a_strides[-2:]
244
+ b_batch_strides, b_mm_strides = b_strides[:-2], b_strides[-2:]
245
+ d_mm_shape = []
246
+ if len(a_mm_shape) == 1:
247
+ s, d = a_mm_shape[0], a_mm_strides[0]
248
+ a_mm_shape = [1] + a_mm_shape
249
+ a_mm_strides = [s * d] + a_mm_strides
250
+ else:
251
+ d_mm_shape.append(a_mm_shape[0]) # The first mode for d applies only when a is not a vector.
252
+
253
+ if len(b_mm_shape) == 1:
254
+ s, d = b_mm_shape[0], b_mm_strides[0]
255
+ b_mm_shape = b_mm_shape + [1]
256
+ b_mm_strides = b_mm_strides + [s * d]
257
+ else:
258
+ d_mm_shape.append(b_mm_shape[1]) # The second mode for d applies only when b is not a vector.
259
+
260
+ logger.debug(f"The MM shape for operand A is {a_mm_shape} with strides {a_mm_strides}.")
261
+ logger.debug(f"The MM shape for operand B is {b_mm_shape} with strides {b_mm_strides}.")
262
+ logger.debug(f"The MM shape for operand D is {d_mm_shape}.")
263
+
264
+ M0, K0 = a_mm_shape
265
+ K1, N0 = b_mm_shape
266
+ if K0 != K1:
267
+ raise ValueError(
268
+ f"The 'K' extent must match for the operands: K={K0} in operand A is not equal to K={K1} in operand B."
269
+ )
270
+
271
+ # Check if batch dimensions of A and B are tileable as well as compatible.
272
+ batch_shape, batch_axis_order = [], ()
273
+ if len(a_batch_shape) > 0:
274
+ if not check_batch_tileable(a_batch_shape, a_batch_strides):
275
+ message = (
276
+ f"The batch layout for A corresponding to shape = {a_batch_shape} and strides = {a_batch_strides} "
277
+ "is currently not supported because it is not tileable."
278
+ )
279
+ raise ValueError(message)
280
+ logger.debug(
281
+ f"The batch layout for A corresponding to shape = {a_batch_shape} and strides = {a_batch_strides} IS tileable."
282
+ )
283
+ batch_shape = a_batch_shape
284
+ batch_axis_order = a_batch_axis_order = axis_order_in_memory(a_batch_strides)
285
+
286
+ if len(b_batch_shape) > 0:
287
+ if not check_batch_tileable(b_batch_shape, b_batch_strides):
288
+ message = (
289
+ f"The batch layout for B corresponding to shape = {b_batch_shape} and strides = {b_batch_strides} "
290
+ "is currently not supported because it is not tileable."
291
+ )
292
+ raise ValueError(message)
293
+ logger.debug(
294
+ f"The batch layout for B corresponding to shape = {b_batch_shape} and strides = {b_batch_strides} IS tileable."
295
+ )
296
+ batch_shape = b_batch_shape
297
+ batch_axis_order = b_batch_axis_order = axis_order_in_memory(b_batch_strides)
298
+
299
+ if len(a_batch_shape) > 0 and len(b_batch_shape) > 0:
300
+ if a_batch_shape != b_batch_shape:
301
+ raise ValueError(f"The batch dimensions of operands A {a_batch_shape} and B {b_batch_shape} must match.")
302
+ if a_batch_axis_order != b_batch_axis_order:
303
+ raise ValueError(f"The batch order of operands A {a_batch_axis_order} and B {b_batch_axis_order} must match.")
304
+
305
+ logger.debug(f"The batch shape is {batch_shape} with batch axis order {batch_axis_order}.")
306
+
307
+ batch_count = functools.reduce(operator.mul, batch_shape, 1)
308
+
309
+ # Create matrix layout traits.
310
+ a_order, a_ld, a_batch_offset = get_matrix_layout_traits(a_mm_shape, a_mm_strides, a_batch_strides, col_bcast=False)
311
+ a_layout_traits = LayoutTraits(
312
+ order=a_order,
313
+ ld=a_ld,
314
+ batch_offset=a_batch_offset,
315
+ is_conjugate=a_layout.is_conjugate,
316
+ mm_shape=a_mm_shape,
317
+ mm_strides=a_mm_strides,
318
+ )
319
+ logger.debug(f"The layout order for operand A is {a_order.name}, with LD {a_ld}, and batch offset {a_batch_offset}.")
320
+
321
+ b_order, b_ld, b_batch_offset = get_matrix_layout_traits(b_mm_shape, b_mm_strides, b_batch_strides, col_bcast=False)
322
+ b_layout_traits = LayoutTraits(
323
+ order=b_order,
324
+ ld=b_ld,
325
+ batch_offset=b_batch_offset,
326
+ is_conjugate=b_layout.is_conjugate,
327
+ mm_shape=b_mm_shape,
328
+ mm_strides=b_mm_strides,
329
+ )
330
+ logger.debug(f"The layout order for operand B is {b_order.name}, with LD {b_ld}, and batch offset {b_batch_offset}.")
331
+
332
+ # Process matrix c, if provided.
333
+ c_layout_traits = None
334
+ if c_layout is not None:
335
+ # 1. C cannot be a vector.
336
+ # 2. C can be a matrix of dimension (M, N) or (M, 1), broadcast in the latter case
337
+ # and has to have contiguous strides.
338
+ # 3. C can be batched matrices of dimension (..., M, N) or (..., M, 1), broadcast in
339
+ # the latter case and has to have contiguous strides.
340
+ c_shape, c_strides = list(c_layout.shape), list(c_layout.strides)
341
+
342
+ c_batch_shape, c_mm_shape = c_shape[:-2], c_shape[-2:]
343
+ c_batch_strides, c_mm_strides = c_strides[:-2], c_strides[-2:]
344
+ if len(c_mm_shape) == 1:
345
+ raise ValueError(f"C cannot be a vector. C shape: {c_mm_shape}")
346
+ logger.debug(f"The MM shape for operand C is {c_mm_shape} with strides {c_mm_strides}.")
347
+
348
+ Mc, Nc = c_mm_shape
349
+ if Mc != M0:
350
+ raise ValueError(f"The M dimension of the C matrix ({Mc}) must match the M dimension of A.")
351
+
352
+ if (inplace and Nc != N0) or (Nc != 1 and Nc != N0):
353
+ raise ValueError(f"The N dimension of the C matrix ({Nc}) must match the N dimension of B. {inplace_addendum}")
354
+
355
+ # For the inplace option, C must be batched if an operand is batched.
356
+ if inplace or len(c_batch_shape) > 0:
357
+ if c_batch_shape != batch_shape:
358
+ raise ValueError(
359
+ f"The batch dimension of operand C {c_batch_shape} must match with that of the other operands "
360
+ f"{batch_shape}. {inplace_addendum}"
361
+ )
362
+
363
+ if batch_shape and (c_batch_axis_order := axis_order_in_memory(c_batch_strides)) != batch_axis_order:
364
+ raise ValueError(
365
+ f"The batch axis order of operand C {c_batch_axis_order} must match with that of the other "
366
+ f"operands {batch_axis_order}."
367
+ )
368
+
369
+ if batch_shape and not check_batch_tileable(c_batch_shape, c_batch_strides):
370
+ message = (
371
+ f"The batch layout for C corresponding to shape = {c_batch_shape} and strides = "
372
+ f"{c_batch_strides} is currently not supported because it is not tileable."
373
+ )
374
+ raise ValueError(message)
375
+
376
+ # Inplace writes back into C, so the C layout must be unique.
377
+ # Otherwise distinct logical indices alias the same memory cell,
378
+ # producing overlapping writes / undefined behavior.
379
+ if inplace and not StridedLayout(c_shape, c_strides, itemsize=1).is_unique:
380
+ raise ValueError(
381
+ f"The layout for C with shape = {c_shape} and strides = {c_strides} is not "
382
+ f"supported for inplace operations: the index-to-memory mapping is not "
383
+ f"injective, which would cause overlapping writes into the same memory."
384
+ )
385
+
386
+ c_order, c_ld, c_batch_offset = get_matrix_layout_traits(
387
+ c_mm_shape, c_mm_strides, c_batch_strides, col_bcast=not inplace
388
+ )
389
+ c_layout_traits = LayoutTraits(order=c_order, ld=c_ld, batch_offset=c_batch_offset, is_conjugate=c_layout.is_conjugate)
390
+ logger.debug(f"The layout order for operand C is {c_order.name}, with LD {c_ld}, and batch offset {c_batch_offset}.")
391
+
392
+ return MMTraits(
393
+ M=M0,
394
+ N=N0,
395
+ K=K0,
396
+ d_mm_shape=d_mm_shape,
397
+ inplace=inplace,
398
+ c_layout=c_layout,
399
+ batch_count=batch_count,
400
+ batch_shape=batch_shape,
401
+ batch_axis_order=batch_axis_order,
402
+ a_layout_traits=a_layout_traits,
403
+ b_layout_traits=b_layout_traits,
404
+ c_layout_traits=c_layout_traits,
405
+ )
406
+
407
+
408
+ def get_result_traits(mm_traits: MMTraits, epilog_ordering: cublaslt.Order | None, logger: logging.Logger) -> ResultTraits:
409
+ """
410
+ epilog_ordering = value of type cublaslt.Order or None.
411
+
412
+ The result layout is determined from:
413
+ - the ordering of operand c, if it is provided, or
414
+ - the epilog requirement, if it exists, or
415
+ - the ordering of operand a.
416
+
417
+ The result batch dimensions must have the same extents and axis order as the inputs. The
418
+ MM layout can be C or F.
419
+ """
420
+
421
+ # For inplace=True, the result traits are essentially the same as for operand C except
422
+ # for conjugation.
423
+ if mm_traits.inplace:
424
+ result_shape, result_strides = mm_traits.c_layout.shape, mm_traits.c_layout.strides
425
+ d_layout_traits = dataclasses.replace(mm_traits.c_layout_traits, is_conjugate=False)
426
+ return ResultTraits(result_shape=result_shape, result_strides=result_strides, d_layout_traits=d_layout_traits)
427
+
428
+ # The result shape is the batch shape + d_mm_shape.
429
+ result_shape = (*mm_traits.batch_shape, *mm_traits.d_mm_shape)
430
+
431
+ if mm_traits.c_layout_traits is not None:
432
+ result_ordering = mm_traits.c_layout_traits.order
433
+ elif epilog_ordering is not None:
434
+ result_ordering = epilog_ordering
435
+ else:
436
+ result_ordering = mm_traits.a_layout_traits.order
437
+
438
+ if result_ordering == cublaslt.Order.ROW:
439
+ d_order = list(range(len(mm_traits.d_mm_shape) - 1, -1, -1))
440
+ elif result_ordering == cublaslt.Order.COL:
441
+ d_order = list(range(len(mm_traits.d_mm_shape)))
442
+ else:
443
+ raise AssertionError("Internal Error.")
444
+
445
+ result_axis_order = [len(mm_traits.batch_axis_order) + a for a in d_order] + list(mm_traits.batch_axis_order)
446
+
447
+ # Calculate the result strides.
448
+ result_strides = calculate_strides(result_shape, result_axis_order)
449
+
450
+ # For degenerate matrices, we need to specify the result orientation.
451
+ result_orientation = None
452
+ if len(mm_traits.d_mm_shape) < 2:
453
+ if mm_traits.M == 1:
454
+ result_orientation = cublaslt.Order.ROW
455
+ elif mm_traits.N == 1:
456
+ result_orientation = cublaslt.Order.COL
457
+
458
+ # The result's traits.
459
+ d_batch_strides, d_mm_strides = (
460
+ result_strides[: len(mm_traits.batch_shape)],
461
+ result_strides[len(mm_traits.batch_shape) :],
462
+ )
463
+ order, d_ld, d_batch_offset = get_matrix_layout_traits(
464
+ mm_traits.d_mm_shape,
465
+ d_mm_strides,
466
+ d_batch_strides,
467
+ col_bcast=False,
468
+ ordering=result_ordering,
469
+ orientation=result_orientation,
470
+ )
471
+ assert order == result_ordering, (
472
+ f"Internal Error: d_order = {order.name}, result_ordering = {result_ordering.name}, mm_traits = {mm_traits}."
473
+ )
474
+ d_layout_traits = LayoutTraits(order=order, ld=d_ld, batch_offset=d_batch_offset, is_conjugate=False)
475
+ logger.debug(f"The layout order for operand D is {order.name}, with LD {d_ld}, and batch offset {d_batch_offset}.")
476
+
477
+ return ResultTraits(result_shape=result_shape, result_strides=result_strides, d_layout_traits=d_layout_traits)
478
+
479
+
480
+ SHARED_MM_DOCUMENTATION = utils.COMMON_SHARED_DOC_MAP.copy()
481
+ SHARED_MM_DOCUMENTATION.update(
482
+ {
483
+ "a": """\
484
+ A tensor representing the first operand to the matrix multiplication (see `Semantics`_). The currently supported types
485
+ are :class:`numpy.ndarray`, :class:`cupy.ndarray`, and :class:`torch.Tensor`.""".replace("\n", " "),
486
+ #
487
+ "b": """\
488
+ A tensor representing the second operand to the matrix multiplication (see `Semantics`_). The currently supported types
489
+ are :class:`numpy.ndarray`, :class:`cupy.ndarray`, and :class:`torch.Tensor`.""".replace("\n", " "),
490
+ #
491
+ "c": """\
492
+ (Optional) A tensor representing the operand to add to the matrix multiplication result (see `Semantics`_). The currently
493
+ supported types are :class:`numpy.ndarray`, :class:`cupy.ndarray`, and :class:`torch.Tensor`.""".replace("\n", " "),
494
+ #
495
+ "c_admonitions": """
496
+ .. versionchanged:: 0.3.0
497
+ In order to avoid broadcasting behavior ambiguity, nvmath-python no longer
498
+ accepts a 1-D (vector) `c`. Use a singleton dimension to convert your input
499
+ array to 2-D.
500
+ """,
501
+ #
502
+ "alpha": """\
503
+ The scale factor for the matrix multiplication term as a real or complex number. The default is
504
+ :math:`1.0`.""".replace("\n", " "),
505
+ #
506
+ "beta": """\
507
+ The scale factor for the matrix addition term as a real or complex number. A value for `beta` must be provided if
508
+ operand `c` is specified.""".replace("\n", " "),
509
+ #
510
+ "quantization_scales": """\
511
+ Specify scale factors for the matrix multiplication as a :class:`~nvmath.linalg.advanced.MatmulQuantizationScales`
512
+ object. Alternatively, a `dict` containing the parameters for the
513
+ :class:`~nvmath.linalg.advanced.MatmulQuantizationScales`
514
+ constructor can also be provided. The scale factors can be provided as scalars or tensors.
515
+ If a scale factor is provided as a tensor, it must be from the same package and on the same
516
+ memory space (CPU or GPU device) as the operands of the matmul.
517
+ If a scale factor is provided as a scalar, and the execution space is GPU,
518
+ a CPU->GPU copy is inevitable. To avoid this copy, provide
519
+ the quantization scale as one-element array on the GPU.
520
+ Allowed and required only for narrow-precision (FP8 and lower) operations.""".replace("\n", " "),
521
+ #
522
+ "algorithms": """\
523
+ A sequence of :class:`Algorithm` objects that can be directly provided to bypass planning. The algorithm objects must be
524
+ compatible with the matrix multiplication. A typical use for this option is to provide algorithms serialized (numpy)
525
+ from a previously planned and autotuned matrix multiplication.""".replace("\n", " "),
526
+ #
527
+ "epilog": """\
528
+ Specify an epilog :math:`\\mathcal{F}` as an object of type :class:`MatmulEpilog` to apply to the result of the matrix
529
+ multiplication: :math:`\\mathcal{F}(\\alpha a @ b + \\beta c)`. The default is no epilog. See `cuBLASLt documentation
530
+ <https://docs.nvidia.com/cuda/cublas/#cublasltepilogue-t>`_ for the list of available epilogs.""".replace("\n", " "),
531
+ #
532
+ "epilog_inputs": """\
533
+ Specify the additional inputs needed for the selected epilog as a dictionary, where the key is the epilog input name and
534
+ the value is the epilog input. The epilog input must be a tensor with the same package and in the same memory space as
535
+ the operands (see the constructor for more information on the operands). If the required epilog inputs are not provided,
536
+ an exception is raised that lists the required epilog inputs. Some epilog inputs are generated by other epilogs. For
537
+ example, the epilog input for :class:`MatmulEpilog.DRELU` is generated by matrix multiplication with the same operands
538
+ using :class:`MatmulEpilog.RELU_AUX`. """.replace("\n", " "),
539
+ #
540
+ "qualifiers": """\
541
+ If desired, specify the matrix qualifiers as a :class:`numpy.ndarray` of
542
+ :class:`~nvmath.linalg.advanced.matrix_qualifiers_dtype` objects of length 3 corresponding to the operands `a`, `b`, and
543
+ `c`. See :ref:`matrix-tensor-qualifiers` for the motivation behind
544
+ qualifiers.""".replace("\n", " "),
545
+ #
546
+ "options": """\
547
+ Specify options for the matrix multiplication as a :class:`~nvmath.linalg.advanced.MatmulOptions` object. Alternatively,
548
+ a `dict` containing the parameters for the ``MatmulOptions`` constructor can also be provided. If not specified, the
549
+ value will be set to the default-constructed ``MatmulOptions`` object.""".replace("\n", " "),
550
+ #
551
+ "preferences": """\
552
+ This parameter specifies the preferences for planning as a :class:`MatmulPlanPreferences` object. Alternatively, a
553
+ dictionary containing the parameters for the :class:`MatmulPlanPreferences` constructor can also be provided. If not
554
+ specified, the value will be set to the default-constructed :class:`MatmulPlanPreferences` object.
555
+ """.replace("\n", " "),
556
+ #
557
+ "result": """\
558
+ The result of the specified matrix multiplication (epilog applied), which remains on the same device and belongs to the
559
+ same package as the input operands. If an epilog (like :attr:`nvmath.linalg.advanced.MatmulEpilog.RELU_AUX`) that
560
+ results in extra output is used, or an extra output is requested (for example by setting
561
+ :attr:`~nvmath.linalg.advanced.MatmulOptions.result_amax` option in ``options`` argument),
562
+ a tuple is returned with the first element being the matrix multiplication result (epilog applied) and the second element
563
+ being the auxiliary output provided as a `dict`. """.replace("\n", " "),
564
+ #
565
+ "narrow_precision": """\
566
+
567
+ .. _narrow_precision:
568
+
569
+ Matrix multiplication with narrow-precision operands is supported, in FP8, MXFP8, and NVFP4 formats.
570
+
571
+ **FP8 and MXFP8**
572
+
573
+ FP8 and MXFP8 use ``float8_e4m3fn`` or ``float8_e5m2`` data types. The difference is the scaling mode:
574
+ FP8 (``block_scaling=False``) uses per-tensor scaling where a single scalar scale is applied to each operand;
575
+ MXFP8 (``block_scaling=True``) uses microscaling with 32-element blocks arranged in 128x128 tiles.
576
+
577
+ .. note::
578
+
579
+ FP8 and MXFP8 matrix multiplication requires **CUDA Toolkit 12.8 or newer**.
580
+ **FP8 requires a device with compute capability 8.9 or higher** (Ada, Hopper, Blackwell or newer architecture).
581
+ **MXFP8 requires a device with compute capability 10.0 or higher** (Blackwell or newer architecture).
582
+ Please refer to the `compute capability table <https://developer.nvidia.com/cuda-gpus>`_
583
+ to check the compute capability of your device.
584
+
585
+ For FP8 operations:
586
+
587
+ * For each operand a scaling factor needs to be specified via ``quantization_scales`` argument.
588
+ * Maximum absolute value of the result (amax) can be requested via
589
+ :attr:`~nvmath.linalg.advanced.MatmulOptions.result_amax` option in ``options`` argument.
590
+ * Custom result type (both FP8 and non-FP8) can be requested via
591
+ :attr:`~nvmath.linalg.advanced.MatmulOptions.result_type` option in ``options`` argument.
592
+
593
+ For MXFP8 operations:
594
+
595
+ * 1-D (vector) operands are not supported. Both ``a`` and ``b`` must be at least 2-D matrices.
596
+ * Broadcasting of batch dimensions is not supported. The batch shapes of ``a`` and ``b`` must match exactly.
597
+ * All operand dimensions (M, N, K) must be multiples of 128.
598
+ * :attr:`~nvmath.linalg.advanced.MatmulOptions.block_scaling` option must be set to ``True`` and
599
+ block scaling factors need to be specified via ``quantization_scales`` argument.
600
+ Utilities in :mod:`nvmath.linalg.advanced.helpers.matmul` can be used to create and modify
601
+ block scaling factors, see e.g. :func:`~nvmath.linalg.advanced.helpers.matmul.create_mxfp8_scale`.
602
+ * When the result type is a narrow-precision data type, the auxiliary output ``"d_out_scale"``
603
+ will be returned containing the scales used for result quantization.
604
+
605
+ *Layout Requirements*
606
+
607
+ Due to the requirements of narrow-precision GEMM kernels, the contracting dimension
608
+ K must be contiguous (stride-1) for both operands. The following layout constraints
609
+ apply to both FP8 and MXFP8:
610
+
611
+ * Operand ``a`` must be ``(..., M, K)`` with ``stride[-1] == 1`` and
612
+ ``stride[-2] >= K`` (row-major). The leading dimension (``stride[-2]``) can be
613
+ larger than ``K`` to support sliced or padded views.
614
+
615
+ * Operand ``b`` must be ``(..., K, N)`` with ``stride[-2] == 1`` and
616
+ ``stride[-1] >= K`` (column-major). The leading dimension (``stride[-1]``) can
617
+ be larger than ``K`` to support sliced or padded views.
618
+
619
+ .. attention::
620
+
621
+ Epilog support for MXFP8 is still evolving in the underlying cuBLASLt library,
622
+ so not every combination of epilog, data type, and layout is guaranteed to work.
623
+ If running into unsupported combinations, a cuBLASLt error will be raised
624
+ either at planning time or at execution time that will reveal the
625
+ root cause. These gaps are expected to be filled in future cuBLASLt releases.
626
+
627
+ For more details on the FP8 and MXFP8 formats in cuBLAS,
628
+ see the `cublasLtMatmul documentation <https://docs.nvidia.com/cuda/cublas/#cublasltmatmul>`_.
629
+
630
+ **NVFP4**
631
+
632
+ .. versionadded:: 0.9.0
633
+ NVFP4 support.
634
+
635
+ NVFP4 uses ``float4_e2m1fn_x2`` data type with block scaling (16-element blocks arranged in 128x64 tiles).
636
+
637
+ .. note::
638
+
639
+ NVFP4 matrix multiplication currently requires **CUDA Toolkit 12.8 or newer**,
640
+ **a device with compute capability 10.0 or higher** (Blackwell or newer architecture),
641
+ and **PyTorch 2.9 or newer** for ``float4_e2m1fn_x2`` dtype support.
642
+ Please refer to the `compute capability table <https://developer.nvidia.com/cuda-gpus>`_
643
+ to check the compute capability of your device.
644
+
645
+ For NVFP4 operations:
646
+
647
+ * 1-D (vector) operands are not supported. Both ``a`` and ``b`` must be at least 2-D matrices.
648
+ * Broadcasting of batch dimensions is not supported. The batch shapes of ``a`` and ``b`` must match exactly.
649
+ * The outer dimensions of ``a`` and ``b`` (M and N) must be multiples of 128,
650
+ and the contracting dimension K must be a multiple of 64.
651
+ * :attr:`~nvmath.linalg.advanced.MatmulOptions.block_scaling` option must be set to ``True`` and
652
+ block scaling factors need to be specified via ``quantization_scales`` argument.
653
+ * When the result type is a narrow-precision data type, the auxiliary output ``"d_out_scale"``
654
+ will be returned containing the scales used for result quantization.
655
+
656
+ *Layout and Packing Requirements*
657
+
658
+ FP4 data is per-byte packed: ``float4_e2m1fn_x2`` stores 2 FP4 values per byte.
659
+ The block scaling (VEC16_UE4M3) assigns one scale factor per 16 consecutive elements
660
+ along the innermost (stride-1) dimension of each operand. The layout requirements
661
+ below ensure that this innermost dimension corresponds to the contracting dimension K
662
+ for both operands.
663
+
664
+ * Operand ``a`` must be ``(..., M, K//2)`` with ``stride[-1] == 1`` and
665
+ ``stride[-2] >= K//2``, i.e., row-wise packed along K. Note that the
666
+ leading dimension (``stride[-2]``) can be larger than ``K//2`` to support
667
+ sliced views, as long as the stride remains 16-byte aligned.
668
+
669
+ * Operand ``b`` must be ``(..., K//2, N)`` with ``stride[-2] == 1`` and
670
+ ``stride[-1] >= K//2``, i.e., column-wise packed along K. Note that the
671
+ leading dimension (``stride[-1]``) can be larger than ``K//2`` to support
672
+ sliced views, as long as the stride remains 16-byte aligned.
673
+
674
+ If your data has the stride-1 axis along a dimension other than K,
675
+ you must repack it before calling :func:`matmul`.
676
+
677
+ When the result type is also FP4, the output is packed along a dimension that
678
+ depends on the result layout order:
679
+
680
+ * **Row-major result**: packed along N — shape ``(..., M, N//2)``, strides ``(..., N//2, 1)``.
681
+ * **Column-major result**: packed along M — shape ``(..., M//2, N)``, strides ``(..., 1, M//2)``.
682
+
683
+ The result layout order is determined by the following priority:
684
+
685
+ 1. If ``c`` is provided, the result inherits ``c``'s layout order.
686
+ 2. Otherwise, if the epilog requests a specific layout, that layout is used.
687
+ 3. Otherwise, the result inherits ``a``'s layout order as a fallback.
688
+
689
+ *Epilog Support*
690
+
691
+ NVFP4 matmul supports epilogs. The following have been verified:
692
+
693
+ * ``RELU``, ``GELU`` -- with both row-major and column-major output.
694
+ * ``BIAS``, ``RELU_BIAS``, ``GELU_BIAS`` -- with column-major output only
695
+ (``BIAS`` with ``float16`` C/D requires cuBLASLt >= 13.0).
696
+
697
+ .. attention::
698
+
699
+ Epilog support for NVFP4 is still evolving in the underlying cuBLASLt library,
700
+ so not every combination of epilog, data type, and layout is guaranteed to work.
701
+ If running into unsupported combinations, a cuBLASLt error will be raised
702
+ either at planning time or at execution time that will reveal the
703
+ root cause. These gaps are expected to be filled in future cuBLASLt releases.
704
+
705
+ *Helper Functions*
706
+
707
+ The :mod:`nvmath.linalg.advanced.helpers.matmul` module provides helpers for working with
708
+ FP4 encoding/decoding and NVFP4 block scales, see e.g.
709
+ :func:`~nvmath.linalg.advanced.helpers.matmul.quantize_to_fp4`,
710
+ :func:`~nvmath.linalg.advanced.helpers.matmul.unpack_fp4`,
711
+ :func:`~nvmath.linalg.advanced.helpers.matmul.get_block_scale_offset`,
712
+ :func:`~nvmath.linalg.advanced.helpers.matmul.to_block_scale`,
713
+ :func:`~nvmath.linalg.advanced.helpers.matmul.expand_block_scale`.
714
+
715
+ For more details on the NVFP4 format in cuBLAS,
716
+ see the `cublasLtMatmul documentation <https://docs.nvidia.com/cuda/cublas/#cublasltmatmul>`_.
717
+ For usage examples, see the relevant files in the
718
+ `examples/linalg/advanced/matmul
719
+ <https://github.com/NVIDIA/nvmath-python/tree/main/examples/linalg/advanced/matmul>`_
720
+ directory.
721
+ """.strip(),
722
+ #
723
+ "thread_safety": """\
724
+ A :class:`Matmul` instance should only be used by its creating thread; it is not safe to use
725
+ concurrently from multiple threads. The free function :func:`matmul` creates a fresh
726
+ instance per call and is safe to call concurrently from multiple threads.
727
+ """.replace("\n", " "),
728
+ #
729
+ "semantics": """\
730
+ .. _semantics:
731
+
732
+ The semantics of the matrix multiplication follows :external:py:data:`numpy.matmul` semantics, with some restrictions on
733
+ broadcasting. In addition, the semantics for the fused matrix addition are described below.
734
+
735
+ .. note::
736
+
737
+ For narrow-precision formats (FP8, MXFP8, NVFP4), some of the rules below are
738
+ restricted — see the :ref:`narrow-precision <narrow_precision>` section for details.
739
+
740
+ * For in-place matrix multiplication (where the result is written into `c`) the result has the same shape as `c`.
741
+ * If arguments `a` and `b` are matrices, they are multiplied according to the rules of matrix multiplication.
742
+ * If argument `a` is 1-D, it is promoted to a matrix by prefixing ``1`` to its dimensions. After matrix
743
+ multiplication, the prefixed ``1`` is removed from the result's dimensions if the operation is not in-place.
744
+ * If argument `b` is 1-D, it is promoted to a matrix by appending ``1`` to its dimensions. After matrix
745
+ multiplication, the appended ``1`` is removed from the result's dimensions if the operation is not in-place.
746
+ * If `a` or `b` is N-D (N > 2), then the operand is treated as a batch of matrices. If both `a` and `b` are N-D,
747
+ their batch dimensions must match. If exactly one of `a` or `b` is N-D, the other operand is broadcast.
748
+ * The operand for the matrix addition `c` may be a matrix of shape (M, 1) or (M, N), or the batched versions
749
+ (..., M, 1) or (..., M, N). Here M and N are the dimensions of the result of the matrix multiplication. If N = 1, the
750
+ columns of `c` are broadcast for the addition; the rows of `c` are never broadcast. If batch dimensions are not
751
+ present, `c` is broadcast across batches as needed. If the operation is in-place, `c` cannot be broadcast since
752
+ it must be large enough to hold the result.
753
+ * Similarly, when operating on a batch, auxiliary outputs are 3-D for all epilogs. Therefore, epilogs that return 1-D
754
+ vectors of length N in non-batched mode return 3-D matrices of size (batch, N, 1) in batched mode.
755
+
756
+ For narrow-precision operations (FP8 and lower), further restrictions apply;
757
+ see the narrow-precision support section below.
758
+ """.strip(),
759
+ }
760
+ )
761
+
762
+
763
+ class InvalidMatmulState(Exception):
764
+ pass
765
+
766
+
767
+ def _check_extents(shape: tuple, name: str):
768
+ if any(e <= 0 for e in shape):
769
+ message = f"The specified extents {shape} for operand {name} are not valid. The extents must be strictly positive. "
770
+ raise ValueError(message)
771
+
772
+
773
+ def _detect_and_validate_ab_operands_for_fp4(a, b, logger) -> bool:
774
+ """
775
+ Detect whether A and B are FP4 operands, and if so validate their format.
776
+
777
+ Returns True if both operands are FP4 (float4_e2m1fn_x2), False if neither
778
+ is FP4, and raises ValueError if exactly one is FP4 (mixed operands are not
779
+ supported).
780
+
781
+ When both operands are FP4, the function validates layout and dimensions.
782
+ FP4 data is always packed: float4_e2m1fn_x2 stores 2 FP4 values per byte.
783
+ A and B must be in the following format:
784
+
785
+ - A must be (M, K//2) with stride[-1]==1 and stride[-2] >= K//2, i.e. row-wise
786
+ packed along K. The leading dimension can be larger than K//2, namely
787
+ padded/sliced views are supported.
788
+ - B must be (K//2, N) with stride[-2]==1 and stride[-1] >= K//2, i.e. column-wise
789
+ packed along K. The leading dimension can be larger than K//2, namely
790
+ padded/sliced views are supported.
791
+
792
+ Why packing must be along K:
793
+
794
+ cuBLASLt hardcodes transa=OP_T for MXP4, and expects both A and B to be provided
795
+ in column-major layout. In column-major,
796
+ the stride-1 (innermost) dimension corresponds to the rows of the stored matrix.
797
+ Combined with OP_T, these rows map to the contracting dimension K from the user's
798
+ logical perspective. This means:
799
+
800
+ - User's row-major A (M, K//2) with stride[-1]==1: cuBLASLt interprets this
801
+ as a column-major (K//2, M) matrix (K//2 rows along the stride-1 axis,
802
+ M columns). With transa=OP_T, the logical GEMM operand becomes (M, K),
803
+ with the physical stride-1 axis aligned to the contraction dimension K.
804
+ - User's column-major B (K//2, N) with stride[-2]==1: cuBLASLt interprets
805
+ this as a column-major (K//2, N) matrix directly. With transb=OP_N
806
+ (the default), the logical GEMM operand is (K, N), again with the
807
+ physical stride-1 axis aligned to K.
808
+
809
+ NVFP4 block scaling (VEC16_UE4M3) assigns one scale per 16 elements along the
810
+ innermost (stride-1) dimension. Because of the layout above, this innermost
811
+ dimension is K, so the scales are naturally aligned with the contraction axis.
812
+
813
+ Dimension requirements:
814
+ - M (outer dim of A): must be a multiple of 128
815
+ - N (outer dim of B): must be a multiple of 128
816
+ - K (contraction dim): must be a multiple of 64
817
+ """
818
+ a_is_fp4 = a.dtype == "float4_e2m1fn_x2"
819
+ b_is_fp4 = b.dtype == "float4_e2m1fn_x2"
820
+
821
+ # Neither is FP4 means this is not an FP4 operation
822
+ if not a_is_fp4 and not b_is_fp4:
823
+ return False
824
+
825
+ # One is FP4 and the other is not: unsupported
826
+ if a_is_fp4 != b_is_fp4:
827
+ raise ValueError(
828
+ f"Mixed FP4/non-FP4 A/B operands are not supported. "
829
+ f"Got A dtype={a.dtype}, B dtype={b.dtype}. "
830
+ f"Both A and B operands must be float4_e2m1fn_x2 or neither."
831
+ )
832
+
833
+ logger.info(f"FP4 validation: A shape={a.shape}, strides={a.strides}")
834
+ logger.info(f"FP4 validation: B shape={b.shape}, strides={b.strides}")
835
+
836
+ if len(a.shape) < 2:
837
+ raise ValueError(f"FP4 operand A must be at least 2-D, got shape {a.shape}.")
838
+ if len(b.shape) < 2:
839
+ raise ValueError(f"FP4 operand B must be at least 2-D, got shape {b.shape}.")
840
+
841
+ # Validate A: Must be row-major (..., M, K//2) with strides (..., K//2, 1)
842
+ if a.strides[-1] != 1:
843
+ raise ValueError(f"FP4 operand A must be row-major with stride[-1]=1. Got shape {a.shape} with strides {a.strides}.")
844
+
845
+ # Validate B: Must be column-major (..., K//2, N) with strides (..., 1, K//2)
846
+ if b.strides[-2] != 1:
847
+ raise ValueError(
848
+ f"FP4 operand B must be column-major with stride[-2]=1. "
849
+ f"Got shape {b.shape} with strides {b.strides}. "
850
+ f"Use torch.as_strided() to create column-major view."
851
+ )
852
+
853
+ # Extract dimensions from packed tensors:
854
+ # A is (M, K//2) -> M = a.shape[-2], K = a.shape[-1] * 2
855
+ # B is (K//2, N) -> N = b.shape[-1], K = b.shape[-2] * 2
856
+ M = a.shape[-2]
857
+ K_from_a = a.shape[-1] * 2 # Unpack: K//2 -> K
858
+ K_from_b = b.shape[-2] * 2 # Unpack: K//2 -> K
859
+ N = b.shape[-1]
860
+
861
+ # K should match between A and B
862
+ if K_from_a != K_from_b:
863
+ raise ValueError(
864
+ f"Dimension mismatch: K from A ({K_from_a}) != K from B ({K_from_b}). "
865
+ f"A shape is {a.shape} (M, K//2), B shape is {b.shape} (K//2, N)."
866
+ )
867
+ K = K_from_a
868
+
869
+ logger.info(f"FP4 dimensions: M={M}, N={N}, K={K}")
870
+
871
+ # Validate block scaling dimension requirements
872
+ errors = []
873
+ if M % 128 != 0:
874
+ errors.append(f"M={M} must be divisible by 128")
875
+ if N % 128 != 0:
876
+ errors.append(f"N={N} must be divisible by 128")
877
+ if K % 64 != 0:
878
+ errors.append(f"K={K} must be divisible by 64")
879
+
880
+ if errors:
881
+ raise ValueError(
882
+ f"FP4 block scaling dimension requirements not met: {', '.join(errors)}. "
883
+ f"NVFP4 requires M and N divisible by 128, K divisible by 64."
884
+ )
885
+
886
+ return True
887
+
888
+
889
+ def _create_fp4_ab_layouts(a_shape, a_strides, a_is_conjugate, b_shape, b_strides, b_is_conjugate):
890
+ """
891
+ Create MatrixLayout objects for packed FP4 operands A and B.
892
+
893
+ cuBLASLt always computes A^T @ B (transa=OP_T is hardcoded). The user provides
894
+ A as (M, K//2) row-wise packed and B as (K//2, N) column-wise packed. We convert
895
+ these to logical shapes/strides that cuBLASLt expects:
896
+
897
+ - A is reinterpreted as (K//2, M) internally (swap last two dims), so that
898
+ cuBLASLt computes (A^T)^T @ B = A @ B.
899
+ - B is kept as is, but strides are converted from packed to logical.
900
+
901
+ Since float4_e2m1fn_x2 packs 2 values per byte, logical strides are 2x the
902
+ packed strides along the K dimension.
903
+
904
+ Args:
905
+ a_shape: Physical shape of A, e.g. (..., M, K//2).
906
+ a_strides: Physical strides of A.
907
+ a_is_conjugate: Whether A is conjugated.
908
+ b_shape: Physical shape of B, e.g. (..., K//2, N).
909
+ b_strides: Physical strides of B.
910
+ b_is_conjugate: Whether B is conjugated.
911
+
912
+ Returns:
913
+ (a_layout, b_layout) — MatrixLayout objects with logical shapes/strides.
914
+ """
915
+ M, K_packed = a_shape[-2], a_shape[-1]
916
+ K_logical = K_packed * 2
917
+
918
+ # A: swap last two stride dimensions (transpose for cuBLASLt), then convert to logical
919
+ a_transposed_strides = (*a_strides[:-2], a_strides[-1], a_strides[-2])
920
+ a_logical_shape = (*a_shape[:-2], M, K_logical)
921
+ a_batch_strides = tuple(s * 2 for s in a_transposed_strides[:-2])
922
+ a_logical_strides = (*a_batch_strides, a_transposed_strides[-1] * 2, a_transposed_strides[-2])
923
+
924
+ # B: keep dimension order, convert packed strides to logical
925
+ N = b_shape[-1]
926
+ b_logical_shape = (*b_shape[:-2], K_logical, N)
927
+ b_batch_strides = tuple(s * 2 for s in b_strides[:-2])
928
+ b_logical_strides = (*b_batch_strides, b_strides[-2], b_strides[-1] * 2)
929
+
930
+ a_layout = MatrixLayout(a_logical_shape, a_logical_strides, a_is_conjugate)
931
+ b_layout = MatrixLayout(b_logical_shape, b_logical_strides, b_is_conjugate)
932
+ return a_layout, b_layout
933
+
934
+
935
+ def _create_d_out_scale_and_scale_mode(result_class, num_output_elements, d_dtype_width, device_id, stream_holder):
936
+ """
937
+ Create the d_out_scale tensor and determine the scale mode for block-scaled output.
938
+ Block-scaled narrow-precision output (FP4 or FP8) requires a scale tensor where each
939
+ scale covers a group of output elements:
940
+
941
+ - FP4 (VEC16_UE4M3): each scale covers 16 elements, stored as ``float8_e4m3fn``
942
+ - FP8 (VEC32_UE8M0): each scale covers 32 elements, stored as ``uint8``.
943
+
944
+ Args:
945
+ result_class: The tensor class used to create the output tensor.
946
+ num_output_elements: Total number of output elements.
947
+ d_dtype_width: Result dtype width.
948
+ device_id: The CUDA device id.
949
+ stream_holder: The stream holder for tensor allocation.
950
+
951
+ Returns:
952
+ (d_out_scale_tensor, d_out_scale_mode) — the allocated scale tensor and the
953
+ corresponding ``cublaslt.MatmulMatrixScale`` mode.
954
+ """
955
+ if d_dtype_width == 4:
956
+ scale_mode = cublaslt.MatmulMatrixScale.VEC16_UE4M3
957
+ scale_group_size = 16
958
+ scale_dtype = "float8_e4m3fn" # UE4M3 format, consistent with input A/B scales
959
+ else:
960
+ assert d_dtype_width == 8, "Internal error."
961
+ scale_mode = cublaslt.MatmulMatrixScale.VEC32_UE8M0
962
+ scale_group_size = 32
963
+ scale_dtype = "uint8" # UE8M0 format
964
+
965
+ num_scales = num_output_elements // scale_group_size
966
+ d_out_scale = utils.create_empty_tensor(
967
+ result_class,
968
+ (num_scales,),
969
+ scale_dtype,
970
+ device_id,
971
+ stream_holder,
972
+ verify_strides=False,
973
+ )
974
+ return d_out_scale, scale_mode
975
+
976
+
977
+ def _realloc_if_needed_and_copy_to_mirror(src_holder, dest_holder, destination_device_id, stream_holder):
978
+ """
979
+ Copy a CPU source operand into its device-side mirror (``dest_holder``).
980
+
981
+ Two cases:
982
+
983
+ * **Buffer exists** (``dest_holder.tensor is not None``): copy the
984
+ source data into the existing device buffer in-place via ``copy_()``.
985
+ * **Buffer released** (``dest_holder.tensor is None``, e.g. after
986
+ ``release_operands()``): call ``src_holder.to()`` to allocate a new
987
+ device buffer and copy the data into it, then assign the underlying
988
+ raw tensor to ``dest_holder.tensor``. The ``dest_holder`` wrapper
989
+ object itself is never replaced, so its concrete type is preserved.
990
+
991
+ Args:
992
+ src_holder: Wrapped CPU source operand.
993
+ dest_holder: Device-side tensor wrapper whose ``.tensor`` may be None.
994
+ Note: ``dest_holder.device_id`` is not usable when ``.tensor`` is
995
+ None, hence the explicit ``destination_device_id`` parameter.
996
+ destination_device_id: CUDA device ordinal (int, never ``"cpu"``)
997
+ since this function is only used for CPU-to-GPU mirroring.
998
+ stream_holder: Stream wrapper for the copy / allocation.
999
+
1000
+ Returns:
1001
+ True if a new buffer was allocated (data pointer changed),
1002
+ False if the existing buffer was reused via in-place copy.
1003
+ """
1004
+ if dest_holder.tensor is not None:
1005
+ dest_holder.copy_(src_holder, stream_holder=stream_holder)
1006
+ return False
1007
+ dest_holder.tensor = src_holder.to(destination_device_id, stream_holder).tensor
1008
+ return True
1009
+
1010
+
1011
+ @utils.docstring_decorator(SHARED_MM_DOCUMENTATION, skip_missing=False)
1012
+ class Matmul:
1013
+ """
1014
+ Create a stateful object encapsulating the specified matrix multiplication computation
1015
+ :math:`\\alpha a @ b + \\beta c` and the required resources to perform the operation. A
1016
+ stateful object can be used to amortize the cost of preparation (planning in the case of
1017
+ matrix multiplication) across multiple executions (also see the :ref:`Stateful APIs
1018
+ <host api types>` section).
1019
+
1020
+ The function-form API :func:`matmul` is a convenient alternative to using stateful
1021
+ objects for *single* use (the user needs to perform just one matrix multiplication, for
1022
+ example), in which case there is no possibility of amortizing preparatory costs. The
1023
+ function-form APIs are just convenience wrappers around the stateful object APIs.
1024
+
1025
+ Using the stateful object typically involves the following steps:
1026
+
1027
+ 1. **Problem Specification**: Initialize the object with a defined operation and
1028
+ options.
1029
+ 2. **Preparation**: Use :meth:`plan` to determine the best algorithmic implementation
1030
+ for this specific matrix multiplication operation.
1031
+ 3. **Execution**: Perform the matrix multiplication computation with :meth:`execute`.
1032
+ 4. **Resource Management**: Ensure all resources are released either by explicitly
1033
+ calling :meth:`free` or by managing the stateful object within a context manager.
1034
+
1035
+ Detailed information on what's happening in the various phases described above can be
1036
+ obtained by passing in a :class:`logging.Logger` object to :class:`MatmulOptions` or by
1037
+ setting the appropriate options in the root logger object, which is used by default:
1038
+
1039
+ >>> import logging
1040
+ >>> logging.basicConfig(
1041
+ ... level=logging.INFO,
1042
+ ... format="%(asctime)s %(levelname)-8s %(message)s",
1043
+ ... datefmt="%m-%d %H:%M:%S",
1044
+ ... )
1045
+
1046
+ A user can select the desired logging level and, in general, take advantage of all of
1047
+ the functionality offered by the Python `logging` module.
1048
+
1049
+ Args:
1050
+ a: {a}
1051
+
1052
+ b: {b}
1053
+
1054
+ c: {c}
1055
+ {c_admonitions}
1056
+
1057
+ alpha: {alpha}
1058
+
1059
+ beta: {beta}
1060
+
1061
+ qualifiers: {qualifiers}
1062
+
1063
+ options: {options}
1064
+
1065
+ stream: {stream}
1066
+
1067
+ quantization_scales: {quantization_scales}
1068
+
1069
+ Semantics:
1070
+ {semantics}
1071
+
1072
+ Narrow-precision support:
1073
+ {narrow_precision}
1074
+
1075
+ Thread Safety:
1076
+ {thread_safety}
1077
+
1078
+ .. seealso::
1079
+ :meth:`autotune`, :meth:`plan`, :meth:`reset_operands`,
1080
+ :meth:`reset_operands_unchecked`, :meth:`execute`
1081
+
1082
+ Examples:
1083
+
1084
+ >>> import numpy as np
1085
+ >>> import nvmath
1086
+
1087
+ Create two 2-D float64 ndarrays on the CPU:
1088
+
1089
+ >>> M, N, K = 1024, 1024, 1024
1090
+ >>> a = np.random.rand(M, K)
1091
+ >>> b = np.random.rand(K, N)
1092
+
1093
+ We will define a matrix multiplication operation followed by a RELU epilog function
1094
+ using the specialized matrix multiplication interface.
1095
+
1096
+ Create a Matmul object encapsulating the problem specification above:
1097
+
1098
+ >>> mm = nvmath.linalg.advanced.Matmul(a, b)
1099
+
1100
+ Options can be provided above to control the behavior of the operation using the
1101
+ `options` argument (see :class:`MatmulOptions`).
1102
+
1103
+ Next, plan the operation. The epilog is specified, and optionally, preferences can
1104
+ be specified for planning:
1105
+
1106
+ >>> epilog = nvmath.linalg.advanced.MatmulEpilog.RELU
1107
+ >>> algorithms = mm.plan(epilog=epilog)
1108
+
1109
+ Certain epilog choices (like :attr:`nvmath.linalg.advanced.MatmulEpilog.BIAS`)
1110
+ require additional input provided using the `epilog_inputs` argument to
1111
+ :meth:`plan`.
1112
+
1113
+ Now execute the matrix multiplication, and obtain the result `r1` as a NumPy
1114
+ ndarray.
1115
+
1116
+ >>> r1 = mm.execute()
1117
+
1118
+ Finally, free the object's resources. To avoid having to explicitly make this
1119
+ call, it's recommended to use the Matmul object as a context manager as shown below,
1120
+ if possible.
1121
+
1122
+ >>> mm.free()
1123
+
1124
+ Note that all :class:`Matmul` methods execute on the current stream by default.
1125
+ Alternatively, the `stream` argument can be used to run a method on a specified
1126
+ stream.
1127
+
1128
+ Let's now look at the same problem with CuPy ndarrays on the GPU.
1129
+
1130
+ >>> import cupy as cp
1131
+ >>> a = cp.random.rand(M, K)
1132
+ >>> b = cp.random.rand(K, N)
1133
+
1134
+ Create an Matmul object encapsulating the problem specification described earlier
1135
+ and use it as a context manager.
1136
+
1137
+ >>> with nvmath.linalg.advanced.Matmul(a, b) as mm:
1138
+ ... algorithms = mm.plan(epilog=epilog)
1139
+ ...
1140
+ ... # Execute the operation to get the first result.
1141
+ ... r1 = mm.execute()
1142
+ ...
1143
+ ... # Update operands 'a' and 'b' in-place (see reset_operands() for an
1144
+ ... # alternative).
1145
+ ... a[:] = cp.random.rand(M, K)
1146
+ ... b[:] = cp.random.rand(K, N)
1147
+ ...
1148
+ ... # Execute the operation to get the new result.
1149
+ ... r2 = mm.execute()
1150
+
1151
+
1152
+ All the resources used by the object are released at the end of the block.
1153
+
1154
+ Further examples can be found in the `nvmath/examples/linalg/advanced/matmul
1155
+ <https://github.com/NVIDIA/nvmath-python/tree/main/examples/linalg/advanced/matmul>`_
1156
+ directory.
1157
+ """
1158
+
1159
+ def __init__(
1160
+ self,
1161
+ a,
1162
+ b,
1163
+ /,
1164
+ c=None,
1165
+ *,
1166
+ alpha=None,
1167
+ beta=None,
1168
+ qualifiers=None,
1169
+ quantization_scales=None,
1170
+ options: _configuration.MatmulOptions | dict[str, typing.Any] | None = None,
1171
+ stream: utils.AnyStream | int | None = None,
1172
+ ):
1173
+ options = utils.check_or_create_options(_configuration.MatmulOptions, options, "Matrix multiplication options")
1174
+ assert options is not None
1175
+ self.options = options
1176
+
1177
+ if c is None and options.inplace:
1178
+ raise ValueError("The operation cannot be inplace if operand C is not provided.")
1179
+
1180
+ self.logger = options.logger if options.logger is not None else logging.getLogger()
1181
+
1182
+ if options.inplace and options.result_type is not None:
1183
+ self.logger.warning(
1184
+ f"Matmul: The provided result type {options.result_type} in options is ignored since \
1185
+ the operation is in-place."
1186
+ )
1187
+ self.inplace = options.inplace
1188
+
1189
+ def check_dtype(dtype, operand_name):
1190
+ if dtype not in SUPPORTED_TYPES:
1191
+ raise ValueError(f"The dtype of operand {operand_name} ({dtype}) is not supported.")
1192
+
1193
+ # The matrix multiplication has two required operands 'a' and 'b', and one optional
1194
+ # operand 'c'.
1195
+ a = tensor_wrapper.wrap_operand(a)
1196
+ b = tensor_wrapper.wrap_operand(b)
1197
+ check_dtype(a.dtype, "A")
1198
+ check_dtype(b.dtype, "B")
1199
+ self.logger.info("= SPECIFICATION PHASE =")
1200
+ if self.inplace:
1201
+ self.logger.info("The MM operation will be performed in-place (the result will be written into operand C).")
1202
+ self.logger.info(f"The data type of operand A is '{a.dtype}', and that of operand B is '{b.dtype}'.")
1203
+
1204
+ # Detect FP4 A/B operands, and validate compatibility/format.
1205
+ # This check is done as early as possible.
1206
+ self.using_fp4_ab = _detect_and_validate_ab_operands_for_fp4(a, b, self.logger)
1207
+ if self.using_fp4_ab and not options.block_scaling:
1208
+ # FP4 only supports block scaling, at least for now
1209
+ raise ValueError(
1210
+ f"When using FP4 (float4_e2m1fn_x2) A, B operands, block_scaling=True is required. "
1211
+ f"Got block_scaling={options.block_scaling}."
1212
+ )
1213
+
1214
+ self.num_operands = 2
1215
+ if c is not None:
1216
+ self.num_operands = 3
1217
+ c = tensor_wrapper.wrap_operand(c)
1218
+ if len(c.shape) < 2:
1219
+ raise ValueError(
1220
+ "In order to avoid broadcasting behavior ambiguity, `c` must be at least 2-D. "
1221
+ "Use a singleton dimension to convert your input array to 2-D."
1222
+ )
1223
+ check_dtype(c.dtype, "C")
1224
+ self.logger.info(f"The data type of operand C is {c.dtype}.")
1225
+
1226
+ if c is not None and beta is None:
1227
+ raise ValueError("A value for beta must be provided if operand C is provided.")
1228
+
1229
+ if (a.dtype, b.dtype) not in NAMES_TO_DEFAULT_SCALE_TYPE:
1230
+ raise ValueError(f"Unsupported combination of dtypes for operands A {a.dtype} and B {b.dtype}.")
1231
+
1232
+ # Currently, a.dtype != b.dtype is only supported for FP8 (different FP8 kinds are
1233
+ # allowed), so we assume that A and B have equal width.
1234
+ self.input_type_width = typemaps.NAME_TO_DATA_WIDTH[a.dtype]
1235
+
1236
+ assert self.num_operands == 2 or self.num_operands == 3, "Internal Error."
1237
+
1238
+ _check_extents(a.shape, "a")
1239
+ _check_extents(b.shape, "b")
1240
+ if c is not None:
1241
+ _check_extents(c.shape, "c")
1242
+
1243
+ # Infer the library package & device ID the operands belong to.
1244
+ operands = [a, b]
1245
+ if self.num_operands == 3:
1246
+ operands.append(c)
1247
+ self.operands: MutableSequence[utils.TensorHolder] | None = operands
1248
+
1249
+ self.package = utils.get_operands_package(operands)
1250
+ # Package used for internal operations (stream + allocator). NumPy uses cuda.core.
1251
+ self.internal_op_package = "cuda" if self.package == "numpy" else self.package
1252
+ self.memory_space = "cuda"
1253
+ self.device_id = utils.get_operands_device_id(operands)
1254
+ if self.device_id == "cpu":
1255
+ self.memory_space = "cpu"
1256
+ self.device_id = options.device_id
1257
+ self.logger.info(
1258
+ f"The input operands' memory space is {self.memory_space}, and the execution space is on device {self.device_id}."
1259
+ )
1260
+
1261
+ # Allocate device memory (in stream context) if needed.
1262
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
1263
+ self.logger.info(f"The specified stream for the Matmul ctor is {stream_holder.obj}.")
1264
+
1265
+ # Copy operands to device (and store reference to CPU operand), if needed.
1266
+ self.cpu_c_ref = None
1267
+ if self.memory_space == "cpu":
1268
+ if self.inplace:
1269
+ self.cpu_c_ref = self.operands[2] # Hold reference, needed for inplace operations.
1270
+ self.operands = list(tensor_wrapper.to(self.operands, self.device_id, stream_holder))
1271
+
1272
+ # Set qualifiers.
1273
+ self.qualifiers = qualifiers if qualifiers is not None else np.zeros((3,), dtype=_configuration.matrix_qualifiers_dtype)
1274
+ if self.qualifiers.dtype != _configuration.matrix_qualifiers_dtype:
1275
+ raise ValueError(
1276
+ "The qualifiers must be specified as a NumPy array of length 3 corresponding to the operands A, B, and "
1277
+ "C of type 'matrix_qualifiers_dtype'."
1278
+ )
1279
+ # Set qualifiers based on torch lazy conjugation flag if not provided.
1280
+ self.qualifiers[0]["is_conjugate"] = self.qualifiers[0]["is_conjugate"] ^ self.operands[0].is_conjugate
1281
+ self.qualifiers[1]["is_conjugate"] = self.qualifiers[1]["is_conjugate"] ^ self.operands[1].is_conjugate
1282
+ self.lazy_conjugation = (self.operands[0].is_conjugate, self.operands[1].is_conjugate, False)
1283
+ if self.num_operands == 3:
1284
+ self.qualifiers[2]["is_conjugate"] = self.qualifiers[2]["is_conjugate"] ^ self.operands[2].is_conjugate
1285
+ if self.qualifiers[2]["is_conjugate"]:
1286
+ raise ValueError("The conjugate flag is currently not supported for operand C.")
1287
+
1288
+ # Set blocking or non-blocking behavior.
1289
+ self.blocking = self.options.blocking is True or self.memory_space == "cpu"
1290
+ if self.blocking:
1291
+ self.call_prologue = "This call is blocking and will return only after the operation is complete."
1292
+ else:
1293
+ self.call_prologue = (
1294
+ "This call is non-blocking and will return immediately after the operation is launched on the device."
1295
+ )
1296
+
1297
+ # The result class is that of the first wrapped device operand.
1298
+ self.result_class = self.operands[0].__class__
1299
+
1300
+ # Set memory allocator.
1301
+ self.allocator = (
1302
+ options.allocator
1303
+ if options.allocator is not None
1304
+ else memory._MEMORY_MANAGER[self.internal_op_package](self.device_id, self.logger)
1305
+ )
1306
+
1307
+ # Set memory limit.
1308
+ self.memory_limit = utils.get_memory_limit_from_device_id(self.options.memory_limit, self.device_id)
1309
+ self.logger.info(f"The memory limit is {formatters.MemoryStr(self.memory_limit)}.")
1310
+
1311
+ # Set handle. We don't destroy handles we create.
1312
+ if options.handle is not None:
1313
+ self.handle = options.handle
1314
+ else:
1315
+ self.handle = get_handle(self.device_id)
1316
+
1317
+ # Determine the data types for a and b.
1318
+ self.a_dtype = typemaps.NAME_TO_DATA_TYPE[a.dtype]
1319
+ self.b_dtype = typemaps.NAME_TO_DATA_TYPE[b.dtype]
1320
+ self.a_dtype_name = a.dtype
1321
+ self.b_dtype_name = b.dtype
1322
+
1323
+ self.is_complex = "complex" in self.a_dtype_name or "complex" in self.b_dtype_name
1324
+
1325
+ # Determine the data types for c and d.
1326
+ self.d_dtype = None if self.inplace else options.result_type
1327
+ if self.num_operands == 3:
1328
+ self.c_dtype = typemaps.NAME_TO_DATA_TYPE[c.dtype]
1329
+ if self.d_dtype is None:
1330
+ self.d_dtype = self.c_dtype
1331
+
1332
+ elif self.num_operands == 2:
1333
+ if self.d_dtype is None:
1334
+ self.d_dtype = self.a_dtype
1335
+
1336
+ # c_dtype matches d_dtype, except if output is FP4/FP8, then C uses float16
1337
+ if self.d_dtype in (CudaDataType.CUDA_R_4F_E2M1, CudaDataType.CUDA_R_8F_E5M2, CudaDataType.CUDA_R_8F_E4M3):
1338
+ self.c_dtype = CudaDataType.CUDA_R_16F
1339
+ else:
1340
+ self.c_dtype = self.d_dtype
1341
+
1342
+ self.c_dtype_name = typemaps.DATA_TYPE_TO_NAME[self.c_dtype]
1343
+ self.d_dtype_name = typemaps.DATA_TYPE_TO_NAME[self.d_dtype]
1344
+ self.c_dtype_width = typemaps.NAME_TO_DATA_WIDTH[self.c_dtype_name]
1345
+ self.d_dtype_width = typemaps.NAME_TO_DATA_WIDTH[self.d_dtype_name]
1346
+
1347
+ self.logger.info(f"The data type for the result D is '{self.d_dtype_name}'.")
1348
+
1349
+ def assert_valid_compute_type(compute_type):
1350
+ if compute_type not in COMPUTE_TYPE_TO_DEFAULT_SCALE_TYPE["real"]:
1351
+ message = f"Unsupported compute type. The compute type '{repr(compute_type)}' is currently not supported."
1352
+ raise ValueError(message)
1353
+
1354
+ # Determine the scale type.
1355
+ if options.scale_type is None:
1356
+ if options.compute_type is not None:
1357
+ assert_valid_compute_type(options.compute_type)
1358
+ if self.is_complex:
1359
+ scale_type_map = COMPUTE_TYPE_TO_DEFAULT_SCALE_TYPE["complex"]
1360
+ else:
1361
+ scale_type_map = COMPUTE_TYPE_TO_DEFAULT_SCALE_TYPE["real"]
1362
+ self.scale_type = scale_type_map[options.compute_type]
1363
+ else:
1364
+ self.scale_type = NAMES_TO_DEFAULT_SCALE_TYPE[(self.a_dtype_name, self.b_dtype_name)]
1365
+ self.scale_type_name = typemaps.DATA_TYPE_TO_NAME[self.scale_type]
1366
+ else:
1367
+ self.scale_type = options.scale_type
1368
+ if self.scale_type not in SCALE_TYPE_TO_DEFAULT_COMPUTE_TYPE:
1369
+ message = f"Unsupported scale type. The data type '{repr(self.scale_type)}' is currently not supported."
1370
+ raise ValueError(message)
1371
+ self.scale_type_name = typemaps.DATA_TYPE_TO_NAME[self.scale_type]
1372
+ self.logger.info(f"The scale type is '{self.scale_type_name}'.")
1373
+
1374
+ # Determine the compute type.
1375
+ if options.compute_type is None:
1376
+ if options.scale_type is not None:
1377
+ self.compute_type = SCALE_TYPE_TO_DEFAULT_COMPUTE_TYPE[options.scale_type]
1378
+ else:
1379
+ self.compute_type = NAMES_TO_DEFAULT_COMPUTE_TYPE[(self.a_dtype_name, self.b_dtype_name)]
1380
+ else:
1381
+ self.compute_type = options.compute_type
1382
+ assert_valid_compute_type(self.compute_type)
1383
+ self.logger.info(f"The compute type is {self.compute_type.name}.")
1384
+
1385
+ def is_supported(atype, btype, compute_type, scale_type):
1386
+ ct = cublas.ComputeType
1387
+ st = CudaDataType
1388
+ abtype = atype if atype == btype else (atype, btype)
1389
+ if compute_type in (ct.COMPUTE_16F, ct.COMPUTE_16F_PEDANTIC):
1390
+ return scale_type == st.CUDA_R_16F and abtype == "float16"
1391
+ elif compute_type == ct.COMPUTE_32F_PEDANTIC:
1392
+ if scale_type == st.CUDA_R_32F:
1393
+ return abtype in ("float32", "bfloat16", "float16", "float8_e4m3fn", "float8_e5m2")
1394
+ elif scale_type == st.CUDA_C_32F:
1395
+ return abtype == "complex64"
1396
+ elif compute_type == ct.COMPUTE_32F:
1397
+ if scale_type == st.CUDA_R_32F:
1398
+ return abtype in (
1399
+ "float32",
1400
+ "bfloat16",
1401
+ "float16",
1402
+ "float8_e4m3fn",
1403
+ "float8_e5m2",
1404
+ ("float8_e4m3fn", "float8_e5m2"),
1405
+ ("float8_e5m2", "float8_e4m3fn"),
1406
+ )
1407
+ elif scale_type == st.CUDA_C_32F:
1408
+ return abtype == "complex64"
1409
+ elif compute_type in (
1410
+ ct.COMPUTE_32F_FAST_16F,
1411
+ ct.COMPUTE_32F_FAST_16BF,
1412
+ ct.COMPUTE_32F_FAST_TF32,
1413
+ ct.COMPUTE_32F_EMULATED_16BFX9,
1414
+ ):
1415
+ if scale_type == st.CUDA_R_32F:
1416
+ return abtype == "float32"
1417
+ if scale_type == st.CUDA_C_32F:
1418
+ return abtype == "complex64"
1419
+ elif compute_type in (ct.COMPUTE_64F, ct.COMPUTE_64F_PEDANTIC, ct.COMPUTE_64F_EMULATED_FIXEDPOINT):
1420
+ if scale_type == st.CUDA_R_64F:
1421
+ return abtype == "float64"
1422
+ if scale_type == st.CUDA_C_64F:
1423
+ return abtype == "complex128"
1424
+ return False
1425
+
1426
+ def is_supported_nvfp4(ctype, dtype, compute_type, scale_type):
1427
+ """
1428
+ Validate type combinations based on cuBLAS documentation.
1429
+ https://docs.nvidia.com/cuda/cublas/index.html#id105,
1430
+ see Table 4 and related text.
1431
+ """
1432
+ ct = cublas.ComputeType
1433
+ st = CudaDataType
1434
+
1435
+ # Check compute/scale types
1436
+ if not (compute_type == ct.COMPUTE_32F and scale_type == st.CUDA_R_32F):
1437
+ raise ValueError(
1438
+ f"Selected scale_type={repr(self.scale_type)} compute_type={repr(self.compute_type)} "
1439
+ f"are not supported. Only the following combination is supported: "
1440
+ f"A and B must both be float4_e2m1fn_x2, compute_type=COMPUTE_32F, scale_type=CUDA_R_32F."
1441
+ )
1442
+
1443
+ # Check valid C/D type combinations (Table 4)
1444
+ valid_cd_combos = {
1445
+ ("bfloat16", "bfloat16"),
1446
+ ("bfloat16", "float4_e2m1fn_x2"),
1447
+ ("float16", "float16"),
1448
+ ("float16", "float4_e2m1fn_x2"),
1449
+ ("float32", "float32"),
1450
+ }
1451
+ if (ctype, dtype) not in valid_cd_combos:
1452
+ raise ValueError(
1453
+ f"Invalid C/D type combination for FP4: ctype={self.c_dtype_name}, dtype={self.d_dtype_name}. "
1454
+ f"Valid combinations are: (bfloat16, bfloat16), (bfloat16, float4_e2m1fn_x2), "
1455
+ f"(float16, float16), (float16, float4_e2m1fn_x2), (float32, float32). "
1456
+ f"See cuBLAS documentation Table 4."
1457
+ )
1458
+
1459
+ if self.using_fp4_ab:
1460
+ # Validate remaining type combinations (A and B are already
1461
+ # known to be float4_e2m1fn_x2)
1462
+ is_supported_nvfp4(self.c_dtype_name, self.d_dtype_name, self.compute_type, self.scale_type)
1463
+ elif not is_supported(self.a_dtype_name, self.b_dtype_name, self.compute_type, self.scale_type):
1464
+ raise ValueError(
1465
+ f"Selected scale_type={repr(self.scale_type)} compute_type={repr(self.compute_type)} "
1466
+ + f"are not supported for data types {self.a_dtype_name} (A) and {self.b_dtype_name} (B)."
1467
+ )
1468
+
1469
+ # Set alpha and beta.
1470
+ self.alpha = np.zeros((1,), dtype=self.scale_type_name)
1471
+ try:
1472
+ self.alpha[0] = alpha if alpha is not None else 1
1473
+ except (ValueError, TypeError) as e:
1474
+ raise ValueError(f"The value provided for alpha {alpha} is not convertible to dtype '{self.alpha.dtype}'.") from e
1475
+
1476
+ self.beta = np.zeros((1,), dtype=self.scale_type_name)
1477
+ if beta is not None and self.num_operands == 2:
1478
+ self.logger.warning(f"Matmul: The provided beta value {beta} is ignored since operand C is not specified.")
1479
+ try:
1480
+ self.beta[0] = beta if beta is not None and self.num_operands == 3 else 0
1481
+ except (ValueError, TypeError) as e:
1482
+ raise ValueError(f"The value provided for beta {beta} is not convertible to dtype '{self.beta.dtype}'.") from e
1483
+
1484
+ # Set narrow-precision (FP8 and lower) quantization_scales.
1485
+ if self.input_type_width <= 8:
1486
+ self.quantization_scales = self._validate_operand_scales(quantization_scales, all_required=True)
1487
+ elif quantization_scales is not None:
1488
+ self.logger.warning(
1489
+ "Matmul: The provided scales are ignored, since they are only applicable to narrow-precision (FP8 and lower) "
1490
+ "operations."
1491
+ )
1492
+
1493
+ if self.options.result_amax and self.d_dtype_width > 8:
1494
+ raise ValueError("result_amax=True is allowed only for narrow-precision (FP8 and lower) results")
1495
+
1496
+ # Check operands alignment if needed
1497
+ if self.input_type_width <= 8:
1498
+ for operand, operand_name in zip(self.operands, "ABC", strict=False):
1499
+ if operand.data_ptr % 16 != 0:
1500
+ raise ValueError(
1501
+ f"For narrow-precision (FP8 and lower) multiplication, operand {operand_name} should be aligned to 16 "
1502
+ "bytes."
1503
+ )
1504
+
1505
+ # Capture physical operand extents and strides for consistency check when resetting
1506
+ # operands. In the case of FP4, these must be the packed (physical) values,
1507
+ # not the logical ones , because reset() receives packed FP4 tensors
1508
+ # and must compare against the same physical format.
1509
+ # Hence, these two do not need special handling for FP4.
1510
+ self.operand_extents = tuple(o.shape for o in self.operands)
1511
+ self.operand_strides = tuple(o.strides for o in self.operands)
1512
+
1513
+ if self.using_fp4_ab:
1514
+ a_layout, b_layout = _create_fp4_ab_layouts(
1515
+ self.operands[0].shape,
1516
+ self.operands[0].strides,
1517
+ self.qualifiers[0]["is_conjugate"],
1518
+ self.operands[1].shape,
1519
+ self.operands[1].strides,
1520
+ self.qualifiers[1]["is_conjugate"],
1521
+ )
1522
+ self.logger.info(f"A: packed shape {self.operands[0].shape} -> logical shape {a_layout.shape}")
1523
+ self.logger.info(f"B: packed shape {self.operands[1].shape} -> logical shape {b_layout.shape}")
1524
+ else:
1525
+ self.logger.info(f"A: shape {self.operands[0].shape}, strides {self.operands[0].strides}")
1526
+ self.logger.info(f"B: shape {self.operands[1].shape}, strides {self.operands[1].strides}")
1527
+ a_layout = MatrixLayout(self.operands[0].shape, self.operands[0].strides, self.qualifiers[0]["is_conjugate"])
1528
+ b_layout = MatrixLayout(self.operands[1].shape, self.operands[1].strides, self.qualifiers[1]["is_conjugate"])
1529
+
1530
+ # C is never FP4 (only A and B can be float4_e2m1fn_x2),
1531
+ # so no packed-to-logical conversion needed.
1532
+ c_layout = MatrixLayout(self.operands[2].shape, self.operands[2].strides) if self.num_operands == 3 else None # type: ignore[union-attr]
1533
+
1534
+ # Enforce equal batch shape for A and B if block_scaling=True.
1535
+ if self.options.block_scaling and a_layout.shape[:-2] != b_layout.shape[:-2]:
1536
+ raise ValueError(
1537
+ "When block_scaling=True, the batch dimensions of A and B must match (broadcasting is not supported)."
1538
+ )
1539
+
1540
+ # Get the operation traits.
1541
+ self.mm_traits = get_mm_traits(a_layout, b_layout, c_layout, self.inplace, self.logger)
1542
+ self.result_traits = None # Wait till planning to determine this based on the epilog.
1543
+ self.logger.info(
1544
+ f"The matrix multiplication attributes are M = {self.mm_traits.M}, N = {self.mm_traits.N}, and "
1545
+ f"K = {self.mm_traits.K}."
1546
+ )
1547
+ self.logger.info(
1548
+ f"The batch count is {self.mm_traits.batch_count}, and the batch shape is {self.mm_traits.batch_shape} "
1549
+ f"with batch axis order {self.mm_traits.batch_axis_order}."
1550
+ )
1551
+
1552
+ # Create and set the operation descriptor.
1553
+ self.mm_desc = cublaslt.matmul_desc_create(self.compute_type, self.scale_type)
1554
+
1555
+ self.mm_desc_ifc = matmul_desc_ifc.MatmulDescInterface(self.mm_desc)
1556
+ self.mm_desc_ifc.compute_type = self.compute_type
1557
+ self.mm_desc_ifc.scale_type = self.scale_type
1558
+
1559
+ # Guard SM count target and fast accumulation flag.
1560
+ version = cublaslt.get_version()
1561
+ if options.sm_count_target > 0: # type: ignore[operator]
1562
+ if version < 111103:
1563
+ raise ValueError(f"The 'sm_count_target' option is not supported in cuBLASLt version {version}.")
1564
+ self.mm_desc_ifc.sm_count_target = options.sm_count_target
1565
+ self.logger.info(f"The SM count target is {options.sm_count_target}.")
1566
+
1567
+ if options.fast_accumulation:
1568
+ if version < 111103:
1569
+ raise ValueError(f"The 'fast_accumulation' option is not supported in cuBLASLt version {version}.")
1570
+ self.mm_desc_ifc.fast_accum = options.fast_accumulation
1571
+ self.logger.info(f"The flag for fast accumulation mode is {options.fast_accumulation}.")
1572
+
1573
+ if self.input_type_width == 8 and version < 120800:
1574
+ raise ValueError(
1575
+ f"FP8 is not supported for cuBLASLt version {version}. cuBLASLt version 12.8 or higher is required."
1576
+ )
1577
+
1578
+ # Planning preferences
1579
+ self.preferences = None
1580
+
1581
+ # Epilog attributes.
1582
+ self.epilog = None
1583
+
1584
+ # Epilog attributes: name-to-operand.
1585
+ self.epilog_operands: dict[str, typing.Any] = {}
1586
+
1587
+ # Epilog attributes: epilog input name-to-handler.
1588
+ self.epilog_input_name_to_handler: dict[str, typing.Any] = {}
1589
+
1590
+ # Epilog attributes: name-to-output tensor.
1591
+ self.epilog_outputs: dict[str, typing.Any] = {}
1592
+
1593
+ # Keep track of epilog input traits for resetting operands.
1594
+ self.epilog_inputs_traits: dict[str, typing.Any] = {}
1595
+
1596
+ # Keep track of epilog output handlers to allocate output in execute().
1597
+ self.epilog_output_handlers: list[EpilogOutputHandler] = []
1598
+
1599
+ # Non-epilog aux outputs. Currently, only used for quantization outputs (amax etc.)
1600
+ self.aux_outputs = None
1601
+
1602
+ # Plan attributes.
1603
+ self.preference_ptr = None
1604
+ self.a_layout_ptr, self.b_layout_ptr, self.c_layout_ptr, self.d_layout_ptr = None, None, None, None
1605
+ self.flop_count = 0
1606
+ self.mm_planned = False
1607
+
1608
+ # Algorithm attributes.
1609
+ self.algorithms_buffer = None
1610
+ self.algorithm_objects = None
1611
+ self.cached_best_algorithm_struct = None
1612
+
1613
+ # Workspace lifecycle is managed by `Workspace` (allocate-on-demand,
1614
+ # reuse, mid-call release, exception cleanup, stream-ordered free).
1615
+ self.workspace = Workspace(
1616
+ self.allocator,
1617
+ self.logger,
1618
+ label="device workspace",
1619
+ device_id=self.device_id,
1620
+ )
1621
+
1622
+ # Last event recorded by cuda_call_ctx; consumed on workspace release
1623
+ # so the free is ordered after the compute that touched the buffer.
1624
+ self.last_compute_event = None
1625
+
1626
+ # Track whether the user has called release_operands().
1627
+ self._operands_released = False
1628
+
1629
+ # Device-side array with the quantization_scales
1630
+ self.quantization_scales_device: dict[str, utils.TensorHolder] = {}
1631
+
1632
+ self.valid_state = True
1633
+ self.logger.info("The Matmul operation has been created.")
1634
+
1635
+ def __enter__(self):
1636
+ return self
1637
+
1638
+ def __exit__(self, exc_type, exc_value, traceback):
1639
+ self.free()
1640
+
1641
+ def _check_valid_matmul(self, *args, **kwargs):
1642
+ """
1643
+ Check if the Matmul object is alive and well.
1644
+ """
1645
+ if not self.valid_state:
1646
+ raise InvalidMatmulState("The Matmul object cannot be used after resources are free'd")
1647
+
1648
+ def _check_valid_operands(self, *args, **kwargs):
1649
+ """
1650
+ Check if the operands are available for the operation.
1651
+ """
1652
+ what = kwargs["what"]
1653
+ if self._operands_released:
1654
+ raise RuntimeError(
1655
+ f"{what} cannot be performed after the operands have been released. "
1656
+ f"Use reset_operands() to provide new operands before performing the {what.lower()}."
1657
+ )
1658
+
1659
+ def _free_plan_resources(self, exception: Exception | None = None) -> bool:
1660
+ """
1661
+ Free resources allocated in planning.
1662
+ """
1663
+
1664
+ # Destroy matrix layouts.
1665
+ if self.a_layout_ptr is not None:
1666
+ cublaslt.matrix_layout_destroy(self.a_layout_ptr)
1667
+ self.a_layout_ptr = None
1668
+ if self.b_layout_ptr is not None:
1669
+ cublaslt.matrix_layout_destroy(self.b_layout_ptr)
1670
+ self.b_layout_ptr = None
1671
+ if self.c_layout_ptr != self.d_layout_ptr and self.c_layout_ptr is not None:
1672
+ cublaslt.matrix_layout_destroy(self.c_layout_ptr)
1673
+ self.c_layout_ptr = None
1674
+ if self.d_layout_ptr is not None:
1675
+ cublaslt.matrix_layout_destroy(self.d_layout_ptr)
1676
+ self.d_layout_ptr = None
1677
+
1678
+ if self.preference_ptr is not None:
1679
+ cublaslt.matmul_preference_destroy(self.preference_ptr)
1680
+ self.preference_ptr = None
1681
+
1682
+ self.mm_planned = False
1683
+ return True
1684
+
1685
+ def _check_planned(self, *args, **kwargs):
1686
+ what = kwargs["what"]
1687
+ if not self.mm_planned:
1688
+ raise RuntimeError(f"{what} cannot be performed before plan() has been called.")
1689
+
1690
+ @utils.precondition(_check_valid_matmul)
1691
+ def applicable_algorithm_ids(self, limit=8):
1692
+ """Obtain the algorithm IDs that are applicable to this matrix multiplication.
1693
+
1694
+ Args:
1695
+ limit: The maximum number of applicable algorithm IDs that is desired
1696
+
1697
+ Returns:
1698
+ A sequence of algorithm IDs that are applicable to this matrix multiplication
1699
+ problem specification, in random order.
1700
+ """
1701
+ ...
1702
+ algo_ids = cublaslt.matmul_algo_get_ids(
1703
+ self.handle,
1704
+ self.compute_type,
1705
+ self.scale_type,
1706
+ self.a_dtype,
1707
+ self.b_dtype,
1708
+ self.c_dtype,
1709
+ self.d_dtype,
1710
+ limit,
1711
+ )
1712
+ return algo_ids
1713
+
1714
+ def _validate_scalar_scale(self, operand: str):
1715
+ """
1716
+ Validates a scalar scale.
1717
+ """
1718
+ if self.options.block_scaling:
1719
+ raise ValueError(f"A scalar tensor-wide scale factor is not allowed for {operand.upper()} when block_scaling=True.")
1720
+
1721
+ def _validate_tensor_scale(self, scale, operand: str, operand_size=None):
1722
+ """
1723
+ Validates a tensor scale.
1724
+
1725
+ Args:
1726
+ scale: The tensor scale to validate
1727
+ operand: The operand name (a, b, c, d)
1728
+ operand_size: Size of the operand (needed for block scaling shape validation)
1729
+ """
1730
+ scale_package = utils.infer_object_package(scale)
1731
+ if scale_package != self.package:
1732
+ raise TypeError(
1733
+ f"The quantization scaling tensor for {operand.upper()} must belong to the same package as the operands."
1734
+ )
1735
+
1736
+ # Wrap temporarily since this is needed for validation
1737
+ scale_wrapped = tensor_wrapper.wrap_operand(scale)
1738
+
1739
+ # Device/memory space validation
1740
+ expected_device_id = "cpu" if self.memory_space == "cpu" else self.device_id
1741
+ if expected_device_id != scale_wrapped.device_id:
1742
+ raise ValueError(
1743
+ f'The scale for {operand.upper()} is on device "{scale_wrapped.device_id}", '
1744
+ f'but it should be on device "{expected_device_id}" to match the operands memory space.'
1745
+ )
1746
+
1747
+ # Shape and dtype validation for non-block-scaling
1748
+ if not self.options.block_scaling:
1749
+ if scale_wrapped.shape not in ((1,), ()):
1750
+ raise ValueError(
1751
+ f"The scale for {operand.upper()} must be of shape (1,) or (). Got {scale_wrapped.shape} instead."
1752
+ )
1753
+ if scale_wrapped.dtype != "float32":
1754
+ raise ValueError(f"The scale for {operand.upper()} must be float32 type. Got {scale_wrapped.dtype} instead.")
1755
+
1756
+ # Shape and dtype validation for block-scaling
1757
+ elif self.input_type_width == 8:
1758
+ # FP8: 32-element blocks with 128x128 tiled layout (VEC32_UE8M0)
1759
+ # Dtype validation (always possible)
1760
+ if scale_wrapped.dtype != "uint8":
1761
+ raise ValueError(f"Block scales for {operand.upper()} must be uint8 tensor.")
1762
+
1763
+ # Shape validation (only if operand_size is available)
1764
+ if operand_size is not None:
1765
+ expected_shape = (operand_size // 32,)
1766
+ if scale_wrapped.shape != expected_shape:
1767
+ raise ValueError(
1768
+ f"Scales for {operand.upper()} should have shape {expected_shape}. Got {scale_wrapped.shape}."
1769
+ )
1770
+ elif self.using_fp4_ab:
1771
+ # FP4: 16-element blocks with 128x64 tiled layout (VEC16_UE4M3)
1772
+ # Dtype validation (always possible)
1773
+ if scale_wrapped.dtype != "float8_e4m3fn":
1774
+ raise ValueError(
1775
+ f"Block scales for {operand.upper()} must be float8_e4m3fn tensor (UE4M3 format). "
1776
+ f"Got {scale_wrapped.dtype}."
1777
+ )
1778
+
1779
+ # Shape validation (only if operand_size is available)
1780
+ if operand_size is not None:
1781
+ expected_shape = (operand_size // 16,)
1782
+ if scale_wrapped.shape != expected_shape:
1783
+ raise ValueError(
1784
+ f"Scales for {operand.upper()} should have shape {expected_shape}. Got {scale_wrapped.shape}."
1785
+ )
1786
+ else:
1787
+ raise ValueError("block_scaling == True is not supported for non-FP8/FP4 types.")
1788
+
1789
+ def _validate_operand_scales(self, quantization_scales, all_required):
1790
+ """
1791
+ Validates quantization scales, wrapping them into a MatmulQuantizationScales
1792
+ object if needed.
1793
+
1794
+ Args:
1795
+ quantization_scales: The quantization scales to validate.
1796
+ all_required: Whether all scales are required.
1797
+
1798
+ Returns:
1799
+ A MatmulQuantizationScales object with the validated quantization scales.
1800
+ """
1801
+ if quantization_scales is None:
1802
+ raise ValueError(
1803
+ "Scales are required for narrow-precision (FP8 and lower) operations. "
1804
+ "Please set `quantization_scales` argument."
1805
+ )
1806
+
1807
+ # wrap the quantization scales into a MatmulQuantizationScales object if needed
1808
+ # otherwise, return the quantization scales as is
1809
+ quantization_scales = utils.check_or_create_options(
1810
+ _configuration.MatmulQuantizationScales, quantization_scales, "Scale factors"
1811
+ )
1812
+
1813
+ # Validate which scales are required/allowed
1814
+ expected_scales = "AB"
1815
+ if self.d_dtype_width <= 8 and not self.options.block_scaling:
1816
+ expected_scales += "D"
1817
+ elif quantization_scales.d is not None:
1818
+ if self.options.block_scaling:
1819
+ raise ValueError("Quantization scaling is not supported for D when `block_scaling` option is enabled.")
1820
+ if self.d_dtype_width > 8:
1821
+ raise ValueError(
1822
+ "Quantization scaling is not supported for D when it is not a narrow-precision (FP8 and lower) type."
1823
+ )
1824
+
1825
+ if self.num_operands == 3 and self.c_dtype_width <= 8:
1826
+ expected_scales += "C"
1827
+ elif quantization_scales.c is not None:
1828
+ raise ValueError(
1829
+ "Quantization scaling is not supported for C when it is not a narrow-precision (FP8 and lower) type."
1830
+ )
1831
+
1832
+ if all_required:
1833
+ for operand in expected_scales:
1834
+ if getattr(quantization_scales, operand.lower()) is None:
1835
+ raise ValueError(f"Scale for {operand.upper()} is not specified")
1836
+
1837
+ # Validate each scale by delegating to scalar/tensor specific validators
1838
+ for operand in "abcd":
1839
+ scale = getattr(quantization_scales, operand)
1840
+ if scale is None:
1841
+ continue
1842
+
1843
+ if isinstance(scale, (int, float)):
1844
+ self._validate_scalar_scale(operand)
1845
+ else:
1846
+ # For block scaling, pass operand size for shape validation
1847
+ if self.options.block_scaling and operand in ("a", "b"):
1848
+ operand_idx = 0 if operand == "a" else 1
1849
+ operand_size = self.operands[operand_idx].size # type: ignore[union-attr,index]
1850
+
1851
+ # For FP4, data is always packed: double the size to get logical size
1852
+ if self.using_fp4_ab:
1853
+ operand_size *= 2 # Packed tensor has half the elements
1854
+ self.logger.debug(f"FP4 scale validation for {operand}: adjusted operand_size={operand_size}")
1855
+ else:
1856
+ operand_size = None
1857
+ self._validate_tensor_scale(scale, operand, operand_size)
1858
+
1859
+ return quantization_scales
1860
+
1861
+ def _validate_epilog_aux_scale(self, aux_quantization_scale, *, required):
1862
+ is_narrow_aux = (
1863
+ self.preferences.epilog.aux_type is not None
1864
+ and typemaps.NAME_TO_DATA_WIDTH[typemaps.DATA_TYPE_TO_NAME[self.preferences.epilog.aux_type]] <= 8
1865
+ )
1866
+ if aux_quantization_scale is not None and not is_narrow_aux:
1867
+ raise ValueError(
1868
+ "Scales for epilog auxiliary output are not supported when `preferences.epilog.aux_type` is not set to a "
1869
+ "narrow-precision type."
1870
+ )
1871
+ elif aux_quantization_scale is None and is_narrow_aux and required:
1872
+ raise ValueError(
1873
+ '"aux_quantization_scale" epilog input is required when `preferences.epilog.aux_type` is set to a '
1874
+ "narrow-precision type."
1875
+ )
1876
+
1877
+ # Validate scalar vs tensor scale (same as for operand scales)
1878
+ if aux_quantization_scale is not None:
1879
+ if isinstance(aux_quantization_scale, (int, float)):
1880
+ self._validate_scalar_scale("epilog_aux")
1881
+ else:
1882
+ # No operand_size for epilog_aux scales
1883
+ self._validate_tensor_scale(aux_quantization_scale, "epilog_aux", operand_size=None)
1884
+
1885
+ def _prepare_validated_scalar_scale(self, scale: int | float, operand: str, stream_holder: utils.StreamHolder):
1886
+ """
1887
+ Converts validated scalar to float32 tensor and copies to GPU.
1888
+ Assumes validation already done in _validate_scalar_scale.
1889
+ """
1890
+ # If it's a scalar, copy to GPU. Float32 is the only type allowed by
1891
+ # cublasLtMatmulScale_t for tensor-wide scaling.
1892
+ self.logger.debug(f"Scale for {operand.upper()} will be copied to device {self.device_id}.")
1893
+ scale_op = tensor_wrapper.wrap_operand(np.asarray([scale], dtype="float32"))
1894
+ self.quantization_scales_device[operand] = scale_op.to(self.device_id, stream_holder)
1895
+
1896
+ def _prepare_validated_tensor_scale(self, scale, operand: str, stream_holder: utils.StreamHolder):
1897
+ """
1898
+ Wraps validated tensor and copies to GPU.
1899
+ Assumes all validation already done in _validate_tensor_scale (called in __init__).
1900
+ This is pure preparation - no validation here.
1901
+
1902
+ Note: We wrap the tensor a second time here (first wrap was for validation).
1903
+ This is acceptable because wrapping is cheap and we get early error detection.
1904
+ """
1905
+ # Wrap the scale (second time - first was for validation in __init__)
1906
+ self.quantization_scales_device[operand] = tensor_wrapper.wrap_operand(scale)
1907
+
1908
+ # Copy to GPU if on CPU (no validation, just preparation)
1909
+ if self.quantization_scales_device[operand].device in (None, "cpu"):
1910
+ self.logger.debug(f"Scale for {operand.upper()} will be copied to device {self.device_id}.")
1911
+ self.quantization_scales_device[operand] = self.quantization_scales_device[operand].to(
1912
+ self.device_id, stream_holder
1913
+ )
1914
+
1915
+ def _prepare_single_validated_scale(self, scale, operand: str, cublas_operand: str, stream_holder: utils.StreamHolder):
1916
+ """
1917
+ Prepares a single validated scale and sets its pointer/mode in mm_desc_ifc.
1918
+ Used for both operand scales (a,b,c,d) and epilog scales (epilog_aux).
1919
+ Assumes validation already done.
1920
+ """
1921
+ if scale is None:
1922
+ return
1923
+
1924
+ # Delegate to specific preparer (validation already done)
1925
+ if isinstance(scale, (int, float)):
1926
+ self._prepare_validated_scalar_scale(scale, operand, stream_holder)
1927
+ else:
1928
+ self._prepare_validated_tensor_scale(scale, operand, stream_holder)
1929
+
1930
+ # Set pointer and mode in descriptor
1931
+ setattr(self.mm_desc_ifc, f"{cublas_operand}_scale_pointer", self.quantization_scales_device[operand].data_ptr)
1932
+
1933
+ if self.options.block_scaling:
1934
+ # MXFP8 uses 32-element blocks with UE8M0, FP4 uses 16-element blocks with UE4M3
1935
+ if self.using_fp4_ab:
1936
+ # FP4: 16-element block scaling with UE4M3 format
1937
+ self.logger.debug(f"Using VEC16_UE4M3 scale mode for operand {operand.upper()}.")
1938
+ setattr(self.mm_desc_ifc, f"{cublas_operand}_scale_mode", cublaslt.MatmulMatrixScale.VEC16_UE4M3)
1939
+ else:
1940
+ # FP8: 32-element block scaling with UE8M0 format
1941
+ self.logger.debug(f"Using VEC32_UE8M0 scale mode for operand {operand.upper()}.")
1942
+ setattr(self.mm_desc_ifc, f"{cublas_operand}_scale_mode", cublaslt.MatmulMatrixScale.VEC32_UE8M0)
1943
+ else:
1944
+ self.logger.debug(f"Using SCALAR_32F scale mode for operand {operand.upper()}.")
1945
+ setattr(self.mm_desc_ifc, f"{cublas_operand}_scale_mode", cublaslt.MatmulMatrixScale.SCALAR_32F)
1946
+
1947
+ def _prepare_operand_quantization_scales(self, scales, stream_holder: utils.StreamHolder):
1948
+ """
1949
+ Prepares validated operand scales (a,b,c,d).
1950
+ Assumes scales are validated and wrapped into a MatmulQuantizationScales object.
1951
+ """
1952
+ for operand in "abcd":
1953
+ scale = getattr(scales, operand)
1954
+ self._prepare_single_validated_scale(scale, operand, cublas_operand=operand, stream_holder=stream_holder)
1955
+
1956
+ @utils.precondition(_check_valid_matmul)
1957
+ @utils.atomic(_free_plan_resources, method=True)
1958
+ def plan(
1959
+ self, *, preferences=None, algorithms=None, epilog=None, epilog_inputs=None, stream: utils.AnyStream | int | None = None
1960
+ ): # Epilog inputs require as many inputs (with specific shapes etc) as required by the epilogue. It's a dict.
1961
+ """
1962
+ Plan the matrix multiplication operation, considering the epilog (if provided).
1963
+
1964
+ Args:
1965
+ preferences: {preferences}
1966
+
1967
+ algorithms: {algorithms}
1968
+
1969
+ epilog: {epilog}
1970
+
1971
+ epilog_inputs: {epilog_inputs}
1972
+
1973
+ stream: {stream}
1974
+
1975
+ Returns:
1976
+ A sequence of :class:`nvmath.linalg.advanced.Algorithm` objects that are
1977
+ applicable to this matrix multiplication problem specification, heuristically
1978
+ ordered from fastest to slowest.
1979
+
1980
+ Notes:
1981
+ Epilogs that have ``BIAS`` in their name need an epilog input with the key
1982
+ ``'bias'``. Epilogs that have ``DRELU`` need an epilog input with the key
1983
+ ``'relu_aux'``, which is produced in a "forward pass" epilog like ``RELU_AUX``
1984
+ or ``RELU_AUX_BIAS``. Similarly, epilogs with ``DGELU`` in their name require an
1985
+ epilog input with the key ``'gelu_aux'``, produced in the corresponding forward
1986
+ pass operation.
1987
+
1988
+ Examples:
1989
+
1990
+ >>> import numpy as np
1991
+ >>> import nvmath
1992
+
1993
+ Create two 3-D float64 ndarrays on the CPU representing batched matrices, along
1994
+ with a bias vector:
1995
+
1996
+ >>> batch = 32
1997
+ >>> M, N, K = 1024, 1024, 1024
1998
+ >>> a = np.random.rand(batch, M, K)
1999
+ >>> b = np.random.rand(batch, K, N)
2000
+ >>> # The bias vector will be broadcast along the columns, as well as along the
2001
+ >>> # batch dimension.
2002
+ >>> bias = np.random.rand(M)
2003
+
2004
+ We will define a matrix multiplication operation followed by a
2005
+ :attr:`nvmath.linalg.advanced.MatmulEpilog.RELU_BIAS` epilog function.
2006
+
2007
+ >>> with nvmath.linalg.advanced.Matmul(a, b) as mm:
2008
+ ... # Plan the operation with RELU_BIAS epilog and corresponding epilog
2009
+ ... # input.
2010
+ ... p = nvmath.linalg.advanced.MatmulPlanPreferences(limit=8)
2011
+ ... epilog = nvmath.linalg.advanced.MatmulEpilog.RELU_BIAS
2012
+ ... epilog_inputs = {{"bias": bias}}
2013
+ ... # The preferences can also be provided as a dict: {{'limit': 8}}
2014
+ ... algorithms = mm.plan(
2015
+ ... preferences=p,
2016
+ ... epilog=epilog,
2017
+ ... epilog_inputs=epilog_inputs,
2018
+ ... )
2019
+ ...
2020
+ ... # Execute the matrix multiplication, and obtain the result `r` as a
2021
+ ... # NumPy ndarray.
2022
+ ... r = mm.execute()
2023
+
2024
+ Some epilogs like :attr:`nvmath.linalg.advanced.MatmulEpilog.RELU_AUX` produce
2025
+ auxiliary output.
2026
+
2027
+ >>> with nvmath.linalg.advanced.Matmul(a, b) as mm:
2028
+ ... # Plan the operation with RELU_AUX epilog>
2029
+ ... epilog = nvmath.linalg.advanced.MatmulEpilog.RELU_AUX
2030
+ ... algorithms = mm.plan(epilog=epilog)
2031
+ ...
2032
+ ... # Execute the matrix multiplication, and obtain the result `r` along
2033
+ ... # with the auxiliary output.
2034
+ ... r, auxiliary = mm.execute()
2035
+
2036
+ The auxiliary output is a Python `dict` with the names of each auxiliary output
2037
+ as keys.
2038
+
2039
+ Further examples can be found in the `nvmath/examples/linalg/advanced/matmul
2040
+ <https://github.com/NVIDIA/nvmath-python/tree/main/examples/linalg/advanced/matmul>`_
2041
+ directory.
2042
+ """
2043
+ log_info = self.logger.isEnabledFor(logging.INFO)
2044
+
2045
+ self.logger.info("= PLANNING PHASE =")
2046
+
2047
+ # Release layout objects and other plan resources from a previous plan() call
2048
+ # to prevent leaks on re-plan. This is a no-op on the first call.
2049
+ self._free_plan_resources()
2050
+
2051
+ # Clear epilog operands, since different epilogs can be provided in different calls.
2052
+ # We don't need to worry about ordering, since it's the user's responsibility to
2053
+ # order calls that accept a stream argument. This applies to CPU operands as well,
2054
+ # even though we move them to the GPU, since the execution is blocking.
2055
+ self.epilog_operands = {} # Clear operands in case of repeated planning.
2056
+ self.epilog_input_name_to_handler = {} # Clear input name to handler map as well,
2057
+ self.epilog_inputs_traits = {} # ... and the input traits as well.
2058
+
2059
+ preferences = utils.check_or_create_options(
2060
+ _configuration.MatmulPlanPreferences, preferences, "Matrix multiplication plan preferences"
2061
+ )
2062
+ self.preferences = preferences
2063
+
2064
+ mm_traits = self.mm_traits
2065
+
2066
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
2067
+ self.logger.info(f"The specified stream for the matrix multiplication plan is {stream_holder.obj}.")
2068
+
2069
+ # Base FLOP count.
2070
+ self.flop_count = 2 * mm_traits.M * mm_traits.N * mm_traits.K
2071
+ self.logger.info(f"The base matrix multiplication FLOP count is {formatters.FLOPSStr(self.flop_count, 'FLOP')}.")
2072
+
2073
+ if epilog is None and epilog_inputs is not None:
2074
+ self.logger.warning(
2075
+ f"Matmul: The provided epilog inputs {epilog_inputs.keys()} are ignored since an epilog is not specified."
2076
+ )
2077
+
2078
+ self.epilog = epilog
2079
+ epilog_ordering = None
2080
+ if epilog is not None:
2081
+ assert epilog in EPILOG_INPUT_HANDLERS_MAP, "Not supported."
2082
+ self.logger.info(f"The specified epilog is {epilog.name}.")
2083
+
2084
+ epilog_minimum_versions = EPILOG_MINIMUM_VERSIONS_MAP[epilog]
2085
+ batched_epilog_minimum_versions = BATCHED_EPILOG_MINIMUM_VERSIONS_MAP[epilog]
2086
+ version = cublaslt.get_version()
2087
+ if version < epilog_minimum_versions["cublaslt"]:
2088
+ message = (
2089
+ f"The epilog {epilog.name} requires cublaslt >= {epilog_minimum_versions['cublaslt']}; "
2090
+ f"you have version {version}. Update to CUDA Toolkit >= {epilog_minimum_versions['ctk']}."
2091
+ )
2092
+ raise ValueError(message)
2093
+
2094
+ if len(mm_traits.batch_shape) > 0 and version < batched_epilog_minimum_versions["cublaslt"]:
2095
+ message = (
2096
+ f"The epilog {epilog.name} supports batching in "
2097
+ f"cublaslt >= {batched_epilog_minimum_versions['cublaslt']}; "
2098
+ f"you have version {version}. Update to CUDA Toolkit >= {epilog_minimum_versions['ctk']}."
2099
+ )
2100
+ raise ValueError(message)
2101
+ if (
2102
+ self.mm_traits.c_layout_traits is not None
2103
+ and self.mm_traits.c_layout_traits.order == cublaslt.Order.ROW
2104
+ and epilog
2105
+ in [
2106
+ cublaslt.Epilogue.BGRADA,
2107
+ cublaslt.Epilogue.BGRADB,
2108
+ ]
2109
+ ):
2110
+ msg = f"The epilog {epilog.name} requires input matrix 'c' to be F-contiguous (column-major)."
2111
+ raise ValueError(msg)
2112
+ if (
2113
+ version < 120804
2114
+ # A has one row
2115
+ and self.mm_traits.M == 1
2116
+ # C is broadcast
2117
+ and self.mm_traits.c_layout_traits is not None
2118
+ and self.mm_traits.c_layout_traits.ld == 0
2119
+ # Using both an bias epilog and C
2120
+ and self.epilog & _configuration.MatmulEpilog.BIAS > 0
2121
+ ):
2122
+ message = (
2123
+ "When matrix 'a' has one row, "
2124
+ "simultaneously broadcasting matrix 'c' and using a BIAS epilog requires cublaslt >= 120804; "
2125
+ f"You have version {version}. Update to CUDA Toolkit >= 12.8.1."
2126
+ )
2127
+ raise ValueError(message)
2128
+
2129
+ # Take a copy of the user-provided inputs.
2130
+ if epilog_inputs is not None:
2131
+ epilog_inputs = epilog_inputs.copy()
2132
+ else:
2133
+ epilog_inputs = {}
2134
+
2135
+ # Get the dtype of auxiliary buffer
2136
+ aux_dtype_name = (
2137
+ typemaps.DATA_TYPE_TO_NAME[self.preferences.epilog.aux_type] # type: ignore[attr-defined]
2138
+ if self.preferences.epilog.aux_type is not None # type: ignore[attr-defined]
2139
+ else None
2140
+ )
2141
+
2142
+ # Extract aux quantization scale from the inputs.
2143
+ aux_quantization_scale = epilog_inputs.pop("aux_quantization_scale", None)
2144
+ self._validate_epilog_aux_scale(aux_quantization_scale, required=True)
2145
+ self._prepare_single_validated_scale(
2146
+ aux_quantization_scale, "epilog_aux", cublas_operand="epilogue_aux", stream_holder=stream_holder
2147
+ )
2148
+
2149
+ epilog_input_handler_types = EPILOG_INPUT_HANDLERS_MAP[epilog]
2150
+ if epilog_input_handler_types:
2151
+ epilog_input_handlers = [
2152
+ handler_type(self.logger, mm_traits, epilog, self.c_dtype_name, self.d_dtype_name, aux_dtype_name)
2153
+ for handler_type in epilog_input_handler_types
2154
+ ]
2155
+
2156
+ # Check if the epilog requires a specific result layout, and if the
2157
+ # requirement is consistent for all the handlers.
2158
+ epilog_input_handlers_ordering = {h.order for h in epilog_input_handlers}
2159
+ assert len(epilog_input_handlers_ordering) == 1, "Internal error."
2160
+ epilog_ordering = epilog_input_handlers_ordering.pop()
2161
+
2162
+ required_epilog_input_names = {h.name for h in epilog_input_handlers}
2163
+
2164
+ self.logger.info(f"The epilog requires the following additional inputs: {required_epilog_input_names}.")
2165
+ if required_epilog_input_names != set(epilog_inputs.keys()):
2166
+ raise ValueError(
2167
+ f"The epilog {epilog.name} requires the following input tensors: "
2168
+ f"{required_epilog_input_names}. The provided tensor names are: {epilog_inputs.keys()}"
2169
+ )
2170
+
2171
+ # Wrap epilog inputs.
2172
+ for name in epilog_inputs:
2173
+ epilog_inputs[name] = tensor_wrapper.wrap_operand(epilog_inputs[name])
2174
+
2175
+ # Check if epilog inputs all belong to the same package, which is the same
2176
+ # as the package of the MM operands.
2177
+ epilog_package = utils.get_operands_package(list(epilog_inputs.values()))
2178
+ if self.package != epilog_package:
2179
+ message = f"Library package mismatch for epilog: '{self.package}' => '{epilog_package}'"
2180
+ raise TypeError(message)
2181
+
2182
+ # When we get here, epilog_inputs should only contain tensors because
2183
+ # we popped aux_quantization_scale from the dictionary above.
2184
+ assert all(isinstance(v, tensor_wrapper.TensorHolder) for v in epilog_inputs.values()), "Internal error."
2185
+ # Since all epilog inputs are tensors, we can ensure they all are on
2186
+ # the same memory space as the operands provided at initialization,
2187
+ # as per the documentation for the epilog_inputs parameter.
2188
+ device_id = utils.get_operands_device_id(list(epilog_inputs.values()))
2189
+ expected_device = "cpu" if self.memory_space == "cpu" else self.device_id
2190
+ if device_id != expected_device:
2191
+ raise ValueError(
2192
+ f"The epilog inputs must be in the same memory space as the operands. "
2193
+ f"Expected device '{expected_device}' (operands' memory space is '{self.memory_space}'), "
2194
+ f"but epilog inputs are on device '{device_id}'."
2195
+ )
2196
+
2197
+ # Move epilog inputs to the GPU, if needed.
2198
+ if device_id == "cpu":
2199
+ for e in required_epilog_input_names:
2200
+ self.logger.debug(f"The epilog input {e} will be copied to device{self.device_id}.")
2201
+ self.epilog_operands[e] = epilog_inputs[e].to(self.device_id, stream_holder)
2202
+ else:
2203
+ for e in required_epilog_input_names:
2204
+ self.epilog_operands[e] = epilog_inputs[e]
2205
+
2206
+ # First validate all epilog inputs. Use the GPU tensors in case metadata has
2207
+ # changed.
2208
+ for handler in epilog_input_handlers:
2209
+ handler.validate(epilog_inputs[handler.name])
2210
+
2211
+ # Finally, update the MM descriptor. Note that we pass in
2212
+ # self.epilog_operands (which are on the GPU).
2213
+ for handler in epilog_input_handlers:
2214
+ handler.update(self.mm_desc_ifc, self.epilog_operands[handler.name])
2215
+ self.epilog_input_name_to_handler[handler.name] = handler
2216
+
2217
+ # Capture the epilog operands traits for consistency checks when resetting
2218
+ # operands.
2219
+ self.epilog_inputs_traits = {
2220
+ name: EpilogInputTraits(
2221
+ dtype=self.epilog_operands[name].dtype,
2222
+ extents=self.epilog_operands[name].shape,
2223
+ strides=self.epilog_operands[name].strides,
2224
+ )
2225
+ for name in self.epilog_operands
2226
+ }
2227
+
2228
+ epilog_output_handler_types = EPILOG_OUTPUT_HANDLERS_MAP[epilog]
2229
+ if epilog_output_handler_types:
2230
+ self.epilog_output_handlers = epilog_output_handlers = [
2231
+ handler_type(self.logger, mm_traits, epilog, self.c_dtype_name, self.d_dtype_name, aux_dtype_name)
2232
+ for handler_type in epilog_output_handler_types
2233
+ ]
2234
+ # Check if the epilog requires a specific result layout, and if the
2235
+ # requirement is consistent for all the handlers.
2236
+ epilog_output_handlers_ordering = {h.order for h in epilog_output_handlers}
2237
+ assert len(epilog_output_handlers_ordering) == 1, "Internal error."
2238
+ op_epilog_ordering = epilog_output_handlers_ordering.pop()
2239
+ if epilog_ordering is None:
2240
+ epilog_ordering = op_epilog_ordering
2241
+ else:
2242
+ assert epilog_ordering == op_epilog_ordering, "Internal error."
2243
+
2244
+ # Update the MM descriptor, except for the device pointer.
2245
+ for ohandler in epilog_output_handlers:
2246
+ ohandler.update(self.mm_desc_ifc)
2247
+
2248
+ # Set the epilog. At this point, we're sure that the epilog inputs, if any, are
2249
+ # valid and have been set.
2250
+ self.mm_desc_ifc.epilogue = epilog
2251
+
2252
+ # Fill the result traits, now that we know the epilog.
2253
+ self.result_traits = result_traits = get_result_traits(mm_traits, epilog_ordering, self.logger) # type: ignore[assignment]
2254
+ assert self.result_traits is not None, "Internal Error. self.result_traits should have been set by self.plan()."
2255
+ self.logger.info(
2256
+ f"The layout order for the result D is {self.result_traits.d_layout_traits.order.name}, with LD "
2257
+ f"{self.result_traits.d_layout_traits.ld}, and batch offset "
2258
+ f"{self.result_traits.d_layout_traits.batch_offset}."
2259
+ )
2260
+
2261
+ # Internally transpose operand A if required (conjugate flag) and create layout.
2262
+ transpose = False
2263
+ if mm_traits.a_layout_traits.is_conjugate and self.is_complex:
2264
+ self.mm_desc_ifc.transa = cublas.Operation.C
2265
+ transpose = True
2266
+ self.logger.debug(
2267
+ "To conjugate A, the operand A will be internally transposed and the matrix multiplication will be "
2268
+ "performed with OP_C for operand A."
2269
+ )
2270
+ if self.input_type_width <= 8:
2271
+ # narrow-precision (FP8 and lower) data types are only supported for transa=OP_T
2272
+ self.mm_desc_ifc.transa = cublas.Operation.T
2273
+ transpose = True
2274
+ self.logger.debug(
2275
+ "For narrow-precision (FP8 and lower) multiplication, the operand A will be internally transposed and the "
2276
+ "matrix multiplication will be performed with OP_T for operand A."
2277
+ )
2278
+ m, n, ld, a_order = mm_traits.a_layout_traits.get_mm_layout(transpose=transpose)
2279
+ self.a_layout_ptr = cublaslt.matrix_layout_create(self.a_dtype, rows=m, cols=n, ld=ld)
2280
+ self.logger.debug(f"Layout for A: rows = {m}, cols = {n}, ld = {ld}.")
2281
+
2282
+ # Internally transpose operand B if required (conjugate flag, or epilog is BGRADB)
2283
+ # and create layout.
2284
+ transpose = False
2285
+ if mm_traits.b_layout_traits.is_conjugate and self.is_complex:
2286
+ self.mm_desc_ifc.transb = cublas.Operation.C
2287
+ transpose = True
2288
+ self.logger.debug(
2289
+ "To conjugate B, the operand B will be internally transposed and the matrix multiplication will be "
2290
+ "performed with OP_C for operand B."
2291
+ )
2292
+ elif epilog == _configuration.MatmulEpilog.BGRADB:
2293
+ self.mm_desc_ifc.transb = cublas.Operation.T
2294
+ transpose = True
2295
+ self.logger.debug(
2296
+ "For BGRADB epilog, the operand B will be internally transposed and the matrix multiplication will be "
2297
+ "performed with OP_T for operand B."
2298
+ )
2299
+ m, n, ld, b_order = mm_traits.b_layout_traits.get_mm_layout(transpose=transpose)
2300
+ self.b_layout_ptr = cublaslt.matrix_layout_create(self.b_dtype, rows=m, cols=n, ld=ld)
2301
+ self.logger.debug(f"Layout for B: rows = {m}, cols = {n}, ld = {ld}.")
2302
+
2303
+ self.d_layout_ptr = cublaslt.matrix_layout_create(
2304
+ self.d_dtype, rows=mm_traits.M, cols=mm_traits.N, ld=result_traits.d_layout_traits.ld
2305
+ )
2306
+
2307
+ layout_a_ifc = matrix_layout_ifc.MatrixLayoutInterface(self.a_layout_ptr)
2308
+ layout_a_ifc.order = a_order
2309
+ layout_a_ifc.batch_count = mm_traits.batch_count
2310
+ layout_a_ifc.strided_batch_offset = mm_traits.a_layout_traits.batch_offset
2311
+
2312
+ layout_b_ifc = matrix_layout_ifc.MatrixLayoutInterface(self.b_layout_ptr)
2313
+ layout_b_ifc.order = b_order
2314
+ layout_b_ifc.batch_count = mm_traits.batch_count
2315
+ layout_b_ifc.strided_batch_offset = mm_traits.b_layout_traits.batch_offset
2316
+
2317
+ layout_d_ifc = matrix_layout_ifc.MatrixLayoutInterface(self.d_layout_ptr)
2318
+ layout_d_ifc.order = result_traits.d_layout_traits.order
2319
+ layout_d_ifc.batch_count = mm_traits.batch_count
2320
+ layout_d_ifc.strided_batch_offset = result_traits.d_layout_traits.batch_offset
2321
+
2322
+ if self.num_operands == 2: # By defn, this cannot be inplace.
2323
+ if self.c_dtype == self.d_dtype:
2324
+ # If C and D have equal types, reuse the layout.
2325
+ self.c_layout_ptr = self.d_layout_ptr
2326
+ else:
2327
+ # Otherwise, create a D-like layout, but with different type.
2328
+ self.c_layout_ptr = cublaslt.matrix_layout_create(
2329
+ self.c_dtype, rows=mm_traits.M, cols=mm_traits.N, ld=result_traits.d_layout_traits.ld
2330
+ )
2331
+ layout_c_ifc = matrix_layout_ifc.MatrixLayoutInterface(self.c_layout_ptr)
2332
+ layout_c_ifc.order = result_traits.d_layout_traits.order
2333
+ layout_c_ifc.batch_count = mm_traits.batch_count
2334
+ layout_c_ifc.strided_batch_offset = result_traits.d_layout_traits.batch_offset
2335
+ else:
2336
+ # For inplace operation, use the same layout for C and D.
2337
+ if self.inplace:
2338
+ self.c_layout_ptr = self.d_layout_ptr
2339
+ else:
2340
+ self.c_layout_ptr = cublaslt.matrix_layout_create(
2341
+ self.c_dtype, rows=mm_traits.M, cols=mm_traits.N, ld=mm_traits.c_layout_traits.ld
2342
+ )
2343
+ layout_c_ifc = matrix_layout_ifc.MatrixLayoutInterface(self.c_layout_ptr)
2344
+ layout_c_ifc.order = mm_traits.c_layout_traits.order
2345
+ layout_c_ifc.batch_count = mm_traits.batch_count
2346
+ layout_c_ifc.strided_batch_offset = mm_traits.c_layout_traits.batch_offset
2347
+
2348
+ # FP8 block scaling dimension requirements
2349
+ if (
2350
+ self.input_type_width == 8
2351
+ and self.options.block_scaling
2352
+ and (mm_traits.M % 128 != 0 or mm_traits.N % 128 != 0 or mm_traits.K % 128 != 0)
2353
+ ):
2354
+ raise ValueError(f"M={mm_traits.M} N={mm_traits.N} K={mm_traits.K} must be divisible by 128 for FP8 block_scaling.")
2355
+
2356
+ # Note: FP4 block scaling dimension requirements (M,N % 128, K % 64) are checked
2357
+ # earlier in __init__ via validate_fp4_ab_dimensions().
2358
+
2359
+ # General FP8 alignment
2360
+ if self.input_type_width == 8 and (mm_traits.M % 16 != 0 or mm_traits.N % 16 != 0 or mm_traits.K % 16 != 0):
2361
+ raise ValueError(f"M={mm_traits.M} N={mm_traits.N} K={mm_traits.K} must be divisible by 16 for FP8 operations")
2362
+
2363
+ # General FP4 alignment
2364
+ if self.using_fp4_ab and (mm_traits.M % 16 != 0 or mm_traits.N % 16 != 0 or mm_traits.K % 16 != 0):
2365
+ raise ValueError(f"M={mm_traits.M} N={mm_traits.N} K={mm_traits.K} must be divisible by 16 for FP4 operations")
2366
+
2367
+ if self.options.block_scaling and self.d_dtype_width <= 8: # FP8 and FP4
2368
+ self.mm_desc_ifc.alpha_vector_batch_stride = 1 # Workaround for library caching issue
2369
+
2370
+ # cublasLtMatmulAlgoGetHeuristic requires the scale pointer to be set.
2371
+ num_output_elements = mm_traits.M * mm_traits.N * mm_traits.batch_count
2372
+ d_out_scale, d_out_scale_mode = _create_d_out_scale_and_scale_mode(
2373
+ self.result_class, num_output_elements, self.d_dtype_width, self.device_id, stream_holder
2374
+ )
2375
+ self.aux_outputs = {"d_out_scale": d_out_scale}
2376
+ self.mm_desc_ifc.d_out_scale_pointer = d_out_scale.data_ptr
2377
+ self.mm_desc_ifc.d_out_scale_mode = d_out_scale_mode
2378
+
2379
+ limit = preferences.limit
2380
+ if algorithms is None:
2381
+ num_algorithms = np.empty((1,), dtype=np.int32)
2382
+ self.algorithms_buffer = cublaslt.MatmulHeuristicResult(limit)
2383
+ else:
2384
+ assert all(isinstance(algo, _algorithmmod.Algorithm) for algo in algorithms), (
2385
+ "The algorithms passed to plan() are of wrong type."
2386
+ )
2387
+ num_algorithms = len(algorithms)
2388
+
2389
+ self.preference_ptr = cublaslt.matmul_preference_create()
2390
+
2391
+ if self.input_type_width <= 8:
2392
+ self._prepare_operand_quantization_scales(self.quantization_scales, stream_holder)
2393
+
2394
+ if algorithms is None:
2395
+ # Set preferences.
2396
+ preference_ifc = matmul_pref_ifc.MatmulPreferenceInterface(self.preference_ptr)
2397
+ preference_ifc.max_workspace_bytes = self.memory_limit
2398
+ preference_ifc.reduction_scheme_mask = preferences.reduction_scheme_mask
2399
+ preference_ifc.max_waves_count = preferences.max_waves_count
2400
+ preference_ifc.impl_mask = preferences.numerical_impl_mask
2401
+
2402
+ # Set minimum alignments.
2403
+ a_ptr, b_ptr = self.operands[0].data_ptr, self.operands[1].data_ptr
2404
+ preference_ifc.min_alignment_a_bytes = min(256, pointer_aligned_to(a_ptr))
2405
+ preference_ifc.min_alignment_b_bytes = min(256, pointer_aligned_to(b_ptr))
2406
+ self.logger.debug(f"The minimum alignment for operand A is {preference_ifc.min_alignment_a_bytes} bytes.")
2407
+ self.logger.debug(f"The minimum alignment for operand B is {preference_ifc.min_alignment_b_bytes} bytes.")
2408
+ if self.num_operands == 3:
2409
+ c_ptr = self.operands[2].data_ptr
2410
+ preference_ifc.min_alignment_c_bytes = min(256, pointer_aligned_to(c_ptr))
2411
+ self.logger.debug(f"The minimum alignment for operand C is {preference_ifc.min_alignment_c_bytes} bytes.")
2412
+ # The result alignment should be 256 bytes.
2413
+ self.logger.debug("The minimum alignment for the result D is the default 256 bytes.")
2414
+
2415
+ self.logger.info("Starting matrix multiplication planning...")
2416
+ assert isinstance(self.device_id, int), self.device_id
2417
+ assert stream_holder is not None
2418
+ with utils.cuda_call_ctx(stream_holder, blocking=True, timing=log_info) as (
2419
+ _,
2420
+ elapsed,
2421
+ ):
2422
+ cublaslt.matmul_algo_get_heuristic(
2423
+ self.handle,
2424
+ self.mm_desc,
2425
+ self.a_layout_ptr,
2426
+ self.b_layout_ptr,
2427
+ self.c_layout_ptr,
2428
+ self.d_layout_ptr,
2429
+ self.preference_ptr,
2430
+ limit,
2431
+ self.algorithms_buffer.ptr,
2432
+ num_algorithms.ctypes.data,
2433
+ )
2434
+
2435
+ num_algorithms = num_algorithms[0]
2436
+ if num_algorithms == 0:
2437
+ raise RuntimeError("Planning failed to find any suitable algorithm.")
2438
+ assert self.algorithms_buffer is not None, (
2439
+ "Internal Error. self.algorithms_buffer should have been set by self.plan()."
2440
+ )
2441
+ self.algorithms_buffer = self.algorithms_buffer[:num_algorithms]
2442
+
2443
+ # Create algorithm objects.
2444
+ self.algorithm_objects = tuple(_algorithmmod.Algorithm(a) for a in self.algorithms_buffer)
2445
+ else:
2446
+ self.algorithm_objects = tuple(algorithms)
2447
+ self.algorithms_buffer = cublaslt.MatmulHeuristicResult(len(algorithms))
2448
+ for i, algo in enumerate(algorithms):
2449
+ # we wrap it too well that it's hard to copy-construct...
2450
+ self.algorithms_buffer[i] = algo.algorithm._data
2451
+
2452
+ # Cache the first (best) algorithm struct.
2453
+ self.cached_best_algorithm_struct = self.algorithms_buffer[0]["algo"]
2454
+
2455
+ # Create the map from object to buffer.
2456
+ self.algorithm_object_to_buffer = dict(zip(self.algorithm_objects, self.algorithms_buffer, strict=True))
2457
+
2458
+ workspace_size = int(np.max(self.algorithms_buffer["workspace_size"]))
2459
+ if workspace_size > 0 and self.epilog:
2460
+ workspace_size += 16 # Workaround for library issue
2461
+ self.workspace.set_size(workspace_size)
2462
+
2463
+ if algorithms is None:
2464
+ self.logger.info(
2465
+ f"The plan found {num_algorithms} suitable algorithms within the requested limit of {limit} "
2466
+ f"algorithms, with a workspace requirement of {formatters.MemoryStr(workspace_size)}."
2467
+ )
2468
+ else:
2469
+ self.logger.info(
2470
+ f"The plan is using {num_algorithms} algorithm passed through the algorithms argument, with a "
2471
+ f"workspace requirement of {formatters.MemoryStr(workspace_size)}."
2472
+ )
2473
+
2474
+ self.mm_planned = True
2475
+ if algorithms is None and elapsed.data is not None:
2476
+ self.logger.info(f"The matrix multiplication planning phase took {elapsed.data:.3f} ms to complete.")
2477
+
2478
+ return self.algorithm_objects
2479
+
2480
+ @property
2481
+ def algorithms(self):
2482
+ """
2483
+ After planning using :meth:`plan()`, get the sequence of algorithm objects to
2484
+ inquire their capabilities, configure them, or serialize them for later use.
2485
+
2486
+ Returns:
2487
+ A sequence of :class:`nvmath.linalg.advanced.Algorithm` objects that are
2488
+ applicable to this matrix multiplication problem specification.
2489
+ """
2490
+ return self.algorithm_objects
2491
+
2492
+ def _check_and_set_operand(
2493
+ self,
2494
+ operand,
2495
+ operand_name,
2496
+ mm_desc_ifc,
2497
+ stream_holder,
2498
+ *,
2499
+ operand_index=None,
2500
+ epilog_name=None,
2501
+ package=None,
2502
+ dtype=None,
2503
+ extents=None,
2504
+ strides=None,
2505
+ ):
2506
+ """
2507
+ Check to make sure that the provided operand is consistent with the one it's
2508
+ updating, and update it.
2509
+ """
2510
+ assert (operand_index is None) ^ (epilog_name is None), "Internal Error."
2511
+ assert self.operands is not None, "Internal Error."
2512
+
2513
+ # Make sure that the data type and extents match.
2514
+ utils.check_attribute_match(dtype, operand.dtype, "data type")
2515
+ utils.check_attribute_match(extents, operand.shape, "extents")
2516
+
2517
+ package = utils.infer_object_package(operand.tensor)
2518
+
2519
+ # Conjugate flag of the provided operands must match the original qualifiers
2520
+ if operand_index is not None and self.lazy_conjugation[operand_index] != operand.is_conjugate:
2521
+ raise ValueError(f"The provided operand {operand_name} has different conjugate flag than the original operand")
2522
+
2523
+ device_id = operand.device_id
2524
+ # When memory_space is "cpu", operands should be on CPU even though
2525
+ # self.device_id is the execution device.
2526
+ expected_device_id = "cpu" if self.memory_space == "cpu" else self.device_id
2527
+ if expected_device_id != device_id:
2528
+ raise ValueError(
2529
+ f'The operand {operand_name} is on device "{device_id}", but it should be on device '
2530
+ f'"{expected_device_id}" to match the original operand.'
2531
+ )
2532
+
2533
+ if device_id == "cpu":
2534
+ if self.package != package:
2535
+ message = f"Library package mismatch: '{self.package}' => '{package}'"
2536
+ raise TypeError(message)
2537
+
2538
+ # Check if we have a GPU buffer to update into.
2539
+ if operand_index is not None:
2540
+ o = self.operands[operand_index]
2541
+ else:
2542
+ o = self.epilog_operands[epilog_name]
2543
+ if o is None: # No buffer, create one.
2544
+ # Copy operand across memory spaces (CPU to GPU).
2545
+ o = operand.to(self.device_id, stream_holder)
2546
+ if operand_index is not None:
2547
+ self.operands[operand_index] = o
2548
+ else:
2549
+ self.epilog_operands[epilog_name] = o
2550
+ # Update the epilog pointer, since we're starting afresh.
2551
+ self.epilog_input_name_to_handler[epilog_name].update(mm_desc_ifc, o)
2552
+ else:
2553
+ # In-place copy to existing device pointer because the new operand is on the
2554
+ # CPU.
2555
+ o.copy_(operand, stream_holder=stream_holder)
2556
+ if self.memory_space == "cpu" and operand_index == 2:
2557
+ # Hold references, needed for inplace operations.
2558
+ self.cpu_c_ref = operand
2559
+ else:
2560
+ if self.package != package:
2561
+ message = f"Library package mismatch: '{self.package}' => '{package}'"
2562
+ raise TypeError(message)
2563
+
2564
+ utils.check_attribute_match(strides, operand.strides, "strides")
2565
+
2566
+ # Finally, replace the original operand by the new one.
2567
+ if operand_index is not None:
2568
+ self.operands[operand_index] = operand
2569
+ else:
2570
+ self.epilog_operands[epilog_name] = operand
2571
+ # Update the epilog pointer, since we're starting afresh.
2572
+ self.epilog_input_name_to_handler[epilog_name].update(mm_desc_ifc, operand)
2573
+
2574
+ self.logger.info(f"Operand '{operand_name}' has been reset to the new value.")
2575
+
2576
+ return
2577
+
2578
+ def _reset_quantization_scales_unchecked(self, quantization_scales_obj, stream, stream_holder):
2579
+ """
2580
+ Unchecked reset of quantization scales for operands A, B, C, and D.
2581
+
2582
+ Works for both CPU and CUDA memory spaces. For each provided scale the
2583
+ function updates the host-side value in ``self.quantization_scales``, updates
2584
+ the existing device-side holder in ``self.quantization_scales_device``
2585
+ (copy in-place or rebind ``.tensor``), and refreshes the descriptor pointer.
2586
+
2587
+ A stream holder is created lazily only when a CPU-to-GPU copy is needed
2588
+ (scalar scales, or tensor scales in CPU memory space).
2589
+
2590
+ Returns the stream_holder (may be newly created).
2591
+ """
2592
+ mm_desc_ifc = self.mm_desc_ifc
2593
+ qsd = self.quantization_scales_device
2594
+
2595
+ def _update(holder, scale):
2596
+ nonlocal stream_holder
2597
+ if isinstance(scale, (int, float)):
2598
+ if stream_holder is None:
2599
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
2600
+ src = tensor_wrapper.wrap_operand(np.asarray(scale, dtype="float32"))
2601
+ _realloc_if_needed_and_copy_to_mirror(src, holder, self.device_id, stream_holder)
2602
+ elif self.memory_space == "cpu":
2603
+ if stream_holder is None:
2604
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
2605
+ _realloc_if_needed_and_copy_to_mirror(tensor_wrapper.wrap_operand(scale), holder, self.device_id, stream_holder)
2606
+ else:
2607
+ holder.tensor = scale
2608
+
2609
+ if quantization_scales_obj.a is not None:
2610
+ self.quantization_scales.a = quantization_scales_obj.a
2611
+ holder = qsd["a"]
2612
+ _update(holder, quantization_scales_obj.a)
2613
+ mm_desc_ifc.set_a_scale_pointer_unchecked(holder.data_ptr)
2614
+
2615
+ if quantization_scales_obj.b is not None:
2616
+ self.quantization_scales.b = quantization_scales_obj.b
2617
+ holder = qsd["b"]
2618
+ _update(holder, quantization_scales_obj.b)
2619
+ mm_desc_ifc.set_b_scale_pointer_unchecked(holder.data_ptr)
2620
+
2621
+ if quantization_scales_obj.c is not None:
2622
+ self.quantization_scales.c = quantization_scales_obj.c
2623
+ holder = qsd["c"]
2624
+ _update(holder, quantization_scales_obj.c)
2625
+ mm_desc_ifc.set_c_scale_pointer_unchecked(holder.data_ptr)
2626
+
2627
+ if quantization_scales_obj.d is not None:
2628
+ self.quantization_scales.d = quantization_scales_obj.d
2629
+ holder = qsd["d"]
2630
+ _update(holder, quantization_scales_obj.d)
2631
+ mm_desc_ifc.set_d_scale_pointer_unchecked(holder.data_ptr)
2632
+
2633
+ return stream_holder
2634
+
2635
+ def _reset_aux_quantization_scale_unchecked(self, aux_quantization_scale, stream, stream_holder):
2636
+ """
2637
+ Unchecked reset of aux_quantization_scale.
2638
+
2639
+ Works for both CPU and CUDA memory spaces. Updates the existing
2640
+ device-side holder (copy in-place or rebind ``.tensor``) and refreshes
2641
+ the descriptor pointer.
2642
+ A stream holder is created lazily only when a CPU-to-GPU copy is needed.
2643
+
2644
+ Returns the stream_holder (may be newly created).
2645
+ """
2646
+ holder = self.quantization_scales_device["epilog_aux"]
2647
+
2648
+ if isinstance(aux_quantization_scale, (int, float)):
2649
+ if stream_holder is None:
2650
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
2651
+ src = tensor_wrapper.wrap_operand(np.asarray(aux_quantization_scale, dtype="float32"))
2652
+ _realloc_if_needed_and_copy_to_mirror(src, holder, self.device_id, stream_holder)
2653
+ elif self.memory_space == "cpu":
2654
+ if stream_holder is None:
2655
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
2656
+ _realloc_if_needed_and_copy_to_mirror(
2657
+ tensor_wrapper.wrap_operand(aux_quantization_scale), holder, self.device_id, stream_holder
2658
+ )
2659
+ else:
2660
+ holder.tensor = aux_quantization_scale
2661
+
2662
+ self.mm_desc_ifc.epilogue_aux_scale_pointer = holder.data_ptr
2663
+ return stream_holder
2664
+
2665
+ def reset_operands_unchecked(
2666
+ self,
2667
+ *,
2668
+ a=None,
2669
+ b=None,
2670
+ c=None,
2671
+ alpha=None,
2672
+ beta=None,
2673
+ quantization_scales=None,
2674
+ epilog_inputs=None,
2675
+ stream: utils.AnyStream | int | None = None,
2676
+ ):
2677
+ """
2678
+ {reset_operands_unchecked}
2679
+ """
2680
+ if alpha is not None:
2681
+ self.alpha[0] = alpha
2682
+
2683
+ if beta is not None:
2684
+ self.beta[0] = beta
2685
+
2686
+ stream_holder = None
2687
+
2688
+ if epilog_inputs is not None and "aux_quantization_scale" in epilog_inputs:
2689
+ aux_quantization_scale = epilog_inputs.get("aux_quantization_scale")
2690
+ stream_holder = self._reset_aux_quantization_scale_unchecked(aux_quantization_scale, stream, stream_holder)
2691
+
2692
+ quantization_scales_obj = quantization_scales
2693
+ if quantization_scales is not None and isinstance(quantization_scales, dict):
2694
+ quantization_scales_obj = _configuration.MatmulQuantizationScales(**quantization_scales)
2695
+
2696
+ if self.memory_space == "cuda":
2697
+ if a is not None:
2698
+ self.operands[0].tensor = a # type: ignore[index, union-attr]
2699
+ if b is not None:
2700
+ self.operands[1].tensor = b # type: ignore[index, union-attr]
2701
+ if c is not None:
2702
+ self.operands[2].tensor = c # type: ignore[index, union-attr]
2703
+
2704
+ if epilog_inputs is not None:
2705
+ for epilog_name, epilog_value in epilog_inputs.items():
2706
+ if epilog_name != "aux_quantization_scale":
2707
+ self.epilog_operands[epilog_name].tensor = epilog_value
2708
+ self.epilog_input_name_to_handler[epilog_name].update_pointer(
2709
+ self.mm_desc_ifc, self.epilog_operands[epilog_name].data_ptr
2710
+ )
2711
+
2712
+ else:
2713
+ if stream_holder is None:
2714
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
2715
+
2716
+ if a is not None:
2717
+ a_wrapped = tensor_wrapper.wrap_operand(a)
2718
+ _realloc_if_needed_and_copy_to_mirror(a_wrapped, self.operands[0], self.device_id, stream_holder) # type: ignore[index, union-attr]
2719
+ if b is not None:
2720
+ b_wrapped = tensor_wrapper.wrap_operand(b)
2721
+ _realloc_if_needed_and_copy_to_mirror(b_wrapped, self.operands[1], self.device_id, stream_holder) # type: ignore[index, union-attr]
2722
+ if c is not None:
2723
+ c_wrapped = tensor_wrapper.wrap_operand(c)
2724
+ _realloc_if_needed_and_copy_to_mirror(c_wrapped, self.operands[2], self.device_id, stream_holder) # type: ignore[index, union-attr]
2725
+ if self.inplace:
2726
+ self.cpu_c_ref = c_wrapped
2727
+
2728
+ if epilog_inputs is not None:
2729
+ for epilog_name, epilog_value in epilog_inputs.items():
2730
+ if epilog_name != "aux_quantization_scale":
2731
+ epilog_input_wrapped = tensor_wrapper.wrap_operand(epilog_value)
2732
+ reallocated = _realloc_if_needed_and_copy_to_mirror(
2733
+ epilog_input_wrapped, self.epilog_operands[epilog_name], self.device_id, stream_holder
2734
+ )
2735
+ if reallocated:
2736
+ self.epilog_input_name_to_handler[epilog_name].update_pointer(
2737
+ self.mm_desc_ifc, self.epilog_operands[epilog_name].data_ptr
2738
+ )
2739
+
2740
+ if quantization_scales_obj is not None:
2741
+ self._reset_quantization_scales_unchecked(quantization_scales_obj, stream, stream_holder)
2742
+
2743
+ self._operands_released = False
2744
+
2745
+ @utils.precondition(_check_valid_matmul)
2746
+ def reset_operands(
2747
+ self,
2748
+ *,
2749
+ a=None,
2750
+ b=None,
2751
+ c=None,
2752
+ alpha=None,
2753
+ beta=None,
2754
+ quantization_scales=None,
2755
+ epilog_inputs=None,
2756
+ stream: utils.AnyStream | int | None = None,
2757
+ ):
2758
+ """
2759
+ Reset one or more operands held by this :class:`Matmul` instance.
2760
+
2761
+ .. versionchanged:: 0.9
2762
+ All parameters are now keyword-only.
2763
+
2764
+ Args:
2765
+ a: {a}
2766
+
2767
+ b: {b}
2768
+
2769
+ c: {c}
2770
+ {c_admonitions}
2771
+
2772
+ alpha: {alpha}
2773
+
2774
+ beta: {beta}
2775
+
2776
+ epilog_inputs: {epilog_inputs}
2777
+
2778
+ stream: {stream}
2779
+
2780
+ quantization_scales: {quantization_scales}
2781
+
2782
+ Semantics:
2783
+ - Only the operands explicitly passed are updated. At least one operand
2784
+ is required (all of them after :meth:`release_operands`), otherwise
2785
+ a :class:`ValueError` is raised.
2786
+
2787
+ - This method will perform various checks on the new operands to make sure:
2788
+
2789
+ - The shapes, strides, datatypes match those of the old ones.
2790
+ - The packages that the operands belong to match those of the old ones.
2791
+ - If input tensors are on GPU, the device must match.
2792
+
2793
+ Examples:
2794
+
2795
+ >>> import cupy as cp
2796
+ >>> import nvmath
2797
+
2798
+ Create two 3-D float64 ndarrays on the GPU:
2799
+
2800
+ >>> M, N, K = 128, 128, 256
2801
+ >>> a = cp.random.rand(M, K)
2802
+ >>> b = cp.random.rand(K, N)
2803
+
2804
+ Create an matrix multiplication object as a context manager
2805
+
2806
+ >>> with nvmath.linalg.advanced.Matmul(a, b) as mm:
2807
+ ... # Plan the operation.
2808
+ ... algorithms = mm.plan()
2809
+ ...
2810
+ ... # Execute the MM to get the first result.
2811
+ ... r1 = mm.execute()
2812
+ ...
2813
+ ... # Reset the operands to new CuPy ndarrays.
2814
+ ... a_new = cp.random.rand(M, K)
2815
+ ... b_new = cp.random.rand(K, N)
2816
+ ... mm.reset_operands(a=a_new, b=b_new)
2817
+ ...
2818
+ ... # Execute to get the new result corresponding to the updated operands.
2819
+ ... r2 = mm.execute()
2820
+
2821
+ With :meth:`reset_operands`, minimal overhead is achieved as problem
2822
+ specification and planning are only performed once.
2823
+
2824
+ For the particular example above, the operands are on the GPU, so calling
2825
+ :meth:`reset_operands` only updates internal references and is efficient. An
2826
+ alternative would be to modify the existing operands in-place (e.g.
2827
+ ``a[:]=a_new`` and ``b[:]=b_new``), but that would copy data and have
2828
+ performance implications. When using in-place updates, the operand memory space
2829
+ must be accessible from the execution space.
2830
+
2831
+ For more details, please refer to `inplace update example
2832
+ <https://github.com/NVIDIA/nvmath-python/tree/main/examples/linalg/advanced/matmul/example05_stateful_inplace.py>`_.
2833
+
2834
+ .. seealso::
2835
+ :meth:`release_operands`, :meth:`reset_operands_unchecked`
2836
+ """
2837
+
2838
+ if c is not None and self.num_operands == 2:
2839
+ raise ValueError(
2840
+ "The matrix multiplication problem specification does not include operand C, so it cannot be reset."
2841
+ )
2842
+
2843
+ # If operands have been released, all required operands must be provided.
2844
+ if self._operands_released:
2845
+ # Check that all main operands are provided
2846
+ all_main_provided = a is not None and b is not None and (self.num_operands != 3 or c is not None)
2847
+
2848
+ # Check epilog_inputs if required
2849
+ epilog_names = self.epilog_inputs_traits.keys()
2850
+ epilog_ok = True
2851
+ if epilog_names:
2852
+ if epilog_inputs is None:
2853
+ epilog_ok = False
2854
+ elif epilog_names != epilog_inputs.keys():
2855
+ raise ValueError(
2856
+ f"The epilog inputs {epilog_names} are required. "
2857
+ f"The provided epilog input names are {epilog_inputs.keys()}."
2858
+ )
2859
+
2860
+ scales_ok = True
2861
+ needs_scales = self.input_type_width <= 8
2862
+ if needs_scales and quantization_scales is None:
2863
+ scales_ok = False
2864
+
2865
+ if not all_main_provided or not epilog_ok or not scales_ok:
2866
+ raise ValueError(
2867
+ "After release_operands(), all required operands must be provided to reset_operands(). "
2868
+ f"Required: a, b{', c' if self.num_operands == 3 else ''}"
2869
+ f"{', quantization_scales' if needs_scales else ''}"
2870
+ f"{', epilog_inputs' if epilog_names else ''}"
2871
+ )
2872
+
2873
+ # Initialize operands and epilog_operands to prepare for new values
2874
+ self.operands = [None] * self.num_operands # type: ignore[list-item]
2875
+ epilog_names = self.epilog_inputs_traits.keys()
2876
+ self.epilog_operands = dict.fromkeys(epilog_names)
2877
+ if needs_scales:
2878
+ self.quantization_scales = _configuration.MatmulQuantizationScales()
2879
+ elif all(arg is None for arg in (a, b, c, alpha, beta, quantization_scales, epilog_inputs)):
2880
+ # All arguments are None: there is nothing to update, so reject the call.
2881
+ raise ValueError("reset_operands() requires at least one operand to be provided.")
2882
+
2883
+ # Update alpha.
2884
+ if alpha is not None:
2885
+ try:
2886
+ self.alpha[0] = alpha
2887
+ except (ValueError, TypeError) as e:
2888
+ raise ValueError(
2889
+ f"The value provided for alpha {alpha} is not convertible to dtype '{self.alpha.dtype}'."
2890
+ ) from e
2891
+
2892
+ # Update beta.
2893
+ if beta is not None:
2894
+ if self.num_operands == 2:
2895
+ self.logger.warning(f"Matmul: The provided beta value {beta} is ignored since operand C is not specified.")
2896
+ else:
2897
+ try:
2898
+ self.beta[0] = beta
2899
+ except (ValueError, TypeError) as e:
2900
+ raise ValueError(
2901
+ f"The value provided for beta {beta} is not convertible to dtype '{self.beta.dtype}'."
2902
+ ) from e
2903
+
2904
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
2905
+
2906
+ if epilog_inputs is not None and "aux_quantization_scale" in epilog_inputs:
2907
+ epilog_inputs = epilog_inputs.copy()
2908
+ aux_quantization_scale = epilog_inputs.pop("aux_quantization_scale")
2909
+ self._validate_epilog_aux_scale(aux_quantization_scale, required=False)
2910
+ self._prepare_single_validated_scale(
2911
+ aux_quantization_scale, "epilog_aux", cublas_operand="epilogue_aux", stream_holder=stream_holder
2912
+ )
2913
+
2914
+ # Reset the provided operands.
2915
+ if a is not None:
2916
+ a = tensor_wrapper.wrap_operand(a)
2917
+ index = 0
2918
+ self._check_and_set_operand(
2919
+ a,
2920
+ "A",
2921
+ self.mm_desc_ifc,
2922
+ stream_holder,
2923
+ operand_index=index,
2924
+ dtype=self.a_dtype_name,
2925
+ extents=self.operand_extents[index],
2926
+ strides=self.operand_strides[index],
2927
+ )
2928
+
2929
+ if b is not None:
2930
+ b = tensor_wrapper.wrap_operand(b)
2931
+ index = 1
2932
+ self._check_and_set_operand(
2933
+ b,
2934
+ "B",
2935
+ self.mm_desc_ifc,
2936
+ stream_holder,
2937
+ operand_index=index,
2938
+ dtype=self.b_dtype_name,
2939
+ extents=self.operand_extents[index],
2940
+ strides=self.operand_strides[index],
2941
+ )
2942
+
2943
+ if c is not None: # If we get here, we know that C is one of the operands in the problem specification.
2944
+ c = tensor_wrapper.wrap_operand(c)
2945
+ index = 2
2946
+ self._check_and_set_operand(
2947
+ c,
2948
+ "C",
2949
+ self.mm_desc_ifc,
2950
+ stream_holder,
2951
+ operand_index=index,
2952
+ dtype=self.c_dtype_name,
2953
+ extents=self.operand_extents[index],
2954
+ strides=self.operand_strides[index],
2955
+ )
2956
+
2957
+ # Update quantization_scales after operands are set, so _validate_operand_scales
2958
+ # can read self.operands[i].size for block-scaling shape checks.
2959
+ if quantization_scales is not None:
2960
+ quantization_scales = self._validate_operand_scales(quantization_scales, all_required=False)
2961
+ if quantization_scales.a is not None:
2962
+ self.quantization_scales.a = quantization_scales.a
2963
+ if quantization_scales.b is not None:
2964
+ self.quantization_scales.b = quantization_scales.b
2965
+ if quantization_scales.c is not None:
2966
+ self.quantization_scales.c = quantization_scales.c
2967
+ if quantization_scales.d is not None:
2968
+ self.quantization_scales.d = quantization_scales.d
2969
+ self._prepare_operand_quantization_scales(self.quantization_scales, stream_holder)
2970
+
2971
+ # Reset the provided epilog inputs.
2972
+ if epilog_inputs is not None:
2973
+ for name in epilog_inputs:
2974
+ epilog_input = tensor_wrapper.wrap_operand(epilog_inputs[name])
2975
+ self._check_and_set_operand(
2976
+ epilog_input,
2977
+ name,
2978
+ self.mm_desc_ifc,
2979
+ stream_holder,
2980
+ epilog_name=name,
2981
+ dtype=self.epilog_inputs_traits[name].dtype,
2982
+ extents=self.epilog_inputs_traits[name].extents,
2983
+ strides=self.epilog_inputs_traits[name].strides,
2984
+ )
2985
+
2986
+ self._operands_released = False
2987
+
2988
+ @utils.precondition(_check_valid_matmul)
2989
+ def release_operands(self):
2990
+ """
2991
+ {release_operands}
2992
+ """
2993
+ if self._operands_released:
2994
+ self.logger.info("Operands have already been released; nothing to do.")
2995
+ return
2996
+
2997
+ # CUDA memory space:
2998
+ # self.operands, self.epilog_operands, and
2999
+ # self.quantization_scales_device hold direct user references;
3000
+ # self.quantization_scales holds the user-provided scales object.
3001
+ # CPU memory space:
3002
+ # self.operands, self.epilog_operands, and
3003
+ # self.quantization_scales_device hold internal device mirrors;
3004
+ # self.quantization_scales holds the user-provided scales object;
3005
+ # self.cpu_c_ref holds a direct reference to the user's CPU operand C.
3006
+ # In both cases, release all of them.
3007
+ # Note that if/when possible, we keep the TensorHolder wrappers and
3008
+ # container structures alive and only release the internal tensor reference.
3009
+ # This is useful when reset_operands_unchecked is called subsequently
3010
+ # because it can reuse the existing wrappers, saving overhead.
3011
+
3012
+ self.operands[0].tensor = None # A
3013
+ self.operands[1].tensor = None # B
3014
+ if self.num_operands == 3:
3015
+ self.operands[2].tensor = None # C
3016
+ for op in self.epilog_operands.values():
3017
+ op.tensor = None
3018
+ for op in self.quantization_scales_device.values():
3019
+ op.tensor = None
3020
+
3021
+ # For the quant scales, the attribute itself might not exist,
3022
+ # so we need to check for that first.
3023
+ if hasattr(self, "quantization_scales"):
3024
+ self.quantization_scales.a = None
3025
+ self.quantization_scales.b = None
3026
+ self.quantization_scales.c = None
3027
+ self.quantization_scales.d = None
3028
+
3029
+ if self.memory_space == "cpu" and self.cpu_c_ref is not None:
3030
+ self.cpu_c_ref.tensor = None
3031
+
3032
+ self._operands_released = True
3033
+ self.logger.info("User-provided operands have been released.")
3034
+
3035
+ @utils.precondition(_check_valid_matmul)
3036
+ @utils.precondition(_check_planned, "Autotuning")
3037
+ @utils.precondition(_check_valid_operands, "Autotuning")
3038
+ def autotune(
3039
+ self, iterations=10, prune=None, release_workspace=False, stream: utils.AnyStream | int | None = None
3040
+ ): # Prune means keep top N of the algorithms only.
3041
+ """
3042
+ Autotune the matrix multiplication to order the algorithms from the fastest measured
3043
+ execution time to the slowest. Once autotuned, the optimally-ordered algorithm
3044
+ sequence can be accessed using :py:attr:`algorithms`.
3045
+
3046
+ .. note::
3047
+ This function will benchmark each of the algorithms and order the algorithms
3048
+ based on the benchmark results. The measurements can be impacted by factors
3049
+ such as GPU temperature, clock settings, or power consumption. Autotuning
3050
+ in an unstable environment can result in a suboptimal algorithm ordering.
3051
+ If you experience performance problems, consider omitting the autotuning.
3052
+
3053
+ Args:
3054
+ iterations: The number of autotuning iterations to perform.
3055
+
3056
+ prune: An integer N, specifying the top N fastest algorithms to retain after
3057
+ autotuning. The default is to retain all algorithms.
3058
+
3059
+ release_workspace: {release_workspace}
3060
+
3061
+ stream: {stream}
3062
+ """
3063
+ self.logger.info("= AUTOTUNING PHASE =")
3064
+ # Measure time taken for autotuning.
3065
+ from timeit import default_timer as timer
3066
+
3067
+ self.logger.info("Starting autotuning...")
3068
+ start = timer()
3069
+
3070
+ assert self.algorithm_objects is not None, "Internal Error. self.algorithm_objects should have been set by self.plan()."
3071
+ num_algorithms = len(self.algorithm_objects)
3072
+ if num_algorithms == 1:
3073
+ self.logger.info("Skipping the autotuning, because only one algorithm has been returned in the planning phase.")
3074
+ return
3075
+ limit = min(prune, num_algorithms) if prune is not None else num_algorithms
3076
+ self.logger.info(
3077
+ f"The number of algorithms in the plan is {num_algorithms}, from which the top {limit} will be retained."
3078
+ )
3079
+ self.logger.info(f"The requested number of iterations is {iterations}.")
3080
+
3081
+ # Autotune setup.
3082
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
3083
+
3084
+ # Create empty tensors for auxiliary output.
3085
+ epilog_outputs = {}
3086
+ for handler in self.epilog_output_handlers:
3087
+ name = handler.name
3088
+ shape, strides, dtype_name = handler.attributes()
3089
+ epilog_outputs[name] = aux = utils.create_empty_tensor(
3090
+ self.result_class,
3091
+ shape,
3092
+ dtype_name,
3093
+ self.device_id,
3094
+ stream_holder,
3095
+ verify_strides=False,
3096
+ strides=strides,
3097
+ )
3098
+
3099
+ # Update the data pointer in the MM descriptor.
3100
+ handler.update_pointer(self.mm_desc_ifc, aux.data_ptr)
3101
+
3102
+ # Take a copy of `c` for autotuning to avoid clobbering it if inplace=True.
3103
+ c = None
3104
+ if self.inplace:
3105
+ # `c` is guaranteed to exist. Clone `c` and copy into it, since `tensor.to`
3106
+ # returns the original tensor when the device ID is the same.
3107
+ c = self.operands[2]
3108
+ c = utils.create_empty_tensor(
3109
+ c.__class__, c.shape, c.dtype, self.device_id, stream_holder, verify_strides=False, strides=c.strides
3110
+ )
3111
+ c.copy_(self.operands[2], stream_holder)
3112
+ assert c.data_ptr != self.operands[2].data_ptr, "Internal error."
3113
+ elif self.num_operands == 3:
3114
+ c = self.operands[2]
3115
+
3116
+ # Create empty tensor for the result, if the operation is not in-place.
3117
+ assert self.result_traits is not None, "Internal Error. self.result_traits should have been set by self.plan()."
3118
+ if self.inplace:
3119
+ result = c
3120
+ else:
3121
+ result = utils.create_empty_tensor(
3122
+ self.result_class,
3123
+ self.result_traits.result_shape,
3124
+ self.d_dtype_name,
3125
+ self.device_id,
3126
+ stream_holder,
3127
+ verify_strides=False,
3128
+ strides=self.result_traits.result_strides,
3129
+ )
3130
+ result_ptr = result.data_ptr
3131
+
3132
+ a, b = self.operands[0], self.operands[1]
3133
+ alpha_ptr, a_ptr, b_ptr, beta_ptr = self.alpha.ctypes.data, a.data_ptr, b.data_ptr, self.beta.ctypes.data
3134
+ # If `c` is not provided, set c_ptr to nullptr.
3135
+ if self.num_operands == 3:
3136
+ c_ptr = c.data_ptr
3137
+ else:
3138
+ assert self.beta[0] == 0.0, "Internal error: beta must be zero if `c` is not specified."
3139
+ c_ptr = 0
3140
+
3141
+ def flush_cache():
3142
+ """
3143
+ Write data to a temporary buffer to flush the L2 cache.
3144
+ """
3145
+
3146
+ @functools.cache
3147
+ def get_l2_cache_size(device_id):
3148
+ device = Device(device_id)
3149
+ return device.properties.l2_cache_size
3150
+
3151
+ l2_cache_size = get_l2_cache_size(self.device_id)
3152
+ cpu_buffer = np.zeros(l2_cache_size, dtype=np.uint8)
3153
+ tensor_wrapper.wrap_operand(cpu_buffer).to(device_id=self.device_id, stream_holder=stream_holder)
3154
+
3155
+ with self.workspace.allocate_perhaps(
3156
+ stream_holder,
3157
+ get_last_event=lambda: self.last_compute_event,
3158
+ ) as ws:
3159
+
3160
+ def execute_matmul(algorithm_ptr):
3161
+ cublaslt.matmul(
3162
+ self.handle,
3163
+ self.mm_desc,
3164
+ alpha_ptr,
3165
+ a_ptr,
3166
+ self.a_layout_ptr,
3167
+ b_ptr,
3168
+ self.b_layout_ptr,
3169
+ beta_ptr,
3170
+ c_ptr,
3171
+ self.c_layout_ptr,
3172
+ result_ptr,
3173
+ self.d_layout_ptr,
3174
+ algorithm_ptr,
3175
+ ws.raw_ptr,
3176
+ ws.size,
3177
+ stream_holder.ptr,
3178
+ )
3179
+
3180
+ # Tune.
3181
+ with utils.cuda_call_ctx(stream_holder, blocking=False, timing=False) as (
3182
+ self.last_compute_event,
3183
+ _,
3184
+ ):
3185
+ gpu_times = np.empty(shape=(len(self.algorithms_buffer), iterations), dtype=float)
3186
+ algorithm_idxs = list(range(len(self.algorithms_buffer)))
3187
+ timing_enabled_options = {utils.timing_enabled_name(): True}
3188
+ start0 = stream_holder.obj.device.create_event(options=timing_enabled_options)
3189
+ end0 = stream_holder.obj.device.create_event(options=timing_enabled_options)
3190
+ for i in range(iterations):
3191
+ random.shuffle(algorithm_idxs)
3192
+ for algorithm_idx in algorithm_idxs:
3193
+ algorithm_ptr = self.algorithms_buffer[algorithm_idx]["algo"].ctypes.data
3194
+ stream_holder.obj.record(start0)
3195
+ execute_matmul(algorithm_ptr=algorithm_ptr)
3196
+ stream_holder.obj.record(end0)
3197
+ # FIXME: @dching Calling sync() here could slow down tuning by
3198
+ # forcing the device to wait for the host to record the elapsed
3199
+ # time. It may be faster to store references to 2 * len(iterations)
3200
+ # * len(algorithms_buffer) Events and compute the elapsed time at
3201
+ # the end.
3202
+ end0.sync()
3203
+ gpu_times[algorithm_idx, i] = end0 - start0
3204
+ # Avoid potential overflow for inplace operations.
3205
+ if self.inplace:
3206
+ c.copy_(self.operands[2], stream_holder)
3207
+ flush_cache()
3208
+
3209
+ gpu_times = np.median(gpu_times, axis=1)
3210
+
3211
+ if release_workspace:
3212
+ ws.release(self.last_compute_event)
3213
+ self.last_compute_event = None
3214
+
3215
+ # Get the sort order based on the GPU times.
3216
+ sorted_gpu_times, sort_order = zip(*sorted(zip(gpu_times, range(num_algorithms), strict=True)), strict=True)
3217
+
3218
+ # Reorder the algorithms buffer and algorithm objects according to the sort order,
3219
+ # and prune it.
3220
+ sort_order = sort_order[:limit]
3221
+ self.algorithms_buffer = self.algorithms_buffer[list(sort_order)]
3222
+ self.algorithm_objects = tuple(self.algorithm_objects[i] for i in sort_order)
3223
+
3224
+ # Update cached first (best) algorithm struct after tuning.
3225
+ self.cached_best_algorithm_struct = self.algorithms_buffer[0]["algo"]
3226
+
3227
+ # Create the map from object to buffer.
3228
+ self.algorithm_object_to_buffer = dict(zip(self.algorithm_objects, self.algorithms_buffer, strict=True))
3229
+
3230
+ gpu_times_str = ", ".join(f"{t:0.3f}" for t in gpu_times)
3231
+ self.logger.info(f"The autotuned GPU times (in milliseconds) are: {gpu_times_str}.")
3232
+ self.logger.info(f"The corresponding sort order is: {sort_order}.")
3233
+ orig_flop_rate = self.flop_count / gpu_times[0] * 1000
3234
+ if sort_order[0] != 0:
3235
+ self.logger.info(
3236
+ f"Autotuning found that the algorithm originally ranked {sort_order[0]} is the best out of the "
3237
+ f"{num_algorithms} in the plan, and moved it to rank 0."
3238
+ )
3239
+ new_flop_rate = self.flop_count / sorted_gpu_times[0] * 1000
3240
+ self.logger.info(
3241
+ f"Autotuning has improved performance from {formatters.FLOPSStr(orig_flop_rate, 'FLOP/s')} to "
3242
+ f"{formatters.FLOPSStr(new_flop_rate, 'FLOP/s')}."
3243
+ )
3244
+ else:
3245
+ self.logger.info(
3246
+ f"Autotuning found that the algorithm ranked best by the plan heuristics remains the best out of the "
3247
+ f"{num_algorithms} algorithms in the plan."
3248
+ )
3249
+ self.logger.info(f"The best performance remains at {formatters.FLOPSStr(orig_flop_rate, 'FLOP/s')}.")
3250
+
3251
+ end = timer()
3252
+ self.logger.info(f"The autotuning took {(end - start) * 1000.0:.3f} ms to complete.")
3253
+
3254
+ def _create_result_tensor(self, stream_holder: utils.StreamHolder, log_debug: bool):
3255
+ """
3256
+ Create the output result tensor for the matmul operation.
3257
+
3258
+ We need special treatment for FP4 output (``float4_e2m1fn_x2``),
3259
+ because the logical shape ``(M, N)`` from ``result_traits`` is converted
3260
+ to a packed shape where one dimension is halved
3261
+ (since two FP4 values are packed per byte).
3262
+
3263
+ For all other dtypes, the logical shape is used directly.
3264
+ """
3265
+ assert self.result_traits is not None, (
3266
+ "Internal error: result_traits must be set by plan() before creating the result tensor."
3267
+ )
3268
+
3269
+ if self.d_dtype != CudaDataType.CUDA_R_4F_E2M1:
3270
+ # Non-FP4 output: no packing needed, use logical shape as-is.
3271
+ result_shape = self.result_traits.result_shape
3272
+ result_strides = self.result_traits.result_strides
3273
+
3274
+ if log_debug:
3275
+ self.logger.debug(
3276
+ f"The output tensor shape = {result_shape} with strides = "
3277
+ f"{result_strides} and data type '{self.d_dtype_name}'."
3278
+ )
3279
+
3280
+ self.result = utils.create_empty_tensor(
3281
+ self.result_class,
3282
+ result_shape,
3283
+ self.d_dtype_name,
3284
+ self.device_id,
3285
+ stream_holder,
3286
+ verify_strides=False,
3287
+ strides=result_strides,
3288
+ )
3289
+ return
3290
+
3291
+ # If we are here, we are dealing with FP4 output that must be packed.
3292
+ # Convert logical shape/strides to packed (physical) shape/strides.
3293
+ # Batching dimensions (leading) are unchanged.
3294
+ result_ndim = len(self.result_traits.result_shape)
3295
+ assert result_ndim >= 2, "Internal error: result must be at least 2D."
3296
+ if self.result_traits.d_layout_traits.order == cublaslt.Order.ROW:
3297
+ packed_axis = result_ndim - 1
3298
+ else:
3299
+ packed_axis = result_ndim - 2
3300
+ result_packed_shape = tuple(e if i != packed_axis else e // 2 for i, e in enumerate(self.result_traits.result_shape))
3301
+ result_packed_strides = tuple(
3302
+ s // 2 if i != packed_axis else s for i, s in enumerate(self.result_traits.result_strides)
3303
+ )
3304
+
3305
+ if log_debug:
3306
+ self.logger.debug(
3307
+ f"FP4 output: logical shape = {tuple(self.result_traits.result_shape)}, "
3308
+ f"logical strides = {tuple(self.result_traits.result_strides)} -> "
3309
+ f"packed shape = {result_packed_shape}, packed strides = {result_packed_strides}, "
3310
+ f"data type '{self.d_dtype_name}'."
3311
+ )
3312
+
3313
+ self.result = utils.create_empty_tensor(
3314
+ self.result_class,
3315
+ result_packed_shape,
3316
+ self.d_dtype_name,
3317
+ self.device_id,
3318
+ stream_holder,
3319
+ verify_strides=False,
3320
+ strides=result_packed_strides,
3321
+ )
3322
+
3323
+ @utils.precondition(_check_valid_matmul)
3324
+ @utils.precondition(_check_planned, "Execution")
3325
+ @utils.precondition(_check_valid_operands, "Execution")
3326
+ def execute(self, *, algorithm=None, release_workspace=False, stream: utils.AnyStream | int | None = None):
3327
+ """
3328
+ Execute a prepared (planned and possibly autotuned) matrix multiplication.
3329
+
3330
+ Args:
3331
+ algorithm: An algorithm chosen from the sequence returned by
3332
+ :meth:`plan` or :py:attr:`algorithms`. By default, the first algorithm in
3333
+ the sequence is used.
3334
+
3335
+ .. experimental:: parameter
3336
+
3337
+ release_workspace: {release_workspace}
3338
+
3339
+ stream: {stream}
3340
+
3341
+ Returns:
3342
+ {result}
3343
+ """
3344
+ log_info = self.logger.isEnabledFor(logging.INFO)
3345
+ log_debug = self.logger.isEnabledFor(logging.DEBUG)
3346
+
3347
+ if log_info:
3348
+ self.logger.info("= EXECUTION PHASE =")
3349
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
3350
+ if log_info:
3351
+ self.logger.info(f"The specified stream for execute() is {stream_holder.obj}.")
3352
+
3353
+ # Create empty tensors for auxiliary output.
3354
+ for handler in self.epilog_output_handlers:
3355
+ name = handler.name
3356
+ shape, strides, dtype_name = handler.attributes()
3357
+ if log_debug:
3358
+ self.logger.debug(f"Beginning auxiliary output tensor '{name}' creation...")
3359
+ self.logger.debug(f"The '{name}' tensor shape = {shape} with strides = {strides} and data type '{dtype_name}'.")
3360
+ self.epilog_outputs[name] = aux = utils.create_empty_tensor(
3361
+ self.result_class,
3362
+ shape,
3363
+ dtype_name,
3364
+ self.device_id,
3365
+ stream_holder,
3366
+ verify_strides=False,
3367
+ strides=strides,
3368
+ )
3369
+ if log_debug:
3370
+ self.logger.debug(f"The auxiliary output tensor '{name}' has been created.")
3371
+ if self.preferences.epilog.aux_amax: # type: ignore[attr-defined]
3372
+ if "float8" not in dtype_name:
3373
+ raise ValueError("epilog.aux_amax=True is not supported when epilog output type is not FP8.")
3374
+ self.epilog_outputs[f"{name}_amax"] = utils.create_empty_tensor(
3375
+ self.result_class,
3376
+ (1,),
3377
+ "float32", # This is the only type allowed by cuBLAS for AMAX.
3378
+ self.device_id,
3379
+ stream_holder,
3380
+ verify_strides=False,
3381
+ )
3382
+ self.mm_desc_ifc.epilogue_aux_amax_pointer = self.epilog_outputs[f"{name}_amax"].data_ptr
3383
+
3384
+ # Update the data pointer in the MM descriptor.
3385
+ handler.update_pointer(self.mm_desc_ifc, aux.data_ptr)
3386
+
3387
+ # Create empty tensor for the result, if the operation is not in-place.
3388
+ assert self.result_traits is not None, "Internal Error. self.result_traits should have been set by self.plan()"
3389
+ if self.inplace:
3390
+ if log_debug:
3391
+ self.logger.debug("The operation is in-place (operand C will be overwritten).")
3392
+ self.result = self.operands[2]
3393
+ else:
3394
+ if log_debug:
3395
+ self.logger.debug("Beginning output (empty) tensor creation...")
3396
+ self._create_result_tensor(stream_holder, log_debug)
3397
+ if log_debug:
3398
+ self.logger.debug("The output (empty) tensor has been created.")
3399
+
3400
+ self.aux_outputs = {}
3401
+
3402
+ if self.options.result_amax:
3403
+ self.aux_outputs["result_amax"] = utils.create_empty_tensor(
3404
+ self.result_class,
3405
+ (1,),
3406
+ "float32", # This is the only type allowed by cuBLAS for AMAX.
3407
+ self.device_id,
3408
+ stream_holder,
3409
+ verify_strides=False,
3410
+ )
3411
+ self.mm_desc_ifc.amax_d_pointer = self.aux_outputs["result_amax"].data_ptr
3412
+
3413
+ if self.options.block_scaling and self.d_dtype_width <= 8: # FP8 and FP4
3414
+ num_output_elements = (
3415
+ self.mm_traits.batch_count * self.result_traits.result_shape[-1] * self.result_traits.result_shape[-2]
3416
+ )
3417
+ d_out_scale, _ = _create_d_out_scale_and_scale_mode(
3418
+ self.result_class, num_output_elements, self.d_dtype_width, self.device_id, stream_holder
3419
+ )
3420
+ self.aux_outputs["d_out_scale"] = d_out_scale
3421
+ self.mm_desc_ifc.d_out_scale_pointer = d_out_scale.data_ptr
3422
+
3423
+ # Select the first (best) algorithm if one is not provided.
3424
+ if algorithm is None:
3425
+ algorithm_struct = self.cached_best_algorithm_struct
3426
+ if log_info:
3427
+ self.logger.info(
3428
+ "The highest ranked algorithm in the plan (algorithm id = "
3429
+ f"{self.algorithm_objects[0].algorithm_id}) will be used."
3430
+ )
3431
+ else:
3432
+ if algorithm not in self.algorithm_objects:
3433
+ raise ValueError("Algorithm passed to execute() has to be included in the plan() algorithms")
3434
+ algorithm_struct = self.algorithm_object_to_buffer[algorithm]["algo"]
3435
+ if log_info:
3436
+ self.logger.info(f"The specified algorithm (algorithm id = {algorithm.algorithm_id}) will be used.")
3437
+
3438
+ a, b = self.operands[0], self.operands[1]
3439
+
3440
+ # If `c` is not provided, set c_ptr to nullptr.
3441
+ if self.num_operands == 3:
3442
+ c_ptr = self.operands[2].data_ptr
3443
+ else:
3444
+ assert self.beta[0] == 0.0, "Internal error: beta must be zero if `c` is not specified."
3445
+ c_ptr = 0
3446
+
3447
+ with self.workspace.allocate_perhaps(
3448
+ stream_holder,
3449
+ get_last_event=lambda: self.last_compute_event,
3450
+ ) as ws:
3451
+ if log_info:
3452
+ self.logger.info("Starting matrix multiplication...")
3453
+ self.logger.info(f"{self.call_prologue}")
3454
+ with utils.cuda_call_ctx(stream_holder, self.blocking, timing=log_info) as (
3455
+ self.last_compute_event,
3456
+ elapsed,
3457
+ ):
3458
+ cublaslt.matmul(
3459
+ self.handle,
3460
+ self.mm_desc,
3461
+ self.alpha.ctypes.data,
3462
+ a.data_ptr,
3463
+ self.a_layout_ptr,
3464
+ b.data_ptr,
3465
+ self.b_layout_ptr,
3466
+ self.beta.ctypes.data,
3467
+ c_ptr,
3468
+ self.c_layout_ptr,
3469
+ self.result.data_ptr,
3470
+ self.d_layout_ptr,
3471
+ algorithm_struct.ctypes.data,
3472
+ ws.raw_ptr,
3473
+ ws.size,
3474
+ stream_holder.ptr,
3475
+ )
3476
+
3477
+ if log_info and elapsed.data is not None:
3478
+ self.logger.info(f"The matrix multiplication calculation took {elapsed.data:.3f} ms to complete.")
3479
+
3480
+ if release_workspace:
3481
+ ws.release(self.last_compute_event)
3482
+ self.last_compute_event = None
3483
+
3484
+ # Return the result and auxiliary outputs, if present.
3485
+ all_outputs = self.epilog_outputs | self.aux_outputs
3486
+ if self.memory_space == "cpu":
3487
+ if self.inplace:
3488
+ # Overwrite operand C.
3489
+ assert self.cpu_c_ref is not None, "Internal error."
3490
+ c = self.cpu_c_ref
3491
+ c.copy_(self.result, stream_holder=stream_holder)
3492
+ out = c.tensor
3493
+ else:
3494
+ out = self.result.to("cpu", stream_holder=stream_holder).tensor
3495
+ # Copy auxiliary output to CPU.
3496
+ aux = {name: all_outputs[name].to("cpu", stream_holder=stream_holder).tensor for name in all_outputs}
3497
+ else:
3498
+ out = self.result.tensor
3499
+ # Return the unwrapped epilog output tensor(s).
3500
+ aux = {name: all_outputs[name].tensor for name in all_outputs}
3501
+
3502
+ # Release internal reference to the result to permit recycling of memory.
3503
+ self.result = None
3504
+ self.aux_outputs = {}
3505
+ self.epilog_outputs = {}
3506
+
3507
+ if aux:
3508
+ return out, aux
3509
+
3510
+ return out
3511
+
3512
+ def free(self):
3513
+ """Free Matmul resources.
3514
+
3515
+ It is recommended that the :class:`Matmul` object be used within a context, but if
3516
+ it is not possible then this method must be called explicitly to ensure that the
3517
+ matrix multiplication resources (especially internal library objects) are properly
3518
+ cleaned up.
3519
+ """
3520
+
3521
+ if not self.valid_state:
3522
+ return
3523
+
3524
+ try:
3525
+ # Ensure ordering with respect to the last computation to avoid
3526
+ # race conditions when releasing internal resources.
3527
+ self.workspace.release(self.last_compute_event)
3528
+ self.last_compute_event = None
3529
+
3530
+ self._free_plan_resources()
3531
+
3532
+ # Destroy matmul descriptor.
3533
+ if self.mm_desc is not None:
3534
+ cublaslt.matmul_desc_destroy(self.mm_desc)
3535
+ self.mm_desc = None
3536
+
3537
+ # Note: self.handle is obtained via get_handle and doesn't need
3538
+ # explicit destruction, it's cached globally
3539
+ # and cleaned up at program exit.
3540
+ # Set all attributes to None except for logger and valid_state.
3541
+ _keep = {"logger", "valid_state"}
3542
+ for attr in list(vars(self)):
3543
+ if attr not in _keep:
3544
+ setattr(self, attr, None)
3545
+
3546
+ except Exception as e:
3547
+ self.logger.critical("Internal error: only part of the Matmul object's resources have been released.")
3548
+ self.logger.critical(str(e))
3549
+ raise e
3550
+ finally:
3551
+ self.valid_state = False
3552
+
3553
+ self.logger.info("The Matmul object's resources have been released.")
3554
+
3555
+
3556
+ @utils.docstring_decorator(SHARED_MM_DOCUMENTATION, skip_missing=False)
3557
+ def matmul(
3558
+ a,
3559
+ b,
3560
+ /,
3561
+ c=None,
3562
+ *,
3563
+ alpha=None,
3564
+ beta=None,
3565
+ epilog=None,
3566
+ epilog_inputs=None,
3567
+ qualifiers=None,
3568
+ quantization_scales=None,
3569
+ options: _configuration.MatmulOptions | dict[str, typing.Any] | None = None,
3570
+ preferences=None,
3571
+ algorithm=None,
3572
+ stream: utils.AnyStream | int | None = None,
3573
+ ):
3574
+ """
3575
+ Perform the specified matrix multiplication computation
3576
+ :math:`\\mathcal{{F}}(\\alpha a @ b + \\beta c)`, where :math:`\\mathcal{{F}}` is
3577
+ the epilog. This function-form is a wrapper around the stateful
3578
+ :class:`Matmul` object APIs and is meant for *single* use (the user needs to perform
3579
+ just one matrix multiplication, for example), in which case there is no possibility of
3580
+ amortizing preparatory costs.
3581
+
3582
+ Detailed information on what's happening within this function can be obtained by passing
3583
+ in a :class:`logging.Logger` object to :class:`MatmulOptions` or by setting the
3584
+ appropriate options in the root logger object, which is used by default:
3585
+
3586
+ >>> import logging
3587
+ >>> logging.basicConfig(
3588
+ ... level=logging.INFO,
3589
+ ... format="%(asctime)s %(levelname)-8s %(message)s",
3590
+ ... datefmt="%m-%d %H:%M:%S",
3591
+ ... )
3592
+
3593
+ A user can select the desired logging level and, in general, take advantage of all of
3594
+ the functionality offered by the Python `logging` module.
3595
+
3596
+ Args:
3597
+ a: {a}
3598
+
3599
+ b: {b}
3600
+
3601
+ c: {c}
3602
+ {c_admonitions}
3603
+
3604
+ alpha: {alpha}
3605
+
3606
+ beta: {beta}
3607
+
3608
+ epilog: {epilog}
3609
+
3610
+ epilog_inputs: {epilog_inputs}
3611
+
3612
+ qualifiers: {qualifiers}
3613
+
3614
+ options: {options}
3615
+
3616
+ preferences: {preferences}
3617
+
3618
+ algorithm: An object of type :class:`Algorithm` objects can be directly provided to
3619
+ bypass planning, if desired. The algorithm object must be compatible with the
3620
+ matrix multiplication. A typical use for this option is to provide an algorithm
3621
+ that has been serialized (numpy) from a previously planned and autotuned
3622
+ matrix multiplication.
3623
+
3624
+ stream: {stream}
3625
+
3626
+ quantization_scales: {quantization_scales}
3627
+
3628
+ Returns:
3629
+ {result}
3630
+
3631
+ Semantics:
3632
+ {semantics}
3633
+
3634
+ Narrow-precision support:
3635
+ {narrow_precision}
3636
+
3637
+ .. seealso::
3638
+ :class:`Matmul`, :class:`MatmulOptions`, :class:`MatmulEpilog`,
3639
+ :class:`MatmulPlanPreferences`
3640
+
3641
+ Examples:
3642
+
3643
+ >>> import cupy as cp
3644
+ >>> import nvmath
3645
+
3646
+ Create three float32 ndarrays on the GPU:
3647
+
3648
+ >>> M, N, K = 128, 64, 256
3649
+ >>> a = cp.random.rand(M, K, dtype=cp.float32)
3650
+ >>> b = cp.random.rand(K, N, dtype=cp.float32)
3651
+ >>> c = cp.random.rand(M, N, dtype=cp.float32)
3652
+
3653
+ Perform the operation :math:`\\alpha a @ b + \\beta c` using :func:`matmul`. The
3654
+ result `r` is also a CuPy float32 ndarray:
3655
+
3656
+ >>> r = nvmath.linalg.advanced.matmul(a, b, c, alpha=1.23, beta=0.74)
3657
+
3658
+ An epilog can be used as well. Here we perform
3659
+ :math:`\\operatorname{{RELU}}(\\alpha a @ b + \\beta c)`:
3660
+
3661
+ >>> epilog = nvmath.linalg.advanced.MatmulEpilog.RELU
3662
+ >>> r = nvmath.linalg.advanced.matmul(a, b, c, alpha=1.23, beta=0.74, epilog=epilog)
3663
+
3664
+ Options can be provided to customize the operation:
3665
+
3666
+ >>> compute_type = nvmath.linalg.advanced.MatmulComputeType.COMPUTE_32F_FAST_TF32
3667
+ >>> o = nvmath.linalg.advanced.MatmulOptions(compute_type=compute_type)
3668
+ >>> r = nvmath.linalg.advanced.matmul(a, b, options=o)
3669
+
3670
+ See `MatmulOptions` for the complete list of available options.
3671
+
3672
+ The package current stream is used by default, but a stream can be explicitly
3673
+ provided to the Matmul operation. This can be done if the operands are computed on a
3674
+ different stream, for example:
3675
+
3676
+ >>> s = cp.cuda.Stream()
3677
+ >>> with s:
3678
+ ... a = cp.random.rand(M, K)
3679
+ ... b = cp.random.rand(K, N)
3680
+ >>> r = nvmath.linalg.advanced.matmul(a, b, stream=s)
3681
+
3682
+ The operation above runs on stream `s` and is ordered with respect to the input
3683
+ computation.
3684
+
3685
+ Create NumPy ndarrays on the CPU.
3686
+
3687
+ >>> import numpy as np
3688
+ >>> a = np.random.rand(M, K)
3689
+ >>> b = np.random.rand(K, N)
3690
+
3691
+ Provide the NumPy ndarrays to :func:`matmul`, with the result also being a NumPy
3692
+ ndarray:
3693
+
3694
+ >>> r = nvmath.linalg.advanced.matmul(a, b)
3695
+
3696
+ Notes:
3697
+ - This function is a convenience wrapper around :class:`Matmul` and is
3698
+ specifically meant for *single* use.
3699
+
3700
+ Further examples can be found in the `nvmath/examples/linalg/advanced/matmul
3701
+ <https://github.com/NVIDIA/nvmath-python/tree/main/examples/linalg/advanced/matmul>`_
3702
+ directory.
3703
+ """
3704
+
3705
+ # Set algorithm limit to 1, but take a copy first if needed.
3706
+ if isinstance(preferences, _configuration.MatmulPlanPreferences):
3707
+ preferences = copy.copy(preferences)
3708
+
3709
+ preferences = utils.check_or_create_options(
3710
+ _configuration.MatmulPlanPreferences, preferences, "Matrix multiplication plan preferences"
3711
+ )
3712
+ preferences.limit = 1
3713
+
3714
+ if algorithm is None:
3715
+ algorithms = None
3716
+ else:
3717
+ algorithms = [algorithm] # The type of algorithm should be algorithm.Algorithm and will be checked in plan()
3718
+
3719
+ with Matmul(
3720
+ a,
3721
+ b,
3722
+ c=c,
3723
+ alpha=alpha,
3724
+ beta=beta,
3725
+ qualifiers=qualifiers,
3726
+ options=options,
3727
+ stream=stream,
3728
+ quantization_scales=quantization_scales,
3729
+ ) as mm:
3730
+ mm.plan(preferences=preferences, epilog=epilog, epilog_inputs=epilog_inputs, stream=stream, algorithms=algorithms)
3731
+
3732
+ r = mm.execute(stream=stream)
3733
+
3734
+ return r