nbxtensor 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. nbxtensor/THIRD_PARTY_NOTICES.md +287 -0
  2. nbxtensor/__init__.py +17 -0
  3. nbxtensor/backend/__init__.py +1 -0
  4. nbxtensor/backend/capabilities.py +207 -0
  5. nbxtensor/backend/cpu/__init__.py +1 -0
  6. nbxtensor/backend/cpu/blas.py +102 -0
  7. nbxtensor/backend/cpu/pool.py +204 -0
  8. nbxtensor/backend/cpu_backend.py +162 -0
  9. nbxtensor/backend/device_facts.py +105 -0
  10. nbxtensor/backend/device_files.py +129 -0
  11. nbxtensor/backend/device_names.py +18 -0
  12. nbxtensor/backend/devices/amd/cdna.yml +228 -0
  13. nbxtensor/backend/devices/amd/cdna2.yml +228 -0
  14. nbxtensor/backend/devices/amd/cdna3.yml +227 -0
  15. nbxtensor/backend/devices/apple/apple_m1.yml +266 -0
  16. nbxtensor/backend/devices/apple/apple_m1_max.yml +266 -0
  17. nbxtensor/backend/devices/apple/apple_m1_pro.yml +266 -0
  18. nbxtensor/backend/devices/apple/apple_m1_ultra.yml +266 -0
  19. nbxtensor/backend/devices/apple/apple_m2.yml +266 -0
  20. nbxtensor/backend/devices/apple/apple_m2_max.yml +266 -0
  21. nbxtensor/backend/devices/apple/apple_m2_pro.yml +266 -0
  22. nbxtensor/backend/devices/apple/apple_m2_ultra.yml +266 -0
  23. nbxtensor/backend/devices/apple/apple_m3.yml +266 -0
  24. nbxtensor/backend/devices/apple/apple_m3_max.yml +266 -0
  25. nbxtensor/backend/devices/apple/apple_m3_pro.yml +266 -0
  26. nbxtensor/backend/devices/apple/apple_m3_ultra.yml +266 -0
  27. nbxtensor/backend/devices/apple/apple_m4.yml +266 -0
  28. nbxtensor/backend/devices/apple/apple_m4_max.yml +266 -0
  29. nbxtensor/backend/devices/apple/apple_m4_pro.yml +308 -0
  30. nbxtensor/backend/devices/apple/apple_m5.yml +269 -0
  31. nbxtensor/backend/devices/apple/apple_m5_max.yml +269 -0
  32. nbxtensor/backend/devices/apple/apple_m5_pro.yml +269 -0
  33. nbxtensor/backend/devices/apple/apple_m5_ultra.yml +269 -0
  34. nbxtensor/backend/devices/apple/apple_m6.yml +269 -0
  35. nbxtensor/backend/devices/apple/apple_silicon.yml +263 -0
  36. nbxtensor/backend/devices/nvidia/ampere.yml +214 -0
  37. nbxtensor/backend/devices/nvidia/hopper.yml +213 -0
  38. nbxtensor/backend/devices/nvidia/volta.yml +411 -0
  39. nbxtensor/backend/faults.py +151 -0
  40. nbxtensor/backend/host_memory.py +185 -0
  41. nbxtensor/backend/launcher.py +2350 -0
  42. nbxtensor/backend/launcher_contract.py +429 -0
  43. nbxtensor/backend/metal_backend.py +661 -0
  44. nbxtensor/backend/metal_device.py +1274 -0
  45. nbxtensor/backend/process_memory.py +73 -0
  46. nbxtensor/backend/replay_graph.py +322 -0
  47. nbxtensor/backend/runtime.py +409 -0
  48. nbxtensor/backend/triton_ext_driver.py +735 -0
  49. nbxtensor/dtype/__init__.py +1 -0
  50. nbxtensor/dtype/convert.py +107 -0
  51. nbxtensor/dtype/dtypes.yml +70 -0
  52. nbxtensor/dtype/itemsize.py +166 -0
  53. nbxtensor/dtype/nbx_dtype.py +72 -0
  54. nbxtensor/dtype/operands.py +158 -0
  55. nbxtensor/dtype/outputs.py +64 -0
  56. nbxtensor/dtype/policy.py +155 -0
  57. nbxtensor/dtype/policy.yml +51 -0
  58. nbxtensor/dtype/promotion.py +112 -0
  59. nbxtensor/host.py +55 -0
  60. nbxtensor/io/__init__.py +1 -0
  61. nbxtensor/io/read_rate.py +197 -0
  62. nbxtensor/io/safetensors.py +314 -0
  63. nbxtensor/memory/__init__.py +9 -0
  64. nbxtensor/memory/allocator.py +1988 -0
  65. nbxtensor/memory/arena.py +75 -0
  66. nbxtensor/memory/device_memory.py +150 -0
  67. nbxtensor/memory/device_transfer.py +154 -0
  68. nbxtensor/memory/layout.py +43 -0
  69. nbxtensor/memory/memory_pool.py +191 -0
  70. nbxtensor/memory/metal.py +96 -0
  71. nbxtensor/memory/oom_advice.py +91 -0
  72. nbxtensor/memory/pointer_tables.py +323 -0
  73. nbxtensor/memory/pool.py +507 -0
  74. nbxtensor/memory/shadow.py +43 -0
  75. nbxtensor/memory/slab.py +273 -0
  76. nbxtensor/memory/trace_replay.py +122 -0
  77. nbxtensor/memory/traces/sana-video-2b-720p.16g.2026-11-02.tsv +13610 -0
  78. nbxtensor/memory/vmm.py +118 -0
  79. nbxtensor/ops/__init__.py +1 -0
  80. nbxtensor/ops/_autotune_policy.py +90 -0
  81. nbxtensor/ops/_common.py +32 -0
  82. nbxtensor/ops/_configs.py +1041 -0
  83. nbxtensor/ops/_cost.py +231 -0
  84. nbxtensor/ops/abs.py +17 -0
  85. nbxtensor/ops/adaptive_avg_pool2d.py +161 -0
  86. nbxtensor/ops/add.py +96 -0
  87. nbxtensor/ops/addcdiv.py +29 -0
  88. nbxtensor/ops/addcmul.py +29 -0
  89. nbxtensor/ops/addmv_op.py +64 -0
  90. nbxtensor/ops/addr.py +68 -0
  91. nbxtensor/ops/all_reduce.py +83 -0
  92. nbxtensor/ops/amax.py +40 -0
  93. nbxtensor/ops/any_reduce.py +83 -0
  94. nbxtensor/ops/arange_op.py +27 -0
  95. nbxtensor/ops/argmax.py +107 -0
  96. nbxtensor/ops/argmin.py +93 -0
  97. nbxtensor/ops/atan2.py +71 -0
  98. nbxtensor/ops/attention_wrappers.py +1648 -0
  99. nbxtensor/ops/autotune_bucket.py +137 -0
  100. nbxtensor/ops/autotune_cache.py +430 -0
  101. nbxtensor/ops/autotune_certified.py +1262 -0
  102. nbxtensor/ops/autotune_refusals.py +380 -0
  103. nbxtensor/ops/autotune_settings.py +58 -0
  104. nbxtensor/ops/avg_pool2d.py +73 -0
  105. nbxtensor/ops/baddbmm_op.py +132 -0
  106. nbxtensor/ops/batch_norm.py +163 -0
  107. nbxtensor/ops/binary_strided.py +196 -0
  108. nbxtensor/ops/bitwise_and.py +26 -0
  109. nbxtensor/ops/bitwise_left_shift.py +47 -0
  110. nbxtensor/ops/bitwise_not.py +24 -0
  111. nbxtensor/ops/bitwise_or.py +26 -0
  112. nbxtensor/ops/bitwise_right_shift.py +47 -0
  113. nbxtensor/ops/bucketize.py +37 -0
  114. nbxtensor/ops/cat_op.py +87 -0
  115. nbxtensor/ops/celu.py +20 -0
  116. nbxtensor/ops/clamp.py +24 -0
  117. nbxtensor/ops/clamp_min.py +22 -0
  118. nbxtensor/ops/conv2d.py +265 -0
  119. nbxtensor/ops/conv2d_m8n8k4.py +165 -0
  120. nbxtensor/ops/conv_depthwise2d.py +154 -0
  121. nbxtensor/ops/conv_transpose2d.py +148 -0
  122. nbxtensor/ops/conv_wrappers.py +1482 -0
  123. nbxtensor/ops/copy.py +18 -0
  124. nbxtensor/ops/copy_op.py +39 -0
  125. nbxtensor/ops/cos.py +17 -0
  126. nbxtensor/ops/count_nonzero.py +64 -0
  127. nbxtensor/ops/cross_entropy.py +67 -0
  128. nbxtensor/ops/cummax.py +109 -0
  129. nbxtensor/ops/cummin.py +105 -0
  130. nbxtensor/ops/cumsum.py +244 -0
  131. nbxtensor/ops/decode_attn_vec.py +162 -0
  132. nbxtensor/ops/depthwise_conv2d.py +132 -0
  133. nbxtensor/ops/dequant_gemv.py +190 -0
  134. nbxtensor/ops/dft.py +67 -0
  135. nbxtensor/ops/dispatch.py +1228 -0
  136. nbxtensor/ops/div.py +75 -0
  137. nbxtensor/ops/dot_op.py +67 -0
  138. nbxtensor/ops/dropout.py +23 -0
  139. nbxtensor/ops/dtype_convert.py +42 -0
  140. nbxtensor/ops/elementwise_launch.py +81 -0
  141. nbxtensor/ops/elementwise_wrappers.py +2315 -0
  142. nbxtensor/ops/elu.py +20 -0
  143. nbxtensor/ops/embedding.py +69 -0
  144. nbxtensor/ops/eq.py +32 -0
  145. nbxtensor/ops/erf.py +18 -0
  146. nbxtensor/ops/exp.py +17 -0
  147. nbxtensor/ops/exp2.py +18 -0
  148. nbxtensor/ops/fft_op.py +125 -0
  149. nbxtensor/ops/fill_op.py +20 -0
  150. nbxtensor/ops/flash_attention.py +307 -0
  151. nbxtensor/ops/flash_attention_m8n8k4.py +384 -0
  152. nbxtensor/ops/flash_decode.py +78 -0
  153. nbxtensor/ops/flip_op.py +60 -0
  154. nbxtensor/ops/floor.py +90 -0
  155. nbxtensor/ops/full_op.py +24 -0
  156. nbxtensor/ops/fused_moe.py +417 -0
  157. nbxtensor/ops/fused_moe_m8n8k4.py +99 -0
  158. nbxtensor/ops/fused_upsample_conv.py +413 -0
  159. nbxtensor/ops/gather_op.py +52 -0
  160. nbxtensor/ops/ge.py +32 -0
  161. nbxtensor/ops/gelu.py +31 -0
  162. nbxtensor/ops/gemv_vec.py +80 -0
  163. nbxtensor/ops/glu.py +43 -0
  164. nbxtensor/ops/grid_sampler.py +145 -0
  165. nbxtensor/ops/group_norm_tiled.py +67 -0
  166. nbxtensor/ops/groupnorm.py +123 -0
  167. nbxtensor/ops/gt.py +32 -0
  168. nbxtensor/ops/hardsigmoid.py +18 -0
  169. nbxtensor/ops/hardswish.py +19 -0
  170. nbxtensor/ops/im2col.py +57 -0
  171. nbxtensor/ops/index_add.py +95 -0
  172. nbxtensor/ops/index_put_op.py +92 -0
  173. nbxtensor/ops/index_select.py +121 -0
  174. nbxtensor/ops/index_wrappers.py +770 -0
  175. nbxtensor/ops/isfinite.py +20 -0
  176. nbxtensor/ops/isinf.py +20 -0
  177. nbxtensor/ops/isnan.py +18 -0
  178. nbxtensor/ops/launch_keys.py +1054 -0
  179. nbxtensor/ops/launch_observer.py +54 -0
  180. nbxtensor/ops/layernorm.py +71 -0
  181. nbxtensor/ops/le.py +35 -0
  182. nbxtensor/ops/leaky_relu.py +19 -0
  183. nbxtensor/ops/lerp.py +76 -0
  184. nbxtensor/ops/linalg_wrappers.py +1370 -0
  185. nbxtensor/ops/linspace_op.py +47 -0
  186. nbxtensor/ops/log.py +17 -0
  187. nbxtensor/ops/log_sigmoid.py +23 -0
  188. nbxtensor/ops/logical_and.py +26 -0
  189. nbxtensor/ops/logical_not.py +24 -0
  190. nbxtensor/ops/logical_or.py +26 -0
  191. nbxtensor/ops/logical_xor.py +37 -0
  192. nbxtensor/ops/loss_wrappers.py +282 -0
  193. nbxtensor/ops/lt.py +32 -0
  194. nbxtensor/ops/masked_fill.py +21 -0
  195. nbxtensor/ops/matmul.py +377 -0
  196. nbxtensor/ops/matmul_m8n8k4.py +235 -0
  197. nbxtensor/ops/max_pool2d.py +74 -0
  198. nbxtensor/ops/max_pool3d.py +93 -0
  199. nbxtensor/ops/max_reduce.py +91 -0
  200. nbxtensor/ops/maximum.py +18 -0
  201. nbxtensor/ops/mean.py +40 -0
  202. nbxtensor/ops/min_reduce.py +91 -0
  203. nbxtensor/ops/minimum.py +18 -0
  204. nbxtensor/ops/mish.py +22 -0
  205. nbxtensor/ops/mma_m8n8k4.py +152 -0
  206. nbxtensor/ops/moe_align.py +195 -0
  207. nbxtensor/ops/moe_decode_vec.py +374 -0
  208. nbxtensor/ops/moe_device_residency.py +141 -0
  209. nbxtensor/ops/moe_wrappers.py +345 -0
  210. nbxtensor/ops/mse_loss.py +79 -0
  211. nbxtensor/ops/mul.py +51 -0
  212. nbxtensor/ops/nan_to_num.py +23 -0
  213. nbxtensor/ops/ne.py +32 -0
  214. nbxtensor/ops/neg.py +17 -0
  215. nbxtensor/ops/nllloss.py +124 -0
  216. nbxtensor/ops/nonzero.py +33 -0
  217. nbxtensor/ops/nonzero_op.py +62 -0
  218. nbxtensor/ops/norm_wrappers.py +579 -0
  219. nbxtensor/ops/ones_op.py +20 -0
  220. nbxtensor/ops/oracles/__init__.py +6 -0
  221. nbxtensor/ops/oracles/conv2d_fp64.py +450 -0
  222. nbxtensor/ops/pad_op.py +159 -0
  223. nbxtensor/ops/paged_decode_attn.py +215 -0
  224. nbxtensor/ops/pixel_shuffle.py +144 -0
  225. nbxtensor/ops/pixel_unshuffle.py +72 -0
  226. nbxtensor/ops/pow.py +137 -0
  227. nbxtensor/ops/prod.py +81 -0
  228. nbxtensor/ops/rand_op.py +52 -0
  229. nbxtensor/ops/random_wrappers.py +366 -0
  230. nbxtensor/ops/reciprocal.py +17 -0
  231. nbxtensor/ops/reduction_wrappers.py +845 -0
  232. nbxtensor/ops/relu.py +18 -0
  233. nbxtensor/ops/remainder.py +46 -0
  234. nbxtensor/ops/repeat_interleave.py +48 -0
  235. nbxtensor/ops/repeat_op.py +132 -0
  236. nbxtensor/ops/residual_chain.py +374 -0
  237. nbxtensor/ops/rmsnorm.py +68 -0
  238. nbxtensor/ops/rope.py +142 -0
  239. nbxtensor/ops/rsqrt.py +17 -0
  240. nbxtensor/ops/scaled_softmax.py +96 -0
  241. nbxtensor/ops/scatter_op.py +139 -0
  242. nbxtensor/ops/screen_oracle.py +479 -0
  243. nbxtensor/ops/selu.py +22 -0
  244. nbxtensor/ops/shape_wrappers.py +1032 -0
  245. nbxtensor/ops/sigmoid.py +19 -0
  246. nbxtensor/ops/silu.py +27 -0
  247. nbxtensor/ops/sin.py +17 -0
  248. nbxtensor/ops/softmax.py +169 -0
  249. nbxtensor/ops/softplus.py +27 -0
  250. nbxtensor/ops/sort_op.py +304 -0
  251. nbxtensor/ops/spectral_wrappers.py +481 -0
  252. nbxtensor/ops/sqrt.py +17 -0
  253. nbxtensor/ops/stack_op.py +84 -0
  254. nbxtensor/ops/std.py +113 -0
  255. nbxtensor/ops/strided_copy.py +200 -0
  256. nbxtensor/ops/sub.py +35 -0
  257. nbxtensor/ops/sum.py +40 -0
  258. nbxtensor/ops/tan.py +19 -0
  259. nbxtensor/ops/tanh.py +21 -0
  260. nbxtensor/ops/threshold.py +19 -0
  261. nbxtensor/ops/tiling.yml +91 -0
  262. nbxtensor/ops/tiling_policy.py +43 -0
  263. nbxtensor/ops/tiling_sizes.py +370 -0
  264. nbxtensor/ops/topk.py +267 -0
  265. nbxtensor/ops/trace_op.py +64 -0
  266. nbxtensor/ops/tril.py +64 -0
  267. nbxtensor/ops/triu.py +62 -0
  268. nbxtensor/ops/unfold_op.py +37 -0
  269. nbxtensor/ops/unique_op.py +97 -0
  270. nbxtensor/ops/upsample_bilinear2d.py +106 -0
  271. nbxtensor/ops/upsample_nearest2d.py +52 -0
  272. nbxtensor/ops/upsample_nearest3d.py +61 -0
  273. nbxtensor/ops/var.py +136 -0
  274. nbxtensor/ops/vector_norm.py +216 -0
  275. nbxtensor/ops/weight_norm.py +104 -0
  276. nbxtensor/ops/where.py +39 -0
  277. nbxtensor/ops/wrappers.py +825 -0
  278. nbxtensor/ops/zeros_op.py +20 -0
  279. nbxtensor/quant/__init__.py +1 -0
  280. nbxtensor/quant/quantized_tensor.py +187 -0
  281. nbxtensor/random/__init__.py +1 -0
  282. nbxtensor/random/mt_randn.py +154 -0
  283. nbxtensor/random/rng_pin.py +59 -0
  284. nbxtensor/random/rng_stream.py +118 -0
  285. nbxtensor/random/seeded_draw.py +223 -0
  286. nbxtensor/shape/__init__.py +157 -0
  287. nbxtensor/tensor.py +1867 -0
  288. nbxtensor-0.0.1.dist-info/METADATA +379 -0
  289. nbxtensor-0.0.1.dist-info/RECORD +291 -0
  290. nbxtensor-0.0.1.dist-info/WHEEL +4 -0
  291. nbxtensor-0.0.1.dist-info/licenses/LICENSE +189 -0
@@ -0,0 +1,287 @@
1
+ # Third-party notices — nbxtensor
2
+
3
+ nbxtensor is distributed under the Apache License 2.0 (`LICENSE`). Some of its Triton kernels are derived from, or
4
+ modelled on, the open-source projects below. Each listed file names its source in its header or beside the borrowed
5
+ code, and its own changes are NeuroBrix's. The upstream commit each extraction started from was not recorded at
6
+ extraction time: every source below is declared **unpinned** (its license is the one its repository carries today and
7
+ carried when the code was taken).
8
+
9
+ ## Code derived from third-party projects
10
+
11
+ | project | license | files (under `src/nbxtensor/`) |
12
+ |---|---|---|
13
+ | [FlagOpen/FlagGems](https://github.com/FlagOpen/FlagGems) | Apache-2.0 | `ops/addcdiv.py`, `ops/addcmul.py`, `ops/addmv_op.py`, `ops/addr.py`, `ops/all_reduce.py`, `ops/any_reduce.py`, `ops/arange_op.py`, `ops/argmax.py`, `ops/argmin.py`, `ops/attention_wrappers.py`, `ops/autotune_cache.py`, `ops/avg_pool2d.py`, `ops/baddbmm_op.py`, `ops/batch_norm.py`, `ops/bitwise_and.py`, `ops/bitwise_left_shift.py`, `ops/bitwise_not.py`, `ops/bitwise_or.py`, `ops/bitwise_right_shift.py`, `ops/cat_op.py`, `ops/celu.py`, `ops/conv2d.py`, `ops/copy_op.py`, `ops/count_nonzero.py`, `ops/cummax.py`, `ops/cummin.py`, `ops/cumsum.py`, `ops/dispatch.py`, `ops/dot_op.py`, `ops/elementwise_wrappers.py`, `ops/embedding.py`, `ops/exp2.py`, `ops/fft_op.py`, `ops/flip_op.py`, `ops/gather_op.py`, `ops/gemv_vec.py`, `ops/groupnorm.py`, `ops/index_add.py`, `ops/index_put_op.py`, `ops/index_select.py`, `ops/index_wrappers.py`, `ops/isfinite.py`, `ops/isinf.py`, `ops/isnan.py`, `ops/le.py`, `ops/lerp.py`, `ops/linalg_wrappers.py`, `ops/linspace_op.py`, `ops/log_sigmoid.py`, `ops/logical_and.py`, `ops/logical_not.py`, `ops/logical_or.py`, `ops/logical_xor.py`, `ops/matmul.py`, `ops/max_pool2d.py`, `ops/max_pool3d.py`, `ops/max_reduce.py`, `ops/min_reduce.py`, `ops/mse_loss.py`, `ops/nan_to_num.py`, `ops/nllloss.py`, `ops/nonzero_op.py`, `ops/norm_wrappers.py`, `ops/pad_op.py`, `ops/prod.py`, `ops/reduction_wrappers.py`, `ops/repeat_interleave.py`, `ops/scaled_softmax.py`, `ops/scatter_op.py`, `ops/shape_wrappers.py`, `ops/softplus.py`, `ops/sort_op.py`, `ops/stack_op.py`, `ops/std.py`, `ops/tan.py`, `ops/threshold.py`, `ops/topk.py`, `ops/trace_op.py`, `ops/tril.py`, `ops/triu.py`, `ops/unique_op.py`, `ops/upsample_nearest2d.py`, `ops/var.py`, `ops/vector_norm.py`, `ops/weight_norm.py`, `ops/wrappers.py` |
14
+ | [BobMcDear/attorch](https://github.com/BobMcDear/attorch) | MIT | `ops/_common.py`, `ops/conv2d.py`, `ops/conv_wrappers.py`, `ops/cross_entropy.py`, `ops/glu.py`, `ops/layernorm.py`, `ops/rmsnorm.py`, `ops/softmax.py` |
15
+ | [linkedin/Liger-Kernel](https://github.com/linkedin/Liger-Kernel) | BSD-2-Clause | `ops/rope.py` |
16
+ | [Dao-AILab/flash-attention](https://github.com/Dao-AILab/flash-attention) | BSD-3-Clause | `ops/flash_attention.py` (from the upstream flash_attn_triton.py), `ops/elementwise_wrappers.py` (its wrapper) |
17
+
18
+ FlagGems publishes no NOTICE file; its Apache-2.0 license is reproduced below, and the changes are stated in each
19
+ file's header.
20
+
21
+ ## Projects cited as a reference only (no code copied)
22
+
23
+ | project | license | where | what is taken |
24
+ |---|---|---|---|
25
+ | [NVIDIA/cutlass](https://github.com/NVIDIA/cutlass) | BSD-3-Clause | `ops/mma_m8n8k4.py`, `ops/depthwise_conv2d.py` | the SM70 fragment layout and the depthwise iterator's shape, as documentation |
26
+ | [ModelTC/lightllm](https://github.com/ModelTC/lightllm), [vllm-project/vllm](https://github.com/vllm-project/vllm) | Apache-2.0 | `ops/decode_attn_vec.py`, `ops/moe_decode_vec.py`, `ops/moe_align.py`, `ops/paged_decode_attn.py`, `ops/attention_wrappers.py` | the structure of decode attention and MoE alignment, re-written |
27
+ | [AutoGPTQ](https://github.com/AutoGPTQ/AutoGPTQ) | MIT | `ops/dequant_gemv.py` | the packing convention of the stored weights |
28
+
29
+ ## License texts
30
+
31
+ ### FlagOpen/FlagGems — Apache License 2.0
32
+
33
+ Apache License
34
+ Version 2.0, January 2004
35
+ http://www.apache.org/licenses/
36
+
37
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
38
+
39
+ 1. Definitions.
40
+
41
+ "License" shall mean the terms and conditions for use, reproduction,
42
+ and distribution as defined by Sections 1 through 9 of this document.
43
+
44
+ "Licensor" shall mean the copyright owner or entity authorized by
45
+ the copyright owner that is granting the License.
46
+
47
+ "Legal Entity" shall mean the union of the acting entity and all
48
+ other entities that control, are controlled by, or are under common
49
+ control with that entity. For the purposes of this definition,
50
+ "control" means (i) the power, direct or indirect, to cause the
51
+ direction or management of such entity, whether by contract or
52
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
53
+ outstanding shares, or (iii) beneficial ownership of such entity.
54
+
55
+ "You" (or "Your") shall mean an individual or Legal Entity
56
+ exercising permissions granted by this License.
57
+
58
+ "Source" form shall mean the preferred form for making modifications,
59
+ including but not limited to software source code, documentation
60
+ source, and configuration files.
61
+
62
+ "Object" form shall mean any form resulting from mechanical
63
+ transformation or translation of a Source form, including but
64
+ not limited to compiled object code, generated documentation,
65
+ and conversions to other media types.
66
+
67
+ "Work" shall mean the work of authorship, whether in Source or
68
+ Object form, made available under the License, as indicated by a
69
+ copyright notice that is included in or attached to the work
70
+ (an example is provided in the Appendix below).
71
+
72
+ "Derivative Works" shall mean any work, whether in Source or Object
73
+ form, that is based on (or derived from) the Work and for which the
74
+ editorial revisions, annotations, elaborations, or other modifications
75
+ represent, as a whole, an original work of authorship. For the purposes
76
+ of this License, Derivative Works shall not include works that remain
77
+ separable from, or merely link (or bind by name) to the interfaces of,
78
+ the Work and Derivative Works thereof.
79
+
80
+ "Contribution" shall mean any work of authorship, including
81
+ the original version of the Work and any modifications or additions
82
+ to that Work or Derivative Works thereof, that is intentionally
83
+ submitted to Licensor for inclusion in the Work by the copyright owner
84
+ or by an individual or Legal Entity authorized to submit on behalf of
85
+ the copyright owner. For the purposes of this definition, "submitted"
86
+ means any form of electronic, verbal, or written communication sent
87
+ to the Licensor or its representatives, including but not limited to
88
+ communication on electronic mailing lists, source code control systems,
89
+ and issue tracking systems that are managed by, or on behalf of, the
90
+ Licensor for the purpose of discussing and improving the Work, but
91
+ excluding communication that is conspicuously marked or otherwise
92
+ designated in writing by the copyright owner as "Not a Contribution."
93
+
94
+ "Contributor" shall mean Licensor and any individual or Legal Entity
95
+ on behalf of whom a Contribution has been received by Licensor and
96
+ subsequently incorporated within the Work.
97
+
98
+ 2. Grant of Copyright License. Subject to the terms and conditions of
99
+ this License, each Contributor hereby grants to You a perpetual,
100
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
101
+ copyright license to reproduce, prepare Derivative Works of,
102
+ publicly display, publicly perform, sublicense, and distribute the
103
+ Work and such Derivative Works in Source or Object form.
104
+
105
+ 3. Grant of Patent License. Subject to the terms and conditions of
106
+ this License, each Contributor hereby grants to You a perpetual,
107
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
108
+ (except as stated in this section) patent license to make, have made,
109
+ use, offer to sell, sell, import, and otherwise transfer the Work,
110
+ where such license applies only to those patent claims licensable
111
+ by such Contributor that are necessarily infringed by their
112
+ Contribution(s) alone or by combination of their Contribution(s)
113
+ with the Work to which such Contribution(s) was submitted. If You
114
+ institute patent litigation against any entity (including a
115
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
116
+ or a Contribution incorporated within the Work constitutes direct
117
+ or contributory patent infringement, then any patent licenses
118
+ granted to You under this License for that Work shall terminate
119
+ as of the date such litigation is filed.
120
+
121
+ 4. Redistribution. You may reproduce and distribute copies of the
122
+ Work or Derivative Works thereof in any medium, with or without
123
+ modifications, and in Source or Object form, provided that You
124
+ meet the following conditions:
125
+
126
+ (a) You must give any other recipients of the Work or
127
+ Derivative Works a copy of this License; and
128
+
129
+ (b) You must cause any modified files to carry prominent notices
130
+ stating that You changed the files; and
131
+
132
+ (c) You must retain, in the Source form of any Derivative Works
133
+ that You distribute, all copyright, patent, trademark, and
134
+ attribution notices from the Source form of the Work,
135
+ excluding those notices that do not pertain to any part of
136
+ the Derivative Works; and
137
+
138
+ (d) If the Work includes a "NOTICE" text file as part of its
139
+ distribution, then any Derivative Works that You distribute must
140
+ include a readable copy of the attribution notices contained
141
+ within such NOTICE file, excluding those notices that do not
142
+ pertain to any part of the Derivative Works, in at least one
143
+ of the following places: within a NOTICE text file distributed
144
+ as part of the Derivative Works; within the Source form or
145
+ documentation, if provided along with the Derivative Works; or,
146
+ within a display generated by the Derivative Works, if and
147
+ wherever such third-party notices normally appear. The contents
148
+ of the NOTICE file are for informational purposes only and
149
+ do not modify the License. You may add Your own attribution
150
+ notices within Derivative Works that You distribute, alongside
151
+ or as an addendum to the NOTICE text from the Work, provided
152
+ that such additional attribution notices cannot be construed
153
+ as modifying the License.
154
+
155
+ You may add Your own copyright statement to Your modifications and
156
+ may provide additional or different license terms and conditions
157
+ for use, reproduction, or distribution of Your modifications, or
158
+ for any such Derivative Works as a whole, provided Your use,
159
+ reproduction, and distribution of the Work otherwise complies with
160
+ the conditions stated in this License.
161
+
162
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
163
+ any Contribution intentionally submitted for inclusion in the Work
164
+ by You to the Licensor shall be under the terms and conditions of
165
+ this License, without any additional terms or conditions.
166
+ Notwithstanding the above, nothing herein shall supersede or modify
167
+ the terms of any separate license agreement you may have executed
168
+ with Licensor regarding such Contributions.
169
+
170
+ 6. Trademarks. This License does not grant permission to use the trade
171
+ names, trademarks, service marks, or product names of the Licensor,
172
+ except as required for reasonable and customary use in describing the
173
+ origin of the Work and reproducing the content of the NOTICE file.
174
+
175
+ 7. Disclaimer of Warranty. Unless required by applicable law or
176
+ agreed to in writing, Licensor provides the Work (and each
177
+ Contributor provides its Contributions) on an "AS IS" BASIS,
178
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
179
+ implied, including, without limitation, any warranties or conditions
180
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
181
+ PARTICULAR PURPOSE. You are solely responsible for determining the
182
+ appropriateness of using or redistributing the Work and assume any
183
+ risks associated with Your exercise of permissions under this License.
184
+
185
+ 8. Limitation of Liability. In no event and under no legal theory,
186
+ whether in tort (including negligence), contract, or otherwise,
187
+ unless required by applicable law (such as deliberate and grossly
188
+ negligent acts) or agreed to in writing, shall any Contributor be
189
+ liable to You for damages, including any direct, indirect, special,
190
+ incidental, or consequential damages of any character arising as a
191
+ result of this License or out of the use or inability to use the
192
+ Work (including but not limited to damages for loss of goodwill,
193
+ work stoppage, computer failure or malfunction, or any and all
194
+ other commercial damages or losses), even if such Contributor
195
+ has been advised of the possibility of such damages.
196
+
197
+ 9. Accepting Warranty or Additional Liability. While redistributing
198
+ the Work or Derivative Works thereof, You may choose to offer,
199
+ and charge a fee for, acceptance of support, warranty, indemnity,
200
+ or other liability obligations and/or rights consistent with this
201
+ License. However, in accepting such obligations, You may act only
202
+ on Your own behalf and on Your sole responsibility, not on behalf
203
+ of any other Contributor, and only if You agree to indemnify,
204
+ defend, and hold each Contributor harmless for any liability
205
+ incurred by, or claims asserted against, such Contributor by reason
206
+ of your accepting any such warranty or additional liability.
207
+
208
+ END OF TERMS AND CONDITIONS
209
+
210
+ ### BobMcDear/attorch — MIT
211
+ MIT License
212
+
213
+ Copyright (c) 2023 Borna Ahmadzadeh
214
+
215
+ Permission is hereby granted, free of charge, to any person obtaining a copy
216
+ of this software and associated documentation files (the "Software"), to deal
217
+ in the Software without restriction, including without limitation the rights
218
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
219
+ copies of the Software, and to permit persons to whom the Software is
220
+ furnished to do so, subject to the following conditions:
221
+
222
+ The above copyright notice and this permission notice shall be included in all
223
+ copies or substantial portions of the Software.
224
+
225
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
226
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
227
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
228
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
229
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
230
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
231
+ SOFTWARE.
232
+
233
+ ### linkedin/Liger-Kernel — BSD 2-Clause
234
+ BSD 2-CLAUSE LICENSE
235
+ Copyright 2024 LinkedIn Corporation
236
+ All Rights Reserved.
237
+ Redistribution and use in source and binary forms, with or
238
+ without modification, are permitted provided that the following
239
+ conditions are met:
240
+ 1. Redistributions of source code must retain the above copyright
241
+ notice, this list of conditions and the following disclaimer.
242
+ 2. Redistributions in binary form must reproduce the above
243
+ copyright notice, this list of conditions and the following
244
+ disclaimer in the documentation and/or other materials provided
245
+ with the distribution.
246
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
247
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
248
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
249
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
250
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
251
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
252
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
253
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
254
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
255
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
256
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
257
+
258
+ ### Dao-AILab/flash-attention — BSD 3-Clause
259
+ BSD 3-Clause License
260
+
261
+ Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file.
262
+ All rights reserved.
263
+
264
+ Redistribution and use in source and binary forms, with or without
265
+ modification, are permitted provided that the following conditions are met:
266
+
267
+ * Redistributions of source code must retain the above copyright notice, this
268
+ list of conditions and the following disclaimer.
269
+
270
+ * Redistributions in binary form must reproduce the above copyright notice,
271
+ this list of conditions and the following disclaimer in the documentation
272
+ and/or other materials provided with the distribution.
273
+
274
+ * Neither the name of the copyright holder nor the names of its
275
+ contributors may be used to endorse or promote products derived from
276
+ this software without specific prior written permission.
277
+
278
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
279
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
280
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
281
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
282
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
283
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
284
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
285
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
286
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
287
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
nbxtensor/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """nbxtensor — an inference-first tensor library, torch-free.
2
+
3
+ The tensor library of NeuroBrix, built to stand on its own: dtypes, shapes,
4
+ strides and views, memory that is planned rather than discovered, device
5
+ backends (CUDA, Apple Metal, CPU) and Triton kernels that declare their own
6
+ cost. NeuroBrix's Triton engine is its first client; it imports this package
7
+ and never re-implements what lives here.
8
+
9
+ What is in the library today, area by area, is the README's status table;
10
+ the versions are numbered as `docs/nbxtensor/DESIGN.md` section 7 says (the
11
+ first publication is 0.0.1, each fix after it increments, the Rust rewrite is
12
+ 2.0.0).
13
+ """
14
+
15
+ #: the one version number; `pyproject.toml` states the same (tests/test_version.py)
16
+ __version__ = "0.0.1"
17
+ __all__: list = []
@@ -0,0 +1 @@
1
+ """Backends: detection, the kernel launcher and its contract, the Metal driver, the CPU backend, graph capture."""
@@ -0,0 +1,207 @@
1
+ """What the backend in force can do, as declared or measured: float64, the flash and reduction tiles, pointers loaded
2
+ from memory, device-side asserts. Cut out of tensor.py (M2, 2026-10-29), unchanged."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import Dict, Optional
7
+
8
+ from nbxtensor.backend import runtime as _rt
9
+
10
+
11
+
12
+
13
+ # Whether the backend HONOURS a device-side assert the author explicitly kept
14
+ # with `@triton.jit(debug=True)`. This is not a question about debug builds:
15
+ # `tl.device_assert` reaches the IR at all ONLY when `options.debug` is true
16
+ # (triton/language/semantic.py: `if not self.builder.options.debug: return`),
17
+ # so a `tt.assert` in the IR is by construction one the author demanded.
18
+ #
19
+ # CUDA and ROCm halt the thread at the assert and the next sync raises. The
20
+ # Metal backend COMPUTES the predicate and then discards it — measured
21
+ # 2026-09-10: with debug=True the generated MSL carries `mask_5 = idx < 2`
22
+ # and never reads it. The guard is paid for in registers and not delivered,
23
+ # so a kernel whose only bounds check is that assert performs the very access
24
+ # the assert was there to prevent (`index_put` wrote 8 floats past the end of
25
+ # a 24-float tensor; `embedding` read past the end of the weight).
26
+ #
27
+ # This is a capability, not a vendor test — adding a backend is adding a row.
28
+ _BACKEND_TRAPS_ON_DEVICE_ASSERT = {"cuda": True, "hip": True, "metal": False}
29
+
30
+ # Whether a kernel can load a device ADDRESS out of a tensor and then read
31
+ # through it — the [E] int64 pointer table that lets one launch reach every
32
+ # expert's weights instead of one launch per expert.
33
+ #
34
+ # Measured 2026-09-17 on triton-ext (M4 Pro, Toolchain 27) with a control that
35
+ # differs by the one variable — whether the address arrives AS a pointer or as
36
+ # an integer to be converted — and in BOTH Triton spellings, because they are
37
+ # different constructs and cannot be assumed to share a fate:
38
+ #
39
+ # control (pointer as a pointer) : nonzero 256/256 correct
40
+ # subject (.to(pointer_type)) : nonzero 0/256 ALL ZEROS
41
+ # subject (tl.cast bitcast=True) : nonzero 0/256 ALL ZEROS
42
+ #
43
+ # The second subject is the spelling our own kernels use, which is what makes
44
+ # the engine's zeros attributable to this and not to us. Nothing is raised: the
45
+ # kernel compiles, launches and writes zeros. The reproducer contains none of
46
+ # our code (`repro_ext_pointer_from_table.py`) and is drafted for upstream.
47
+ #
48
+ # It is recorded HERE because the engine cannot catch what is never raised: a
49
+ # band that cannot address its experts has to refuse by name, and a refusal
50
+ # needs a fact to stand on. This is a capability, not a vendor test — adding a
51
+ # backend is adding a row.
52
+ _BACKEND_LOADS_POINTERS_FROM_MEMORY = {"cuda": True, "hip": True, "metal": False}
53
+ # Whether the backend's kernels can read and write a float64 (or complex128) element. Metal
54
+ # has no double: its lowering NARROWS f64 to float in silence (`triton/metal_backend.py`,
55
+ # `TRITON_METAL_FP64_UNAVAILABLE`), so a kernel over a float64 buffer reads eight-byte
56
+ # elements as four-byte ones. Measured 2026-09-28: `from_numpy(float64).to(bf16)` on the
57
+ # M4 Pro gave 1 139 of 143 360 bits right and 3 255 non-finite values (the Sana 4K sincos
58
+ # positional embedding, every off-trace size). A census says "not this time"; the door in
59
+ # `NBXTensor.to` says "never": a cast from or to such a dtype is refused BY NAME there.
60
+ #
61
+ # The answer is the CALLER's to give (`set_backend_has_fp64`), not a table here: it is a fact
62
+ # about the hardware the caller declares once (NeuroBrix: the vendor profile's
63
+ # `precision.kernels_carry_fp64.triton`, bound by `kernels.wrappers.set_hardware_profile`).
64
+ # Unset, a question that needs it is refused — a float64 element is never assumed readable.
65
+ _BACKEND_HAS_FP64 = None
66
+
67
+
68
+ def set_backend_has_fp64(value: bool) -> None:
69
+ """Declare whether this process's backend kernels compute float64 / complex128 elements."""
70
+ global _BACKEND_HAS_FP64
71
+ if not isinstance(value, bool):
72
+ raise TypeError(f"set_backend_has_fp64 takes a bool, got {value!r}")
73
+ _BACKEND_HAS_FP64 = value
74
+
75
+
76
+ def backend_has_fp64() -> bool:
77
+ """Whether the backend's kernels handle float64 elements, as declared by
78
+ `set_backend_has_fp64`; refused while undeclared."""
79
+ if _BACKEND_HAS_FP64 is None:
80
+ raise RuntimeError(
81
+ f"ZERO FALLBACK: whether the '{_rt.gpu_backend()}' backend's kernels compute "
82
+ f"float64 was never declared (`set_backend_has_fp64`); it is the hardware's fact, "
83
+ f"never assumed")
84
+ return _BACKEND_HAS_FP64
85
+
86
+
87
+ # The smallest `tl.dot` tile dimension a backend's attention lowering handles
88
+ # CORRECTLY. On cuda/hip the floor is the TensorCore minimum, 16, and a decode
89
+ # step at seqlen_q=1 uses it. Metal's generic attention lowering silently
90
+ # mis-computes below 32 -- rows past the first become garbage, for any
91
+ # head_dim -- and refuses rather than emit it; its tiled template does take a
92
+ # smaller tile, but only for a kernel its detector resolves completely at
93
+ # head_dim 64, which is not every kernel.
94
+ #
95
+ # Sixteen wastes half a Q tile at seqlen_q=1. A refusal wastes the model.
96
+ #
97
+ # This is a capability, not a vendor test — adding a backend is adding a row.
98
+ _BACKEND_FA_MIN_TILE = {"cuda": 16, "hip": 16, "metal": 32}
99
+
100
+
101
+ def fa_min_tile() -> int:
102
+ """The smallest attention tile dimension this backend computes correctly."""
103
+ return _backend_capability(
104
+ _BACKEND_FA_MIN_TILE, "_BACKEND_FA_MIN_TILE",
105
+ "the smallest attention tile dimension it computes correctly")
106
+
107
+
108
+ # The largest 2-D reduction tile (product of block dims) a backend's lowering
109
+ # stages correctly. The generic Metal lowering stages one element per thread,
110
+ # so a tile above the 1024-thread threadgroup has lanes with nothing to hold
111
+ # their part -- it refuses rather than reduce part of the tile. cuda/hip lower
112
+ # a 2-D reduce differently and take the tile the reduction kernels were tuned
113
+ # for (BLOCK_M*BLOCK_N = 8192); their entry is that tuned size so min() is the
114
+ # identity and nothing moves there.
115
+ #
116
+ # A capability, not a vendor test -- adding a backend is adding a row.
117
+ _BACKEND_REDUCE_TILE_MAX = {"cuda": 1 << 20, "hip": 1 << 20, "metal": 1024}
118
+
119
+
120
+ def reduce_tile_max() -> int:
121
+ """The largest 2-D reduction tile this backend stages correctly."""
122
+ return _backend_capability(
123
+ _BACKEND_REDUCE_TILE_MAX, "_BACKEND_REDUCE_TILE_MAX",
124
+ "the largest 2-D reduction tile it stages correctly")
125
+
126
+
127
+ # Whether a backend's lowering stages a 2-D reduce ONE ELEMENT PER THREAD along the reduced extent: then that extent of
128
+ # a tile cannot exceed the threads of the program that reduces it (its warps x the backend's threads per warp). Metal,
129
+ # measured 2026-09-07: the GEMV's 8 x 256 at 4 warps and the mv's 64 x 256 at 4 warps refused, naming the numbers
130
+ # (tests/unit/config/test_apple_profiles_agree_with_the_device.py held those tiles in the profile until the certifier
131
+ # chose them; the rule is the kernels' prune now, `ops/_configs.prune_gemv_vec` / `prune_addmv`). cuda/hip reduce many
132
+ # elements per thread in registers.
133
+ _BACKEND_REDUCE_PER_THREAD = {"cuda": False, "hip": False, "metal": True}
134
+ _BACKEND_THREADS_PER_WARP = {"cuda": 32, "hip": 64, "metal": 32}
135
+
136
+
137
+ def reduced_extent_max(num_warps: int) -> Optional[int]:
138
+ """The largest reduced extent a program of `num_warps` stages on this backend, or None when its lowering bounds
139
+ none (it reduces many elements per thread)."""
140
+ if not _backend_capability(_BACKEND_REDUCE_PER_THREAD, "_BACKEND_REDUCE_PER_THREAD",
141
+ "whether it stages a 2-D reduce one element per thread"):
142
+ return None
143
+ return int(num_warps) * int(_backend_capability(_BACKEND_THREADS_PER_WARP, "_BACKEND_THREADS_PER_WARP",
144
+ "its threads per warp"))
145
+
146
+
147
+ def _backend_capability(table, name: str, what: str) -> bool:
148
+ """One row of one capability table, or a refusal naming both."""
149
+ backend = _rt.gpu_backend()
150
+ value = table.get(backend)
151
+ if value is None:
152
+ raise RuntimeError(
153
+ f"ZERO FALLBACK: backend {backend!r} does not say {what} "
154
+ f"({name}, rows: {sorted(table)}). Adding a backend is adding a "
155
+ f"row, not guessing.")
156
+ return value
157
+
158
+
159
+ #: What the ENGINE declared about a backend, above the tables: a capability that is a
160
+ #: property of the launcher it selected, not of the silicon, is the engine's to state.
161
+ #: nbx_tensor is a library with a boundary (R33, the ratchet cell
162
+ #: test_the_boundary_does_not_widen) and asks the engine nothing; the engine tells it,
163
+ #: through `declare_backend_capability`, before a kernel is launched.
164
+ _DECLARED_CAPABILITIES: Dict[str, Dict[str, bool]] = {}
165
+
166
+
167
+ def declare_backend_capability(backend: str, **capabilities: bool) -> None:
168
+ """The engine states a capability of the launcher it selected for `backend`
169
+ (`loads_pointers_from_memory=True` for Metal's triton_ext, proven through its pinned
170
+ scope). Read by the capability questions below, above the static tables."""
171
+ for name, value in capabilities.items():
172
+ if not isinstance(value, bool):
173
+ raise TypeError(f"a backend capability is a bool, not {value!r} ({backend}.{name})")
174
+ _DECLARED_CAPABILITIES.setdefault(backend, {}).update(capabilities)
175
+
176
+
177
+ def backend_loads_pointers_from_memory() -> bool:
178
+ """True where a kernel may dereference an address it LOADED from a tensor.
179
+
180
+ On Metal the answer is a property of the LAUNCHER, not the silicon: a
181
+ loaded address reads correctly exactly when the driver keeps the captured
182
+ address alive across launches, which `triton_ext` does through
183
+ `pinned_addresses` (proven against an fp64 oracle,
184
+ test_the_moe_table_reads_through_a_pinned_scope, 2026-09-20; the archived
185
+ fork had no such scope and the same load returned zeros with nothing
186
+ raised — the measured defect this gate refuses). So the metal row is a
187
+ SELECTION read, not a constant — and the selection is the engine's, so the
188
+ engine DECLARES it here on every Metal run's entry
189
+ (`triton/metal_backend.ensure_triton_metal_or_raise`); undeclared, the table's
190
+ False stands until a launcher proves its own lifetime contract. Until
191
+ 2026-09-26 this function imported the engine's metal_backend to ask, which
192
+ widened the library's boundary (the ratchet cell went red on main).
193
+ """
194
+ backend = _rt.gpu_backend()
195
+ declared = _DECLARED_CAPABILITIES.get(backend, {}).get("loads_pointers_from_memory")
196
+ if declared is not None:
197
+ return declared
198
+ return _backend_capability(
199
+ _BACKEND_LOADS_POINTERS_FROM_MEMORY, "_BACKEND_LOADS_POINTERS_FROM_MEMORY",
200
+ "whether a kernel can read through a pointer loaded from memory")
201
+
202
+
203
+ def backend_traps_on_device_assert() -> bool:
204
+ """True where `tl.device_assert` actually stops the kernel."""
205
+ return _backend_capability(
206
+ _BACKEND_TRAPS_ON_DEVICE_ASSERT, "_BACKEND_TRAPS_ON_DEVICE_ASSERT",
207
+ "whether it honours a device-side assert")
@@ -0,0 +1 @@
1
+ """The CPU backend's host machinery: the thread pool every core is used through (`pool`)."""
@@ -0,0 +1,102 @@
1
+ """The thread count of the BLAS numpy calls, from the pool's size, with no oversubscription (DESIGN rule 14).
2
+
3
+ numpy's matrix products run in the BLAS it was built with, which has its own threads. Two rules:
4
+
5
+ - outside the pool, the BLAS uses as many threads as the pool would (`pool.threads()`: the machine's compute cores);
6
+ - inside `parallel_for`, each piece already runs on a pool thread, so the BLAS a piece calls runs single-threaded:
7
+ pool threads x BLAS threads would put more threads on the cores than there are cores.
8
+
9
+ Through the BLAS's own symbols, found in the process (no new dependency):
10
+
11
+ - Apple's Accelerate (`BLASSetThreading`, macOS 15+): a setting PER THREAD, multi-threaded (Accelerate chooses how
12
+ many) or single-threaded — the pool's threads are set single-threaded when they start;
13
+ - OpenBLAS (numpy's wheels on Linux; `openblas_set_num_threads` / `scipy_openblas_set_num_threads64_`): a count for
14
+ the PROCESS — set to 1 while `parallel_for` runs, the pool's size otherwise.
15
+
16
+ A BLAS none of these names is refused by name when its threads are set: the count is never assumed.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import ctypes
21
+ import functools
22
+ import platform
23
+ from pathlib import Path
24
+ from typing import Optional, Tuple
25
+
26
+ __all__ = ["blas", "set_blas_threads", "blas_threads_of_this_thread"]
27
+
28
+ _ACCELERATE = "/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib"
29
+ _OPENBLAS_SET = ("scipy_openblas_set_num_threads64_", "scipy_openblas_set_num_threads", "openblas_set_num_threads64_",
30
+ "openblas_set_num_threads")
31
+ _OPENBLAS_GET = ("scipy_openblas_get_num_threads64_", "scipy_openblas_get_num_threads", "openblas_get_num_threads64_",
32
+ "openblas_get_num_threads")
33
+
34
+
35
+ def _loaded_openblas() -> Optional[str]:
36
+ maps = Path("/proc/self/maps")
37
+ if not maps.is_file():
38
+ return None
39
+ for line in maps.read_text().splitlines():
40
+ path = line.split()[-1] if line.split() else ""
41
+ if "openblas" in Path(path).name.lower():
42
+ return path
43
+ return None
44
+
45
+
46
+ @functools.lru_cache(maxsize=1)
47
+ def blas() -> Tuple[str, object]:
48
+ """(kind, library) of the BLAS numpy runs in this process: ("accelerate", libBLAS) or ("openblas", the loaded
49
+ library); refused by name otherwise."""
50
+ import numpy # noqa: F401 — numpy loads its BLAS; the library is the one already in the process
51
+ if platform.system() == "Darwin":
52
+ # a system library lives in the dyld shared cache, not as a file on disk: it is loaded, never stat-ed
53
+ try:
54
+ lib = ctypes.CDLL(_ACCELERATE)
55
+ except OSError:
56
+ lib = None
57
+ if lib is not None and hasattr(lib, "BLASSetThreading") and hasattr(lib, "BLASGetThreading"):
58
+ return "accelerate", lib
59
+ path = _loaded_openblas()
60
+ if path is not None:
61
+ lib = ctypes.CDLL(path)
62
+ if any(hasattr(lib, s) for s in _OPENBLAS_SET):
63
+ return "openblas", lib
64
+ raise RuntimeError("ZERO FALLBACK: nbxtensor knows no thread control of this process's BLAS (Accelerate's "
65
+ "BLASSetThreading, OpenBLAS's openblas_set_num_threads); its threads are not set")
66
+
67
+
68
+ def _symbol(lib, names):
69
+ for name in names:
70
+ if hasattr(lib, name):
71
+ return getattr(lib, name)
72
+ raise RuntimeError(f"ZERO FALLBACK: the BLAS exports none of {names}")
73
+
74
+
75
+ def set_blas_threads(n: int) -> None:
76
+ """The BLAS threads: `n` (OpenBLAS: for the process); Accelerate takes no count: 1 is single-threaded for the
77
+ calling thread, more is Accelerate's own multi-threading for it."""
78
+ if not isinstance(n, int) or n < 1:
79
+ raise ValueError(f"set_blas_threads: {n!r} — one thread or more")
80
+ kind, lib = blas()
81
+ if kind == "accelerate":
82
+ fn = lib.BLASSetThreading
83
+ fn.argtypes, fn.restype = [ctypes.c_uint], ctypes.c_int
84
+ if fn(0 if n > 1 else 1) != 0: # BLAS_THREADING_MULTI_THREADED = 0, _SINGLE_THREADED = 1
85
+ raise RuntimeError("Accelerate refused BLASSetThreading on this platform (macOS 15 or later needed)")
86
+ return
87
+ fn = _symbol(lib, _OPENBLAS_SET)
88
+ fn.argtypes, fn.restype = [ctypes.c_int], None
89
+ fn(n)
90
+
91
+
92
+ def blas_threads_of_this_thread() -> Optional[int]:
93
+ """1 when the BLAS runs single-threaded for the calling thread, else its count (OpenBLAS), or None for
94
+ Accelerate's own multi-threading (it states no count)."""
95
+ kind, lib = blas()
96
+ if kind == "accelerate":
97
+ fn = lib.BLASGetThreading
98
+ fn.restype = ctypes.c_uint
99
+ return 1 if fn() == 1 else None
100
+ fn = _symbol(lib, _OPENBLAS_GET)
101
+ fn.restype = ctypes.c_int
102
+ return int(fn())