Consolidate GDN and KDA LeapQuant kernels in one repository
Browse filesUnmodified accepted kernel sources, grouped APIs, original workloads and benchmarks, pinned dependencies, licensing, validation results and provenance.
- LICENSE.txt +202 -0
- NOTICE +7 -0
- README.md +75 -0
- build/torch-cuda/LICENSE.txt +202 -0
- build/torch-cuda/__init__.py +6 -0
- build/torch-cuda/_gdn.py +1858 -0
- build/torch-cuda/_kda.py +1242 -0
- build/torch-cuda/metadata.json +25 -0
- gdn/README.md +161 -0
- gdn/baseline.py +732 -0
- gdn/benchmark.py +149 -0
- gdn/benchmark_results.json +48 -0
- gdn/definition.json +164 -0
- gdn/provenance.json +26 -0
- gdn/validate.py +126 -0
- gdn/validation_results.json +112 -0
- gdn/workloads.jsonl +6 -0
- kda/README.md +163 -0
- kda/baseline.py +789 -0
- kda/benchmark.py +160 -0
- kda/benchmark_results.json +48 -0
- kda/definition.json +174 -0
- kda/provenance.json +26 -0
- kda/validate.py +126 -0
- kda/validation_results.json +112 -0
- kda/workloads.jsonl +6 -0
- requirements.txt +7 -0
LICENSE.txt
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
NOTICE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
LeapQuant checkpoint flush kernels
|
| 2 |
+
|
| 3 |
+
Kernel sources and upstream request files retain their Apache-2.0 SPDX notices.
|
| 4 |
+
Request definition, workloads, reference baseline and benchmark originate from
|
| 5 |
+
https://github.com/NVlabs/kda/pull/10 at commit 48f02e6ba0e98a1841ab6f0a2d99a90b2de1a326.
|
| 6 |
+
The CuTe DSL implementation was evolved with Kernel Design Agents using
|
| 7 |
+
GPT 6.1 and Claude Opus 5.5 in a 48-hour experiment.
|
README.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: kernels
|
| 3 |
+
license: apache-2.0
|
| 4 |
+
tags:
|
| 5 |
+
- cuda
|
| 6 |
+
- cute-dsl
|
| 7 |
+
- cutlass
|
| 8 |
+
- blackwell
|
| 9 |
+
- b300
|
| 10 |
+
- leapquant
|
| 11 |
+
- linear-attention
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# LeapQuant checkpoint flush kernels
|
| 15 |
+
|
| 16 |
+
One repository containing the Gated DeltaNet (GDN) and Kimi Delta Attention
|
| 17 |
+
(KDA) window-boundary state re-quantization kernels. Both use CuTe DSL and
|
| 18 |
+
Blackwell tensor cores. The kernel algorithms and bytes are unchanged from
|
| 19 |
+
their final accepted optimization submissions.
|
| 20 |
+
|
| 21 |
+
| Component | Documentation and benchmark | Final paired speedup, all six batches | Batches >=128 |
|
| 22 |
+
|---|---|---:|---:|
|
| 23 |
+
| Gated DeltaNet | [gdn/](gdn/README.md) | 2.551x | 2.813x |
|
| 24 |
+
| Kimi Delta Attention | [kda/](kda/README.md) | 2.999x | 3.128x |
|
| 25 |
+
|
| 26 |
+
These are B300 deployment-kernel measurements against the request's TileLang
|
| 27 |
+
baseline, from the 2026-10-24 paired evaluations. They do not measure a complete
|
| 28 |
+
model or the allocation/packing overhead of the functional interface. Both
|
| 29 |
+
implementations passed the original six workloads and deployment validation;
|
| 30 |
+
the component directories retain the reports and exact source hashes.
|
| 31 |
+
|
| 32 |
+
## Install and load
|
| 33 |
+
|
| 34 |
+
Tested on NVIDIA B300 (compute capability 10.3), Python 3.12,
|
| 35 |
+
PyTorch 2.12.1+cu130 and nvidia-cutlass-dsl[cu13] 4.6.0. Other architectures
|
| 36 |
+
are not advertised. See each component README for shapes and input contracts.
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
python -m pip install torch==2.12.1 --index-url https://download.pytorch.org/whl/cu130
|
| 40 |
+
python -m pip install "nvidia-cutlass-dsl[cu13]==4.6.0" cuda-bindings==13.3.1 kernels==0.17.2 huggingface-hub==2.2.0
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
```python
|
| 44 |
+
from kernels import get_kernel
|
| 45 |
+
|
| 46 |
+
op = get_kernel("humanfia-lab/kernels", version=1, trust_remote_code=True)
|
| 47 |
+
gdn = op.gdn # run(...), Pool(...), flush_inplace(...)
|
| 48 |
+
kda = op.kda # run(...), Pool(...), flush_inplace(...)
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
The `main` and `v1` branches both contain the complete release. `v1` is the
|
| 52 |
+
version loaded above. The runtime sources are `build/torch-cuda/_gdn.py` and
|
| 53 |
+
`build/torch-cuda/_kda.py`; metadata, the public import wrapper and the runtime
|
| 54 |
+
license are alongside them. Each component directory contains its README,
|
| 55 |
+
original workload, benchmark, baseline and reference definition, plus validation
|
| 56 |
+
and provenance. Dependency pins and Apache-2.0 licensing are shared at the root.
|
| 57 |
+
|
| 58 |
+
## Reproduce
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
hf download humanfia-lab/kernels --repo-type kernel --revision v1 --local-dir leapquant-kernels
|
| 62 |
+
cd leapquant-kernels
|
| 63 |
+
python -m pip install -r requirements.txt
|
| 64 |
+
cd gdn
|
| 65 |
+
python benchmark.py --impl ../build/torch-cuda/_gdn.py
|
| 66 |
+
python validate.py
|
| 67 |
+
cd ../kda
|
| 68 |
+
python benchmark.py --impl ../build/torch-cuda/_kda.py
|
| 69 |
+
python validate.py
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
Run `python benchmark.py` in either component directory for the original
|
| 73 |
+
TileLang baseline (requires the pinned TileLang and nvcc on PATH). Construct and
|
| 74 |
+
warm the caller-owned pool before CUDA graph capture. The flush operates only on
|
| 75 |
+
heads whose counter equals 16; the counter remains at 16 for the decode step.
|
build/torch-cuda/LICENSE.txt
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
build/torch-cuda/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
"""LeapQuant checkpoint flush kernels, grouped by attention variant."""
|
| 3 |
+
from . import _gdn as gdn
|
| 4 |
+
from . import _kda as kda
|
| 5 |
+
|
| 6 |
+
__all__ = ["gdn", "kda"]
|
build/torch-cuda/_gdn.py
ADDED
|
@@ -0,0 +1,1858 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
"""CuTe DSL LeapQuant GDN window flush for SM100/SM103 (tcgen05 design).
|
| 3 |
+
|
| 4 |
+
One persistent CTA per SM: a TMA producer warp and four consumer groups of four warps. The producer heads a
|
| 5 |
+
warpgroup of its own (three idle warps) that gives registers to the consumers with setmaxnreg (32 / 112).
|
| 6 |
+
Each group flushes one (slot, head) at a time:
|
| 7 |
+
* TMA brings the checkpoint (int8 codes 128B-swizzled, scales, factors), the update buffer
|
| 8 |
+
and its weights into a 32 KB stage; the stage is released as soon as the last product has read it.
|
| 9 |
+
The small inputs are issued first on the stage barrier and the 16 KB code tile on its own barrier,
|
| 10 |
+
so a group starts a program on the small inputs and waits for the codes only before dequantizing.
|
| 11 |
+
* The state S (fp32, scaled by a per-head power of two 2^sig) is built in tensor memory: one tf32
|
| 12 |
+
MMA writes the scale product 2^8 (p s_v[v] / 127) s_k[k], the dequantization multiplies it by the
|
| 13 |
+
codes, and the rank-16 update (bf16 hi/lo) and the old rank-4 part (tf32 hi/lo) are accumulated by
|
| 14 |
+
tcgen05.mma. Codes become floats as fp16 pairs 2^s (1024 + c + 128) (one PRMT per two codes) converted
|
| 15 |
+
by add.rn.f32.f16 (FHADD, FMA pipe) with -1152 2^s, s = sig - 8: 2^s c exactly, so the ALU pipe only
|
| 16 |
+
sees the byte permutes; a program with s outside the fp16 range [-24, 4] first rescales the scale
|
| 17 |
+
product in TMEM by an exact power of two. Other format conversions also run on the FMA pipe.
|
| 18 |
+
* An fp16 copy of S in shared memory feeds the three subspace-iteration products on the
|
| 19 |
+
tensor cores (as K-major A for S@q and MN-major A for S^T@q); an eight-column projection uses TMEM
|
| 20 |
+
columns 112-119 while their original fp32 state values stay in registers. Q operands carry fp16
|
| 21 |
+
high/low parts. CholeskyQR2 uses FP32x2 mul/FMA for independent factor entries on larger launches
|
| 22 |
+
and the original scalar factorization on smaller launches. It runs on all four warps (one row per thread); its second pass drops
|
| 23 |
+
numerically dependent columns so the result stays orthonormal.
|
| 24 |
+
* E = S - q^T u is formed in place in tensor memory (tf32 MMA with the stored fp16 factors);
|
| 25 |
+
column scales, row scales and int8 codes are computed from fp32 E; code tiles are staged in the
|
| 26 |
+
group's operand buffers and written by per-warp TMA stores.
|
| 27 |
+
* The group's leader warp issues every MMA sequence (also those of the rare precision path) from inline PTX
|
| 28 |
+
(mma8_f16 / mma_list): shared-memory descriptors are (address >> 4) | constant, plus one 64-bit add per K
|
| 29 |
+
step, followed by the commit. Each operand handoff first synchronizes all four writer warps, then the
|
| 30 |
+
leader fences its acquired generic shared-memory view into the async proxy before issuing the MMA.
|
| 31 |
+
GPU-side due selection: the producer scans (idx, fill counter) and skips slot 0.
|
| 32 |
+
At 16 or more heads per SM, the initial scan lets CTAs with no due heads skip tensor-memory allocation,
|
| 33 |
+
consumer setup and empty-stage handoffs. Consumer warp zero checks the first candidate alongside the producer;
|
| 34 |
+
a due seed allocates tensor memory before the initial barrier. Otherwise allocation overlaps q0 setup after
|
| 35 |
+
the scan, and empty CTAs allocate nothing. The deallocating warp reloads the immutable shared due mask at exit
|
| 36 |
+
so it need not stay in a register across the persistent loop. Smaller calls use the original setup. Both paths
|
| 37 |
+
are compiled by Pool construction; flush selects using only the public launch size and SM count.
|
| 38 |
+
Idle warps of the producer warpgroup prefetch the four TMA descriptors, q0 and (one slice per CTA) the fill-counter array
|
| 39 |
+
into L2 at entry, so the first copies of each SM do not wait for a cold descriptor fetch and the due check's
|
| 40 |
+
dependent counter loads hit L2.
|
| 41 |
+
"""
|
| 42 |
+
import torch
|
| 43 |
+
import cutlass
|
| 44 |
+
import cutlass.cute as cute
|
| 45 |
+
from cutlass import Float16, BFloat16, Float32, Int8, Int32, Uint32, Uint64, Int64, Boolean
|
| 46 |
+
from cutlass.cute.runtime import make_ptr
|
| 47 |
+
from cutlass.cutlass_dsl import dsl_user_op, T
|
| 48 |
+
from cutlass._mlir.dialects import llvm
|
| 49 |
+
from cutlass.utils import SmemAllocator
|
| 50 |
+
from cutlass.cute.nvgpu import tcgen05
|
| 51 |
+
import cuda.bindings.driver as cuda
|
| 52 |
+
|
| 53 |
+
HV, K, V, L, R = 32, 128, 128, 16, 4
|
| 54 |
+
SS, OFF = 33 * V * K, 12288 # pool geometry in fp32 words
|
| 55 |
+
NG = 4 # consumer groups
|
| 56 |
+
NSTAGE = 4
|
| 57 |
+
assert NSTAGE == NG # each group owns one stage
|
| 58 |
+
PROD_WARP = 4 * NG
|
| 59 |
+
NTHREADS = 32 * (4 * NG + 4) # the producer warp heads a warpgroup of its own (setmaxnreg)
|
| 60 |
+
REG_CONS, REG_PROD = 112, 32 # per SMSP: 4 * 32 * 112 + 32 * 32 < 16384 registers (allocation needs slack)
|
| 61 |
+
STAGE = 32768
|
| 62 |
+
ST_CODES, ST_SC, ST_KB, ST_UB, ST_W, ST_P = 0, 16384, 19456, 23552, 27648, 27712
|
| 63 |
+
LOAD_BYTES = 3072 + 4096 + 4096 + 64 + 16 # small inputs (the 16 KB code tile has its own barrier)
|
| 64 |
+
EPS = 1e-12
|
| 65 |
+
TAU2 = 1e-3 # second CholeskyQR pass: drop columns with pivot <= TAU2 * |column|^2
|
| 66 |
+
TAU1 = 0.03 # first pass: all relative pivots above TAU1 -> kappa^2 <~ 4 / TAU1 ~ 133:
|
| 67 |
+
# the first pass is orthonormal to ~1e-5 << fp16 rounding: no second pass
|
| 68 |
+
MAGIC_RND = 12582912.0 # 1.5 * 2^23: add, then the low byte is the rounded integer
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# ----------------------------------------------------------------------------------------------
|
| 72 |
+
# inline PTX helpers
|
| 73 |
+
# ----------------------------------------------------------------------------------------------
|
| 74 |
+
def _asm(ret_types, args, text, cons, side=True, loc=None, ip=None):
|
| 75 |
+
if not ret_types:
|
| 76 |
+
llvm.inline_asm(None, args, text, cons, has_side_effects=side, is_align_stack=False,
|
| 77 |
+
asm_dialect=llvm.AsmDialect.AD_ATT, loc=loc, ip=ip)
|
| 78 |
+
return []
|
| 79 |
+
rt = ret_types[0] if len(ret_types) == 1 else llvm.StructType.get_literal(ret_types)
|
| 80 |
+
out = llvm.inline_asm(rt, args, text, cons, has_side_effects=side, is_align_stack=False,
|
| 81 |
+
asm_dialect=llvm.AsmDialect.AD_ATT, loc=loc, ip=ip)
|
| 82 |
+
if len(ret_types) == 1:
|
| 83 |
+
return [out]
|
| 84 |
+
return [llvm.extractvalue(ret_types[i], out, [i], loc=loc, ip=ip) for i in range(len(ret_types))]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _u(x, loc, ip):
|
| 88 |
+
return Uint32(x).ir_value(loc=loc, ip=ip)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _f(x, loc, ip):
|
| 92 |
+
return Float32(x).ir_value(loc=loc, ip=ip)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@dsl_user_op
|
| 96 |
+
def tmem_alloc(dst_smem_addr, ncols: cutlass.Constexpr, *, loc=None, ip=None):
|
| 97 |
+
_asm([], [_u(dst_smem_addr, loc, ip)],
|
| 98 |
+
f"tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [$0], {ncols};", "r", loc=loc, ip=ip)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@dsl_user_op
|
| 102 |
+
def tmem_free(addr, ncols: cutlass.Constexpr, *, loc=None, ip=None):
|
| 103 |
+
_asm([], [_u(addr, loc, ip)],
|
| 104 |
+
f"tcgen05.dealloc.cta_group::1.sync.aligned.b32 $0, {ncols};", "r", loc=loc, ip=ip)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@dsl_user_op
|
| 108 |
+
def tmem_relinquish(*, loc=None, ip=None):
|
| 109 |
+
_asm([], [], "tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;", "", loc=loc, ip=ip)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@dsl_user_op
|
| 113 |
+
def tmem_ld8(addr, *, loc=None, ip=None):
|
| 114 |
+
r = _asm([T.f32()] * 8, [_u(addr, loc, ip)],
|
| 115 |
+
"tcgen05.ld.sync.aligned.32x32b.x8.b32 {$0,$1,$2,$3,$4,$5,$6,$7}, [$8]; tcgen05.wait::ld.sync.aligned;",
|
| 116 |
+
",".join(["=f"] * 8 + ["r"]), loc=loc, ip=ip)
|
| 117 |
+
return [Float32(x) for x in r]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@dsl_user_op
|
| 121 |
+
def tmem_ld4(addr, *, loc=None, ip=None):
|
| 122 |
+
r = _asm([T.f32()] * 4, [_u(addr, loc, ip)],
|
| 123 |
+
"tcgen05.ld.sync.aligned.32x32b.x4.b32 {$0,$1,$2,$3}, [$4]; tcgen05.wait::ld.sync.aligned;",
|
| 124 |
+
",".join(["=f"] * 4 + ["r"]), loc=loc, ip=ip)
|
| 125 |
+
return [Float32(x) for x in r]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@dsl_user_op
|
| 129 |
+
def tmem_ld16_nw(addr, *, loc=None, ip=None):
|
| 130 |
+
"""Issue a 32x32b.x16 TMEM load (no wait); pass the result through tmem_wait_ld before use."""
|
| 131 |
+
r = _asm([T.f32()] * 16, [_u(addr, loc, ip)],
|
| 132 |
+
"tcgen05.ld.sync.aligned.32x32b.x16.b32 {" + ",".join("$" + str(i) for i in range(16)) + "}, [$16];",
|
| 133 |
+
",".join(["=f"] * 16 + ["r"]), loc=loc, ip=ip)
|
| 134 |
+
return [Float32(x) for x in r]
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@dsl_user_op
|
| 138 |
+
def tmem_ld32_nw(addr, *, loc=None, ip=None):
|
| 139 |
+
"""Issue a 32x32b.x32 TMEM load (no wait); pass the result through tmem_wait_ld before use."""
|
| 140 |
+
r = _asm([T.f32()] * 32, [_u(addr, loc, ip)],
|
| 141 |
+
"tcgen05.ld.sync.aligned.32x32b.x32.b32 {" + ",".join("$" + str(i) for i in range(32)) + "}, [$32];",
|
| 142 |
+
",".join(["=f"] * 32 + ["r"]), loc=loc, ip=ip)
|
| 143 |
+
return [Float32(x) for x in r]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@dsl_user_op
|
| 147 |
+
def tmem_ld16x256x4_nw(addr, *, loc=None, ip=None):
|
| 148 |
+
r = _asm([T.f32()] * 16, [_u(addr, loc, ip)],
|
| 149 |
+
"tcgen05.ld.sync.aligned.16x256b.x4.b32 {" + ",".join("$" + str(i) for i in range(16)) + "}, [$16];",
|
| 150 |
+
",".join(["=f"] * 16 + ["r"]), loc=loc, ip=ip)
|
| 151 |
+
return [Float32(x) for x in r]
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@dsl_user_op
|
| 155 |
+
def tmem_wait_ld(vals, *, loc=None, ip=None):
|
| 156 |
+
"""tcgen05.wait::ld with a register dependency on the loaded values (uses cannot move above the wait)."""
|
| 157 |
+
n = len(vals)
|
| 158 |
+
r = _asm([T.f32()] * n, [_f(x, loc, ip) for x in vals], "tcgen05.wait::ld.sync.aligned;",
|
| 159 |
+
",".join(["=f"] * n + [str(i) for i in range(n)]), loc=loc, ip=ip)
|
| 160 |
+
return [Float32(x) for x in r]
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@dsl_user_op
|
| 164 |
+
def tmem_st16_nw(addr, vals, *, loc=None, ip=None):
|
| 165 |
+
_asm([], [_u(addr, loc, ip)] + [_f(x, loc, ip) for x in vals],
|
| 166 |
+
"tcgen05.st.sync.aligned.32x32b.x16.b32 [$0], {" + ",".join("$" + str(i + 1) for i in range(16)) + "};",
|
| 167 |
+
",".join(["r"] + ["f"] * 16), loc=loc, ip=ip)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
@dsl_user_op
|
| 171 |
+
def tmem_st32_nw(addr, vals, *, loc=None, ip=None):
|
| 172 |
+
_asm([], [_u(addr, loc, ip)] + [_f(x, loc, ip) for x in vals],
|
| 173 |
+
"tcgen05.st.sync.aligned.32x32b.x32.b32 [$0], {" + ",".join("$" + str(i + 1) for i in range(32)) + "};",
|
| 174 |
+
",".join(["r"] + ["f"] * 32), loc=loc, ip=ip)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@dsl_user_op
|
| 178 |
+
def tmem_st8_nw(addr, vals, *, loc=None, ip=None):
|
| 179 |
+
_asm([], [_u(addr, loc, ip)] + [_f(x, loc, ip) for x in vals],
|
| 180 |
+
"tcgen05.st.sync.aligned.32x32b.x8.b32 [$0], {" + ",".join("$" + str(i + 1) for i in range(8)) + "};",
|
| 181 |
+
",".join(["r"] + ["f"] * 8), loc=loc, ip=ip)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@dsl_user_op
|
| 185 |
+
def mma8_f16(d, a4, b4, mbar, aconst: cutlass.Constexpr, aoffs: cutlass.Constexpr, bconst: cutlass.Constexpr,
|
| 186 |
+
boffs: cutlass.Constexpr, idesc: cutlass.Constexpr, acc_first: cutlass.Constexpr = False, *, loc=None, ip=None):
|
| 187 |
+
"""Eight tcgen05.mma kind::f16 steps (first one overwrites D) with smem descriptors (addr >> 4) | const plus
|
| 188 |
+
per-step offsets, then a commit to mbar; issue from one elected thread."""
|
| 189 |
+
txt = ["{", ".reg .b64 a0, b0, ad, bd;", ".reg .b32 id;", ".reg .pred pf, pt;",
|
| 190 |
+
"setp.ne.b32 pf, $1, $1;", "setp.eq.b32 pt, $1, $1;", f"mov.b32 id, {idesc};",
|
| 191 |
+
"cvt.u64.u32 a0, $1;", f"or.b64 a0, a0, {aconst};", "cvt.u64.u32 b0, $2;", f"or.b64 b0, b0, {bconst};",
|
| 192 |
+
f"tcgen05.mma.cta_group::1.kind::f16 [$0], a0, b0, id, {'pt' if acc_first else 'pf'};"]
|
| 193 |
+
for kb in range(1, 8):
|
| 194 |
+
txt += [f"add.s64 ad, a0, {aoffs[kb]};", f"add.s64 bd, b0, {boffs[kb]};",
|
| 195 |
+
"tcgen05.mma.cta_group::1.kind::f16 [$0], ad, bd, id, pt;"]
|
| 196 |
+
txt += ["tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [$3];", "}"]
|
| 197 |
+
_asm([], [_u(d, loc, ip), _u(a4, loc, ip), _u(b4, loc, ip), _u(mbar, loc, ip)], " ".join(txt), "r,r,r,r",
|
| 198 |
+
loc=loc, ip=ip)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@dsl_user_op
|
| 202 |
+
def mma_list(d, mbar, bases, steps, *, loc=None, ip=None):
|
| 203 |
+
"""tcgen05.mma steps (kind, a base index, a const, b base index, b const, idesc, accumulate) with smem descriptors
|
| 204 |
+
(bases[i] | const) (bases are addr >> 4), then a commit to mbar; issue from one elected thread."""
|
| 205 |
+
n = len(bases)
|
| 206 |
+
txt = ["{", ".reg .b64 ad, bd;", ".reg .b32 id;", ".reg .pred pf, pt;"] + [f".reg .b64 x{i};" for i in range(n)]
|
| 207 |
+
txt += ["setp.ne.b32 pf, $0, $0;", "setp.eq.b32 pt, $0, $0;"] + [f"cvt.u64.u32 x{i}, ${2 + i};" for i in range(n)]
|
| 208 |
+
for kind, ai, ac, bi, bc, idesc, acc in steps:
|
| 209 |
+
txt += [f"or.b64 ad, x{ai}, {ac};", f"or.b64 bd, x{bi}, {bc};", f"mov.b32 id, {idesc};",
|
| 210 |
+
f"tcgen05.mma.cta_group::1.kind::{kind} [$0], ad, bd, id, {'pt' if acc else 'pf'};"]
|
| 211 |
+
txt += ["tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [$1];", "}"]
|
| 212 |
+
_asm([], [_u(d, loc, ip), _u(mbar, loc, ip)] + [_u(b, loc, ip) for b in bases], " ".join(txt),
|
| 213 |
+
",".join(["r"] * (2 + n)), loc=loc, ip=ip)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@dsl_user_op
|
| 217 |
+
def tmem_wait_st(*, loc=None, ip=None):
|
| 218 |
+
_asm([], [], "tcgen05.wait::st.sync.aligned;", "", loc=loc, ip=ip)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@dsl_user_op
|
| 222 |
+
def tc_before(*, loc=None, ip=None):
|
| 223 |
+
_asm([], [], "tcgen05.fence::before_thread_sync;", "", loc=loc, ip=ip)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@dsl_user_op
|
| 227 |
+
def tc_after(*, loc=None, ip=None):
|
| 228 |
+
_asm([], [], "tcgen05.fence::after_thread_sync;", "", loc=loc, ip=ip)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
@dsl_user_op
|
| 232 |
+
def fence_async_smem(*, loc=None, ip=None):
|
| 233 |
+
_asm([], [], "fence.proxy.async.shared::cta;", "", loc=loc, ip=ip)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@dsl_user_op
|
| 237 |
+
def sts128(addr, a, b, c, d, *, loc=None, ip=None):
|
| 238 |
+
_asm([], [_u(addr, loc, ip)] + [_u(x, loc, ip) for x in (a, b, c, d)],
|
| 239 |
+
"st.shared.v4.b32 [$0], {$1, $2, $3, $4};", "r,r,r,r,r", loc=loc, ip=ip)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@dsl_user_op
|
| 243 |
+
def sts64(addr, a, b, *, loc=None, ip=None):
|
| 244 |
+
_asm([], [_u(addr, loc, ip), _u(a, loc, ip), _u(b, loc, ip)], "st.shared.v2.b32 [$0], {$1, $2};", "r,r,r", loc=loc, ip=ip)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@dsl_user_op
|
| 248 |
+
def sts32(addr, a, *, loc=None, ip=None):
|
| 249 |
+
_asm([], [_u(addr, loc, ip), _u(a, loc, ip)], "st.shared.b32 [$0], $1;", "r,r", loc=loc, ip=ip)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@dsl_user_op
|
| 253 |
+
def lds128(addr, *, loc=None, ip=None):
|
| 254 |
+
r = _asm([T.i32()] * 4, [_u(addr, loc, ip)], "ld.shared.v4.b32 {$0, $1, $2, $3}, [$4];", "=r,=r,=r,=r,r", loc=loc, ip=ip)
|
| 255 |
+
return [Uint32(x) for x in r]
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@dsl_user_op
|
| 259 |
+
def lds128f(addr, *, loc=None, ip=None):
|
| 260 |
+
r = _asm([T.f32()] * 4, [_u(addr, loc, ip)], "ld.shared.v4.f32 {$0, $1, $2, $3}, [$4];", "=f,=f,=f,=f,r", loc=loc, ip=ip)
|
| 261 |
+
return [Float32(x) for x in r]
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
@dsl_user_op
|
| 265 |
+
def lds32(addr, *, loc=None, ip=None):
|
| 266 |
+
r = _asm([T.i32()], [_u(addr, loc, ip)], "ld.shared.b32 $0, [$1];", "=r,r", loc=loc, ip=ip)
|
| 267 |
+
return Uint32(r[0])
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
@dsl_user_op
|
| 271 |
+
def lds32f(addr, *, loc=None, ip=None):
|
| 272 |
+
r = _asm([T.f32()], [_u(addr, loc, ip)], "ld.shared.f32 $0, [$1];", "=f,r", loc=loc, ip=ip)
|
| 273 |
+
return Float32(r[0])
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
@dsl_user_op
|
| 277 |
+
def lds16(addr, *, loc=None, ip=None):
|
| 278 |
+
r = _asm([T.i32()], [_u(addr, loc, ip)], "{ .reg .b16 h; ld.shared.b16 h, [$1]; cvt.u32.u16 $0, h; }", "=r,r", loc=loc, ip=ip)
|
| 279 |
+
return Uint32(r[0])
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
@dsl_user_op
|
| 283 |
+
def stg32(addr, a, *, loc=None, ip=None):
|
| 284 |
+
_asm([], [Int64(addr).ir_value(loc=loc, ip=ip), _u(a, loc, ip)], "st.global.b32 [$0], $1;", "l,r", loc=loc, ip=ip)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@dsl_user_op
|
| 288 |
+
def stg16(addr, a, *, loc=None, ip=None):
|
| 289 |
+
_asm([], [Int64(addr).ir_value(loc=loc, ip=ip), _u(a, loc, ip)],
|
| 290 |
+
"{ .reg .b16 h; cvt.u16.u32 h, $1; st.global.b16 [$0], h; }", "l,r", loc=loc, ip=ip)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
@dsl_user_op
|
| 294 |
+
def stg16_hi(addr, a, *, loc=None, ip=None):
|
| 295 |
+
_asm([], [Int64(addr).ir_value(loc=loc, ip=ip), _u(a, loc, ip)],
|
| 296 |
+
"{ .reg .b16 l, h; mov.b32 {l, h}, $1; st.global.b16 [$0], h; }", "l,r", loc=loc, ip=ip)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
@dsl_user_op
|
| 300 |
+
def ldg32(addr, *, loc=None, ip=None):
|
| 301 |
+
r = _asm([T.i32()], [Int64(addr).ir_value(loc=loc, ip=ip)], "ld.global.b32 $0, [$1];", "=r,l", loc=loc, ip=ip)
|
| 302 |
+
return Uint32(r[0])
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
@dsl_user_op
|
| 306 |
+
def ldg32_volatile(addr, *, loc=None, ip=None):
|
| 307 |
+
r = _asm([T.i32()], [Int64(addr).ir_value(loc=loc, ip=ip)], "ld.global.relaxed.gpu.b32 $0, [$1];", "=r,l", loc=loc, ip=ip)
|
| 308 |
+
return Uint32(r[0])
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
@dsl_user_op
|
| 312 |
+
def f2h2(a, b, *, loc=None, ip=None):
|
| 313 |
+
"""fp16x2 with a in the low half."""
|
| 314 |
+
r = _asm([T.i32()], [_f(a, loc, ip), _f(b, loc, ip)], "cvt.rn.f16x2.f32 $0, $2, $1;", "=r,f,f", side=False, loc=loc, ip=ip)
|
| 315 |
+
return Uint32(r[0])
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@dsl_user_op
|
| 319 |
+
def f2bf2(a, b, *, loc=None, ip=None):
|
| 320 |
+
r = _asm([T.i32()], [_f(a, loc, ip), _f(b, loc, ip)], "cvt.rn.bf16x2.f32 $0, $2, $1;", "=r,f,f", side=False, loc=loc, ip=ip)
|
| 321 |
+
return Uint32(r[0])
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
@dsl_user_op
|
| 325 |
+
def h2f2(x, *, loc=None, ip=None):
|
| 326 |
+
r = _asm([T.f32(), T.f32()], [_u(x, loc, ip)],
|
| 327 |
+
"{ .reg .b16 lo, hi; mov.b32 {lo, hi}, $2; add.rn.f32.f16 $0, lo, 0f80000000; add.rn.f32.f16 $1, hi, 0f80000000; }", "=f,=f,r",
|
| 328 |
+
side=False, loc=loc, ip=ip)
|
| 329 |
+
return Float32(r[0]), Float32(r[1])
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
@dsl_user_op
|
| 333 |
+
def h2f(x, *, loc=None, ip=None):
|
| 334 |
+
r = _asm([T.f32()], [_u(x, loc, ip)], "{ .reg .b16 lo; cvt.u16.u32 lo, $1; add.rn.f32.f16 $0, lo, 0f80000000; }", "=f,r",
|
| 335 |
+
side=False, loc=loc, ip=ip)
|
| 336 |
+
return Float32(r[0])
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@dsl_user_op
|
| 340 |
+
def f2h(a, *, loc=None, ip=None):
|
| 341 |
+
r = _asm([T.i32()], [_f(a, loc, ip)], "{ .reg .b16 h; cvt.rn.f16.f32 h, $1; cvt.u32.u16 $0, h; }", "=r,f",
|
| 342 |
+
side=False, loc=loc, ip=ip)
|
| 343 |
+
return Uint32(r[0])
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
@dsl_user_op
|
| 347 |
+
def f2tf32(a, *, loc=None, ip=None):
|
| 348 |
+
r = _asm([T.f32()], [_f(a, loc, ip)], "{ .reg .b32 t; cvt.rna.tf32.f32 t, $1; mov.b32 $0, t; }", "=f,f",
|
| 349 |
+
side=False, loc=loc, ip=ip)
|
| 350 |
+
return Float32(r[0])
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
@dsl_user_op
|
| 354 |
+
def fmul2(a0, a1, b0, b1, *, loc=None, ip=None):
|
| 355 |
+
r = _asm([T.f32(), T.f32()], [_f(x, loc, ip) for x in (a0, a1, b0, b1)],
|
| 356 |
+
"{ .reg .b64 x, y, z; mov.b64 x, {$2, $3}; mov.b64 y, {$4, $5}; mul.rn.f32x2 z, x, y; mov.b64 {$0, $1}, z; }",
|
| 357 |
+
"=f,=f,f,f,f,f", side=False, loc=loc, ip=ip)
|
| 358 |
+
return Float32(r[0]), Float32(r[1])
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
@dsl_user_op
|
| 362 |
+
def ffma2(a0, a1, b0, b1, c0, c1, *, loc=None, ip=None):
|
| 363 |
+
r = _asm([T.f32(), T.f32()], [_f(x, loc, ip) for x in (a0, a1, b0, b1, c0, c1)],
|
| 364 |
+
"{ .reg .b64 x, y, z, w; mov.b64 x, {$2, $3}; mov.b64 y, {$4, $5}; mov.b64 z, {$6, $7}; fma.rn.f32x2 w, x, y, z; mov.b64 {$0, $1}, w; }",
|
| 365 |
+
"=f,=f,f,f,f,f,f,f", side=False, loc=loc, ip=ip)
|
| 366 |
+
return Float32(r[0]), Float32(r[1])
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
@dsl_user_op
|
| 370 |
+
def fsub2(a0, a1, b0, b1, *, loc=None, ip=None):
|
| 371 |
+
r = _asm([T.f32(), T.f32()], [_f(x, loc, ip) for x in (a0, a1, b0, b1)],
|
| 372 |
+
"{ .reg .b64 x, y, z; mov.b64 x, {$2, $3}; mov.b64 y, {$4, $5}; sub.rn.f32x2 z, x, y; mov.b64 {$0, $1}, z; }",
|
| 373 |
+
"=f,=f,f,f,f,f", side=False, loc=loc, ip=ip)
|
| 374 |
+
return Float32(r[0]), Float32(r[1])
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@dsl_user_op
|
| 378 |
+
def fadd2(a0, a1, b0, b1, *, loc=None, ip=None):
|
| 379 |
+
r = _asm([T.f32(), T.f32()], [_f(x, loc, ip) for x in (a0, a1, b0, b1)],
|
| 380 |
+
"{ .reg .b64 x, y, z; mov.b64 x, {$2, $3}; mov.b64 y, {$4, $5}; add.rn.f32x2 z, x, y; mov.b64 {$0, $1}, z; }",
|
| 381 |
+
"=f,=f,f,f,f,f", side=False, loc=loc, ip=ip)
|
| 382 |
+
return Float32(r[0]), Float32(r[1])
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
@dsl_user_op
|
| 386 |
+
def hadd2(a, b, *, loc=None, ip=None):
|
| 387 |
+
r = _asm([T.i32()], [_u(a, loc, ip), _u(b, loc, ip)], "add.rn.f16x2 $0, $1, $2;", "=r,r,r", side=False, loc=loc, ip=ip)
|
| 388 |
+
return Uint32(r[0])
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
@dsl_user_op
|
| 392 |
+
def fhadd2(h, c, *, loc=None, ip=None):
|
| 393 |
+
"""(f32(h.lo) + c, f32(h.hi) + c) for an f16x2 register h (two FHADD)."""
|
| 394 |
+
r = _asm([T.f32(), T.f32()], [_u(h, loc, ip), _f(c, loc, ip)],
|
| 395 |
+
"{ .reg .b16 lo, hi; mov.b32 {lo, hi}, $2; add.rn.f32.f16 $0, lo, $3; add.rn.f32.f16 $1, hi, $3; }",
|
| 396 |
+
"=f,=f,r,f", side=False, loc=loc, ip=ip)
|
| 397 |
+
return Float32(r[0]), Float32(r[1])
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
@dsl_user_op
|
| 401 |
+
def bf2f2(x, *, loc=None, ip=None):
|
| 402 |
+
"""bf16x2 -> two fp32 (exact), FHADD.BF16 with -0.0."""
|
| 403 |
+
r = _asm([T.f32(), T.f32()], [_u(x, loc, ip)],
|
| 404 |
+
"{ .reg .b16 lo, hi; mov.b32 {lo, hi}, $2; add.rn.f32.bf16 $0, lo, 0f80000000; add.rn.f32.bf16 $1, hi, 0f80000000; }",
|
| 405 |
+
"=f,=f,r", side=False, loc=loc, ip=ip)
|
| 406 |
+
return Float32(r[0]), Float32(r[1])
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@dsl_user_op
|
| 410 |
+
def bfsub2(h, a, b, *, loc=None, ip=None):
|
| 411 |
+
"""(f32(h.lo) - a, f32(h.hi) - b) for a bf16x2 register h (exact when h holds truncations of a, b)."""
|
| 412 |
+
r = _asm([T.f32(), T.f32()], [_u(h, loc, ip), _f(a, loc, ip), _f(b, loc, ip)],
|
| 413 |
+
"{ .reg .b16 lo, hi; mov.b32 {lo, hi}, $2; sub.rn.f32.bf16 $0, lo, $3; sub.rn.f32.bf16 $1, hi, $4; }",
|
| 414 |
+
"=f,=f,r,f,f", side=False, loc=loc, ip=ip)
|
| 415 |
+
return Float32(r[0]), Float32(r[1])
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
@dsl_user_op
|
| 419 |
+
def maxabs3(m, a, b, *, loc=None, ip=None):
|
| 420 |
+
r = _asm([T.f32()], [_f(m, loc, ip), _f(a, loc, ip), _f(b, loc, ip)],
|
| 421 |
+
"{ .reg .f32 x, y; abs.f32 x, $2; abs.f32 y, $3; max.f32 $0, $1, x, y; }", "=f,f,f,f",
|
| 422 |
+
side=False, loc=loc, ip=ip)
|
| 423 |
+
return Float32(r[0])
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
@dsl_user_op
|
| 427 |
+
def bmaxabs2(a, b, *, loc=None, ip=None):
|
| 428 |
+
"""bf16x2 lanes: max(|a|, |b|) (sign bits = xor of the signs; mask them off)."""
|
| 429 |
+
r = _asm([T.i32()], [_u(a, loc, ip), _u(b, loc, ip)], "max.xorsign.abs.bf16x2 $0, $1, $2;", "=r,r,r",
|
| 430 |
+
side=False, loc=loc, ip=ip)
|
| 431 |
+
return Uint32(r[0])
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
@dsl_user_op
|
| 435 |
+
def prmt(a, b, sel, *, loc=None, ip=None):
|
| 436 |
+
r = _asm([T.i32()], [_u(a, loc, ip), _u(b, loc, ip), _u(sel, loc, ip)], "prmt.b32 $0, $1, $2, $3;", "=r,r,r,r",
|
| 437 |
+
side=False, loc=loc, ip=ip)
|
| 438 |
+
return Uint32(r[0])
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
@dsl_user_op
|
| 442 |
+
def redux_max(x, *, loc=None, ip=None):
|
| 443 |
+
r = _asm([T.i32()], [_u(x, loc, ip)], "redux.sync.max.u32 $0, $1, 0xffffffff;", "=r,r", side=False, loc=loc, ip=ip)
|
| 444 |
+
return Uint32(r[0])
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
@dsl_user_op
|
| 448 |
+
def shfl_bfly(x, m: cutlass.Constexpr, *, loc=None, ip=None):
|
| 449 |
+
r = _asm([T.f32()], [_f(x, loc, ip)], f"shfl.sync.bfly.b32 $0, $1, {m}, 0x1f, 0xffffffff;", "=f,f",
|
| 450 |
+
side=False, loc=loc, ip=ip)
|
| 451 |
+
return Float32(r[0])
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
@dsl_user_op
|
| 455 |
+
def shfl_idx(x, src, *, loc=None, ip=None):
|
| 456 |
+
r = _asm([T.f32()], [_f(x, loc, ip), Int32(src).ir_value(loc=loc, ip=ip)],
|
| 457 |
+
"shfl.sync.idx.b32 $0, $1, $2, 0x1f, 0xffffffff;", "=f,f,r", side=False, loc=loc, ip=ip)
|
| 458 |
+
return Float32(r[0])
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
@dsl_user_op
|
| 462 |
+
def rsqrt_approx(x, *, loc=None, ip=None):
|
| 463 |
+
r = _asm([T.f32()], [_f(x, loc, ip)], "rsqrt.approx.ftz.f32 $0, $1;", "=f,f", side=False, loc=loc, ip=ip)
|
| 464 |
+
return Float32(r[0])
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
@dsl_user_op
|
| 468 |
+
def rcp_approx(x, *, loc=None, ip=None):
|
| 469 |
+
r = _asm([T.f32()], [_f(x, loc, ip)], "rcp.approx.ftz.f32 $0, $1;", "=f,f", side=False, loc=loc, ip=ip)
|
| 470 |
+
return Float32(r[0])
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
@dsl_user_op
|
| 474 |
+
def rcp_rn(x, *, loc=None, ip=None):
|
| 475 |
+
r = _asm([T.f32()], [_f(x, loc, ip)], "rcp.rn.f32 $0, $1;", "=f,f", side=False, loc=loc, ip=ip)
|
| 476 |
+
return Float32(r[0])
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
@dsl_user_op
|
| 480 |
+
def nanosleep_ns(t: cutlass.Constexpr, *, loc=None, ip=None):
|
| 481 |
+
_asm([], [], f"nanosleep.u32 {t};", "", loc=loc, ip=ip)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
@dsl_user_op
|
| 485 |
+
def exp2_int(e, *, loc=None, ip=None):
|
| 486 |
+
"""2^e as fp32 for integer e in [-126, 127]."""
|
| 487 |
+
v = (Int32(e) + Int32(127)).to(Uint32) << Uint32(23)
|
| 488 |
+
return v.bitcast(Float32)
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
@dsl_user_op
|
| 492 |
+
def tma_load_4d(dst, tmap, c0, c1, c2, c3, mbar, *, loc=None, ip=None):
|
| 493 |
+
_asm([], [_u(dst, loc, ip), Int64(tmap).ir_value(loc=loc, ip=ip)] + [Int32(c).ir_value(loc=loc, ip=ip) for c in (c0, c1, c2, c3)] + [_u(mbar, loc, ip)],
|
| 494 |
+
"cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes [$0], [$1, {$2, $3, $4, $5}], [$6];",
|
| 495 |
+
"r,l,r,r,r,r,r", loc=loc, ip=ip)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
@dsl_user_op
|
| 499 |
+
def tma_load_3d(dst, tmap, c0, c1, c2, mbar, *, loc=None, ip=None):
|
| 500 |
+
_asm([], [_u(dst, loc, ip), Int64(tmap).ir_value(loc=loc, ip=ip)] + [Int32(c).ir_value(loc=loc, ip=ip) for c in (c0, c1, c2)] + [_u(mbar, loc, ip)],
|
| 501 |
+
"cp.async.bulk.tensor.3d.shared::cluster.global.tile.mbarrier::complete_tx::bytes [$0], [$1, {$2, $3, $4}], [$5];",
|
| 502 |
+
"r,l,r,r,r,r", loc=loc, ip=ip)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
@dsl_user_op
|
| 506 |
+
def bulk_load(dst, src, nbytes, mbar, *, loc=None, ip=None):
|
| 507 |
+
_asm([], [_u(dst, loc, ip), Int64(src).ir_value(loc=loc, ip=ip), _u(nbytes, loc, ip), _u(mbar, loc, ip)],
|
| 508 |
+
"cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [$0], [$1], $2, [$3];",
|
| 509 |
+
"r,l,r,r", loc=loc, ip=ip)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
@dsl_user_op
|
| 513 |
+
def tma_store_4d(tmap, c0, c1, c2, c3, src, *, loc=None, ip=None):
|
| 514 |
+
_asm([], [Int64(tmap).ir_value(loc=loc, ip=ip)] + [Int32(c).ir_value(loc=loc, ip=ip) for c in (c0, c1, c2, c3)] + [_u(src, loc, ip)],
|
| 515 |
+
"cp.async.bulk.tensor.4d.global.shared::cta.tile.bulk_group [$0, {$1, $2, $3, $4}], [$5];",
|
| 516 |
+
"l,r,r,r,r,r", loc=loc, ip=ip)
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
@dsl_user_op
|
| 520 |
+
def prefetch_l2_bulk(addr, nbytes, *, loc=None, ip=None):
|
| 521 |
+
_asm([], [Int64(addr).ir_value(loc=loc, ip=ip), _u(nbytes, loc, ip)], "cp.async.bulk.prefetch.L2.global [$0], $1;", "l,r",
|
| 522 |
+
loc=loc, ip=ip)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
@dsl_user_op
|
| 526 |
+
def prefetch_tmap(addr, *, loc=None, ip=None):
|
| 527 |
+
_asm([], [Int64(addr).ir_value(loc=loc, ip=ip)], "prefetch.tensormap [$0];", "l", loc=loc, ip=ip)
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
@dsl_user_op
|
| 531 |
+
def bulk_commit(*, loc=None, ip=None):
|
| 532 |
+
_asm([], [], "cp.async.bulk.commit_group;", "", loc=loc, ip=ip)
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
@dsl_user_op
|
| 536 |
+
def bulk_wait_read0(*, loc=None, ip=None):
|
| 537 |
+
_asm([], [], "cp.async.bulk.wait_group.read 0;", "", loc=loc, ip=ip)
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
@dsl_user_op
|
| 541 |
+
def bulk_wait0(*, loc=None, ip=None):
|
| 542 |
+
_asm([], [], "cp.async.bulk.wait_group 0;", "", loc=loc, ip=ip)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
@dsl_user_op
|
| 546 |
+
def mbar_init(addr, count: cutlass.Constexpr, *, loc=None, ip=None):
|
| 547 |
+
_asm([], [_u(addr, loc, ip)], f"mbarrier.init.shared::cta.b64 [$0], {count};", "r", loc=loc, ip=ip)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
@dsl_user_op
|
| 551 |
+
def mbar_arrive(addr, *, loc=None, ip=None):
|
| 552 |
+
_asm([], [_u(addr, loc, ip)], "mbarrier.arrive.release.cta.shared::cta.b64 _, [$0];", "r", loc=loc, ip=ip)
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
@dsl_user_op
|
| 556 |
+
def mbar_arrive_tx(addr, nbytes: cutlass.Constexpr, *, loc=None, ip=None):
|
| 557 |
+
_asm([], [_u(addr, loc, ip)], f"mbarrier.arrive.expect_tx.release.cta.shared::cta.b64 _, [$0], {nbytes};", "r", loc=loc, ip=ip)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
@dsl_user_op
|
| 561 |
+
def mbar_wait(addr, parity, *, loc=None, ip=None):
|
| 562 |
+
_asm([], [_u(addr, loc, ip), _u(parity, loc, ip)],
|
| 563 |
+
"{ .reg .pred P; WAIT_${:uid}: mbarrier.try_wait.parity.acquire.cta.shared::cta.b64 P, [$0], $1; @!P bra WAIT_${:uid}; }",
|
| 564 |
+
"r,r", loc=loc, ip=ip)
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
@dsl_user_op
|
| 568 |
+
def named_bar(bid, nthreads: cutlass.Constexpr, *, loc=None, ip=None):
|
| 569 |
+
_asm([], [_u(bid, loc, ip)], f"bar.sync $0, {nthreads};", "r", loc=loc, ip=ip)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
# ----------------------------------------------------------------------------------------------
|
| 573 |
+
# small math helpers
|
| 574 |
+
# ----------------------------------------------------------------------------------------------
|
| 575 |
+
@cute.jit
|
| 576 |
+
def tf32_split(x: Float32):
|
| 577 |
+
"""x = hi + lo with hi exact in tf32 (truncation); the MMA reads the top 19 bits of lo (|error| < 2^-21 |x|)."""
|
| 578 |
+
hi = (x.bitcast(Uint32) & Uint32(0xFFFFE000)).bitcast(Float32)
|
| 579 |
+
return hi, x - hi
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
@cute.jit
|
| 583 |
+
def tf32_split3(x: Float32):
|
| 584 |
+
"""x = hi + lo + lo2 exactly, each term representable in tf32 (truncation splits)."""
|
| 585 |
+
hi = (x.bitcast(Uint32) & Uint32(0xFFFFE000)).bitcast(Float32)
|
| 586 |
+
r = x - hi
|
| 587 |
+
lo = (r.bitcast(Uint32) & Uint32(0xFFFFE000)).bitcast(Float32)
|
| 588 |
+
return hi, lo, r - lo
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
@cute.jit
|
| 592 |
+
def half_split2(a: Float32, b: Float32):
|
| 593 |
+
"""fp16x2 high parts and fp16x2 low parts of (a, b)."""
|
| 594 |
+
h = f2h2(a, b)
|
| 595 |
+
ah, bh = h2f2(h)
|
| 596 |
+
da, db = fsub2(a, b, ah, bh)
|
| 597 |
+
l = f2h2(da, db)
|
| 598 |
+
return h, l
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
@cute.jit
|
| 602 |
+
def sw32_row(base: Uint32, r):
|
| 603 |
+
"""Byte address of the two 16-byte halves of row r in a K/MN SW32 canonical tile (32-byte rows)."""
|
| 604 |
+
rr = Uint32(r)
|
| 605 |
+
a = base + (rr >> Uint32(3)) * Uint32(256) + (rr & Uint32(7)) * Uint32(32)
|
| 606 |
+
sw = ((rr >> Uint32(2)) & Uint32(1)) * Uint32(16)
|
| 607 |
+
return a + sw, a + (Uint32(16) - sw)
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
@cute.jit
|
| 611 |
+
def gram_partial_store(y: cute.Tensor, lane, gw, gbuf: Uint32, p: cutlass.Constexpr):
|
| 612 |
+
"""Form two-row Gram products, then a transposed warp reduction (11 shuffles).
|
| 613 |
+
The permuted entries are stored as per-warp partials at gbuf + 160 p + 16 e + 4 w."""
|
| 614 |
+
b4 = (lane >> 4) & 1
|
| 615 |
+
b3 = (lane >> 3) & 1
|
| 616 |
+
b2 = (lane >> 2) & 1
|
| 617 |
+
b1 = (lane >> 1) & 1
|
| 618 |
+
sl = b3 * 3 + b2 * 2 + b1
|
| 619 |
+
ent = b4 * 5 + sl
|
| 620 |
+
writer = ((lane & 1) == 0) & ((b3 == 0) | (b2 == 0)) & (sl < 5) & (((b3 * 4 + b2 * 2 + b1) != 3))
|
| 621 |
+
# Splitting the ten entries into two sets related by the cycle 0->1->2->3->0
|
| 622 |
+
# lets each lane form five two-row products, rather than all ten products plus selects.
|
| 623 |
+
z = cute.make_rmem_tensor(4, Float32)
|
| 624 |
+
a = cute.make_rmem_tensor(4, Float32)
|
| 625 |
+
b = cute.make_rmem_tensor(4, Float32)
|
| 626 |
+
for i in cutlass.range_constexpr(4):
|
| 627 |
+
z[i] = shfl_bfly(y[i], 16)
|
| 628 |
+
for i in cutlass.range_constexpr(4):
|
| 629 |
+
a[i] = y[i]
|
| 630 |
+
b[i] = z[i]
|
| 631 |
+
if b4 == 1:
|
| 632 |
+
a[i] = y[(i + 1) % 4]
|
| 633 |
+
b[i] = z[(i + 1) % 4]
|
| 634 |
+
r5 = cute.make_rmem_tensor(6, Float32)
|
| 635 |
+
p0, p1 = fmul2(a[0], a[2], a[0], a[2])
|
| 636 |
+
r5[0], r5[1] = ffma2(b[0], b[2], b[0], b[2], p0, p1)
|
| 637 |
+
p0, p1 = fmul2(a[0], a[2], a[1], a[3])
|
| 638 |
+
r5[2], r5[3] = ffma2(b[0], b[2], b[1], b[3], p0, p1)
|
| 639 |
+
r5[4] = a[0] * a[2] + b[0] * b[2]
|
| 640 |
+
r5[5] = Float32(0)
|
| 641 |
+
r3 = cute.make_rmem_tensor(4, Float32)
|
| 642 |
+
for i in cutlass.range_constexpr(3):
|
| 643 |
+
send = r5[3 + i]
|
| 644 |
+
keep = r5[i]
|
| 645 |
+
if b3 == 1:
|
| 646 |
+
send = r5[i]
|
| 647 |
+
keep = r5[3 + i]
|
| 648 |
+
r3[i] = keep + shfl_bfly(send, 8)
|
| 649 |
+
r3[3] = Float32(0)
|
| 650 |
+
r2 = cute.make_rmem_tensor(2, Float32)
|
| 651 |
+
for i in cutlass.range_constexpr(2):
|
| 652 |
+
send = r3[2 + i]
|
| 653 |
+
keep = r3[i]
|
| 654 |
+
if b2 == 1:
|
| 655 |
+
send = r3[i]
|
| 656 |
+
keep = r3[2 + i]
|
| 657 |
+
r2[i] = keep + shfl_bfly(send, 4)
|
| 658 |
+
send = r2[1]
|
| 659 |
+
keep = r2[0]
|
| 660 |
+
if b1 == 1:
|
| 661 |
+
send = r2[0]
|
| 662 |
+
keep = r2[1]
|
| 663 |
+
r1 = keep + shfl_bfly(send, 2)
|
| 664 |
+
r1 = r1 + shfl_bfly(r1, 1)
|
| 665 |
+
if writer:
|
| 666 |
+
sts32(gbuf + Uint32(p * 160) + Uint32(16) * ent.to(Uint32) + Uint32(4) * gw.to(Uint32), r1.bitcast(Uint32))
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
@cute.jit
|
| 670 |
+
def gram_chol_paired(gbuf: Uint32, p: cutlass.Constexpr, cf: cute.Tensor, lane):
|
| 671 |
+
"""Factor the summed Gram matrix with paired independent entries and the original pivot floors."""
|
| 672 |
+
gg = cute.make_rmem_tensor(10, Float32)
|
| 673 |
+
# lanes 0-9 each sum one entry's four per-warp partials; the ten sums are broadcast by shuffles
|
| 674 |
+
v4 = lds128f(gbuf + Uint32(p * 160) + Uint32(16) * cutlass.min(Uint32(lane), Uint32(9)))
|
| 675 |
+
tot = (v4[0] + v4[1]) + (v4[2] + v4[3])
|
| 676 |
+
# gram_partial_store orders the entries as 00,22,01,23,02,11,33,12,03,13.
|
| 677 |
+
for e in cutlass.range_constexpr(10):
|
| 678 |
+
gg[e] = shfl_idx(tot, [0, 2, 5, 4, 7, 1, 8, 9, 3, 6][e])
|
| 679 |
+
l0 = rsqrt_approx(cute.arch.fmax(gg[0], Float32(1e-30)))
|
| 680 |
+
l10 = gg[1] * l0
|
| 681 |
+
# The two independent rows share each preceding inverse diagonal.
|
| 682 |
+
l20, l30 = fmul2(gg[3], gg[6], l0, l0)
|
| 683 |
+
d1 = gg[2] - l10 * l10
|
| 684 |
+
if cutlass.const_expr(p == 0):
|
| 685 |
+
l1 = rsqrt_approx(cute.arch.fmax(cute.arch.fmax(d1, Float32(1e-6) * gg[2]), Float32(1e-30)))
|
| 686 |
+
else:
|
| 687 |
+
l1 = rsqrt_approx(cute.arch.fmax(d1, Float32(1e-30)))
|
| 688 |
+
if d1 <= Float32(TAU2) * gg[2]:
|
| 689 |
+
l1 = Float32(0)
|
| 690 |
+
a21, a31 = ffma2(-l20, -l30, l10, l10, gg[4], gg[7])
|
| 691 |
+
l21, l31 = fmul2(a21, a31, l1, l1)
|
| 692 |
+
d2a, d3a = ffma2(-l20, -l30, l20, l30, gg[5], gg[9])
|
| 693 |
+
d2, d3a = ffma2(-l21, -l31, l21, l31, d2a, d3a)
|
| 694 |
+
if cutlass.const_expr(p == 0):
|
| 695 |
+
l2 = rsqrt_approx(cute.arch.fmax(cute.arch.fmax(d2, Float32(1e-6) * gg[5]), Float32(1e-30)))
|
| 696 |
+
else:
|
| 697 |
+
l2 = rsqrt_approx(cute.arch.fmax(d2, Float32(1e-30)))
|
| 698 |
+
if d2 <= Float32(TAU2) * gg[5]:
|
| 699 |
+
l2 = Float32(0)
|
| 700 |
+
l32 = (gg[8] - l30 * l20 - l31 * l21) * l2
|
| 701 |
+
d3 = d3a - l32 * l32
|
| 702 |
+
if cutlass.const_expr(p == 0):
|
| 703 |
+
l3 = rsqrt_approx(cute.arch.fmax(cute.arch.fmax(d3, Float32(1e-6) * gg[9]), Float32(1e-30)))
|
| 704 |
+
else:
|
| 705 |
+
l3 = rsqrt_approx(cute.arch.fmax(d3, Float32(1e-30)))
|
| 706 |
+
if d3 <= Float32(TAU2) * gg[9]:
|
| 707 |
+
l3 = Float32(0)
|
| 708 |
+
cf[0] = l0
|
| 709 |
+
cf[1] = l10
|
| 710 |
+
cf[2] = l1
|
| 711 |
+
cf[3] = l20
|
| 712 |
+
cf[4] = l21
|
| 713 |
+
cf[5] = l2
|
| 714 |
+
cf[6] = l30
|
| 715 |
+
cf[7] = l31
|
| 716 |
+
cf[8] = l32
|
| 717 |
+
cf[9] = l3
|
| 718 |
+
bad = Boolean(False)
|
| 719 |
+
good = Boolean(False)
|
| 720 |
+
if cutlass.const_expr(p == 0):
|
| 721 |
+
bad = (gg[0] > Float32(1e-30)) & ((d1 < Float32(1e-3) * gg[2]) | (d2 < Float32(1e-3) * gg[5]) | (d3 < Float32(1e-3) * gg[9]))
|
| 722 |
+
good = (gg[0] > Float32(1e-30)) & (d1 > Float32(TAU1) * gg[2]) & (d2 > Float32(TAU1) * gg[5]) & (d3 > Float32(TAU1) * gg[9])
|
| 723 |
+
return bad, good
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
@cute.jit
|
| 727 |
+
def gram_chol_scalar(gbuf: Uint32, p: cutlass.Constexpr, cf: cute.Tensor, lane):
|
| 728 |
+
"""Factor the summed Gram matrix; for the first pass return (needs the precision path, one pass suffices)."""
|
| 729 |
+
gg = cute.make_rmem_tensor(10, Float32)
|
| 730 |
+
# lanes 0-9 each sum one entry's four per-warp partials; the ten sums are broadcast by shuffles
|
| 731 |
+
v4 = lds128f(gbuf + Uint32(p * 160) + Uint32(16) * cutlass.min(Uint32(lane), Uint32(9)))
|
| 732 |
+
tot = (v4[0] + v4[1]) + (v4[2] + v4[3])
|
| 733 |
+
# gram_partial_store orders the entries as 00,22,01,23,02,11,33,12,03,13.
|
| 734 |
+
for e in cutlass.range_constexpr(10):
|
| 735 |
+
gg[e] = shfl_idx(tot, [0, 2, 5, 4, 7, 1, 8, 9, 3, 6][e])
|
| 736 |
+
l0 = rsqrt_approx(cute.arch.fmax(gg[0], Float32(1e-30)))
|
| 737 |
+
l10 = gg[1] * l0
|
| 738 |
+
l1 = Float32(0)
|
| 739 |
+
l2 = Float32(0)
|
| 740 |
+
l3 = Float32(0)
|
| 741 |
+
if cutlass.const_expr(p == 0):
|
| 742 |
+
# first pass: a relative pivot floor damps numerically dependent columns (their direction is kept)
|
| 743 |
+
l1 = rsqrt_approx(cute.arch.fmax(cute.arch.fmax(gg[2] - l10 * l10, Float32(1e-6) * gg[2]), Float32(1e-30)))
|
| 744 |
+
else:
|
| 745 |
+
# second pass: a column without an independent part (relative to its norm) is dropped, which keeps the
|
| 746 |
+
# factor consistent with the vectors and the result orthonormal on the kept columns
|
| 747 |
+
d1 = gg[2] - l10 * l10
|
| 748 |
+
l1 = rsqrt_approx(cute.arch.fmax(d1, Float32(1e-30)))
|
| 749 |
+
if d1 <= Float32(TAU2) * gg[2]:
|
| 750 |
+
l1 = Float32(0)
|
| 751 |
+
l20 = gg[3] * l0
|
| 752 |
+
l21 = (gg[4] - l20 * l10) * l1
|
| 753 |
+
if cutlass.const_expr(p == 0):
|
| 754 |
+
l2 = rsqrt_approx(cute.arch.fmax(cute.arch.fmax(gg[5] - l20 * l20 - l21 * l21, Float32(1e-6) * gg[5]), Float32(1e-30)))
|
| 755 |
+
else:
|
| 756 |
+
d2 = gg[5] - l20 * l20 - l21 * l21
|
| 757 |
+
l2 = rsqrt_approx(cute.arch.fmax(d2, Float32(1e-30)))
|
| 758 |
+
if d2 <= Float32(TAU2) * gg[5]:
|
| 759 |
+
l2 = Float32(0)
|
| 760 |
+
l30 = gg[6] * l0
|
| 761 |
+
l31 = (gg[7] - l30 * l10) * l1
|
| 762 |
+
l32 = (gg[8] - l30 * l20 - l31 * l21) * l2
|
| 763 |
+
if cutlass.const_expr(p == 0):
|
| 764 |
+
l3 = rsqrt_approx(cute.arch.fmax(cute.arch.fmax(gg[9] - l30 * l30 - l31 * l31 - l32 * l32, Float32(1e-6) * gg[9]), Float32(1e-30)))
|
| 765 |
+
else:
|
| 766 |
+
d3 = gg[9] - l30 * l30 - l31 * l31 - l32 * l32
|
| 767 |
+
l3 = rsqrt_approx(cute.arch.fmax(d3, Float32(1e-30)))
|
| 768 |
+
if d3 <= Float32(TAU2) * gg[9]:
|
| 769 |
+
l3 = Float32(0)
|
| 770 |
+
cf[0] = l0
|
| 771 |
+
cf[1] = l10
|
| 772 |
+
cf[2] = l1
|
| 773 |
+
cf[3] = l20
|
| 774 |
+
cf[4] = l21
|
| 775 |
+
cf[5] = l2
|
| 776 |
+
cf[6] = l30
|
| 777 |
+
cf[7] = l31
|
| 778 |
+
cf[8] = l32
|
| 779 |
+
cf[9] = l3
|
| 780 |
+
bad = Boolean(False)
|
| 781 |
+
good = Boolean(False)
|
| 782 |
+
if cutlass.const_expr(p == 0):
|
| 783 |
+
d1 = gg[2] - l10 * l10
|
| 784 |
+
d2 = gg[5] - l20 * l20 - l21 * l21
|
| 785 |
+
d3 = gg[9] - l30 * l30 - l31 * l31 - l32 * l32
|
| 786 |
+
bad = (gg[0] > Float32(1e-30)) & ((d1 < Float32(1e-3) * gg[2]) | (d2 < Float32(1e-3) * gg[5]) | (d3 < Float32(1e-3) * gg[9]))
|
| 787 |
+
good = (gg[0] > Float32(1e-30)) & (d1 > Float32(TAU1) * gg[2]) & (d2 > Float32(TAU1) * gg[5]) & (d3 > Float32(TAU1) * gg[9])
|
| 788 |
+
return bad, good
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
@cute.jit
|
| 792 |
+
def gram_chol(gbuf: Uint32, p: cutlass.Constexpr, cf: cute.Tensor, lane, paired: cutlass.Constexpr):
|
| 793 |
+
# Match the existing small/large launch choice. Both variants are compiled
|
| 794 |
+
# during Pool construction; the flush call never compiles or reads due flags.
|
| 795 |
+
if cutlass.const_expr(paired):
|
| 796 |
+
result = gram_chol_paired(gbuf, p, cf, lane)
|
| 797 |
+
else:
|
| 798 |
+
result = gram_chol_scalar(gbuf, p, cf, lane)
|
| 799 |
+
return result
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
@cute.jit
|
| 803 |
+
def mgs_rows(y: cute.Tensor, lane, gw, buf: Uint32, bar: Uint32):
|
| 804 |
+
# One row per thread; alternate two partial-sum buffers so a following warp store cannot race a reader.
|
| 805 |
+
for j in cutlass.range_constexpr(4):
|
| 806 |
+
v = y[j]
|
| 807 |
+
for rep in cutlass.range_constexpr(2):
|
| 808 |
+
for c in cutlass.range_constexpr(j):
|
| 809 |
+
dot = v * y[c]
|
| 810 |
+
for bit in cutlass.range_constexpr(5):
|
| 811 |
+
dot = dot + shfl_bfly(dot, 16 >> bit)
|
| 812 |
+
addr = buf + Uint32(32 * ((j * j + rep * j + c) % 2))
|
| 813 |
+
if lane == 0:
|
| 814 |
+
sts32(addr + Uint32(4) * gw.to(Uint32), dot.bitcast(Uint32))
|
| 815 |
+
named_bar(bar, 128)
|
| 816 |
+
vv = lds128f(addr)
|
| 817 |
+
dot = (vv[0] + vv[1]) + (vv[2] + vv[3])
|
| 818 |
+
v = v - dot * y[c]
|
| 819 |
+
norm2 = v * v
|
| 820 |
+
for bit in cutlass.range_constexpr(5):
|
| 821 |
+
norm2 = norm2 + shfl_bfly(norm2, 16 >> bit)
|
| 822 |
+
addr = buf + Uint32(32 * ((j * j + 2 * j) % 2))
|
| 823 |
+
if lane == 0:
|
| 824 |
+
sts32(addr + Uint32(4) * gw.to(Uint32), norm2.bitcast(Uint32))
|
| 825 |
+
named_bar(bar, 128)
|
| 826 |
+
vv = lds128f(addr)
|
| 827 |
+
norm2 = (vv[0] + vv[1]) + (vv[2] + vv[3])
|
| 828 |
+
y[j] = v * rsqrt_approx(cute.arch.fmax(norm2, Float32(1e-30)))
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
@cute.jit
|
| 832 |
+
def write_state_part(st: Uint32, tmS: Uint32, lane_off: Uint32, t, tx7: Uint32,
|
| 833 |
+
tail: Uint32, low: cutlass.Constexpr):
|
| 834 |
+
srow = st + (t.to(Uint32) >> Uint32(3)) * Uint32(1024) + tx7 * Uint32(128)
|
| 835 |
+
for blk in cutlass.range_constexpr(8):
|
| 836 |
+
if cutlass.const_expr(blk < 7):
|
| 837 |
+
vv = tmem_wait_ld(tmem_ld16_nw(tmS + lane_off + Uint32(16 * blk)))
|
| 838 |
+
else:
|
| 839 |
+
vv = []
|
| 840 |
+
for i in cutlass.range_constexpr(4):
|
| 841 |
+
vv += lds128f(tail + Uint32(16) * t.to(Uint32) + Uint32(2048 * i))
|
| 842 |
+
for q4 in cutlass.range_constexpr(2):
|
| 843 |
+
ph = cute.make_rmem_tensor(4, Uint32)
|
| 844 |
+
for j in cutlass.range_constexpr(4):
|
| 845 |
+
if cutlass.const_expr(low):
|
| 846 |
+
unused, ph[j] = half_split2(vv[8 * q4 + 2 * j], vv[8 * q4 + 2 * j + 1])
|
| 847 |
+
else:
|
| 848 |
+
ph[j] = f2h2(vv[8 * q4 + 2 * j], vv[8 * q4 + 2 * j + 1])
|
| 849 |
+
ch = Uint32((blk % 4) * 2 + q4)
|
| 850 |
+
sts128(srow + Uint32((blk // 4) * 16384) + ((ch ^ tx7) * Uint32(16)), ph[0], ph[1], ph[2], ph[3])
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
@cute.jit
|
| 854 |
+
def tri_apply(cf: cute.Tensor, y: cute.Tensor):
|
| 855 |
+
q0 = y[0] * cf[0]
|
| 856 |
+
q1 = (y[1] - q0 * cf[1]) * cf[2]
|
| 857 |
+
q2 = (y[2] - q0 * cf[3] - q1 * cf[4]) * cf[5]
|
| 858 |
+
q3 = (y[3] - q0 * cf[6] - q1 * cf[7] - q2 * cf[8]) * cf[9]
|
| 859 |
+
y[0] = q0
|
| 860 |
+
y[1] = q1
|
| 861 |
+
y[2] = q2
|
| 862 |
+
y[3] = q3
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
# ----------------------------------------------------------------------------------------------
|
| 866 |
+
# the kernel
|
| 867 |
+
# ----------------------------------------------------------------------------------------------
|
| 868 |
+
@cute.kernel
|
| 869 |
+
def flush_kernel(raw: cute.Pointer, kbp: cute.Pointer, ubp: cute.Pointer, wp: cute.Pointer, pp: cute.Pointer,
|
| 870 |
+
hcnt: cute.Pointer, idx: cute.Pointer, q0p: cute.Pointer, n: Int32, ns: Int32, tmaps: cute.Pointer, early_exit: cutlass.Constexpr):
|
| 871 |
+
tid, _, _ = cute.arch.thread_idx()
|
| 872 |
+
bid, _, _ = cute.arch.block_idx()
|
| 873 |
+
nblk, _, _ = cute.arch.grid_dim()
|
| 874 |
+
warp = cute.arch.make_warp_uniform(tid // 32)
|
| 875 |
+
lane = tid % 32
|
| 876 |
+
|
| 877 |
+
smem = SmemAllocator()
|
| 878 |
+
stages_raw = smem.allocate_array(Int8, NSTAGE * STAGE, byte_alignment=1024)
|
| 879 |
+
au_raw = smem.allocate_array(Int8, NG * 8192, byte_alignment=1024)
|
| 880 |
+
ao_raw = smem.allocate_array(Int8, NG * 8192, byte_alignment=1024) # AO (4 KB) then BO (4 KB)
|
| 881 |
+
qb_raw = smem.allocate_array(Int8, NG * 6144 + 2048, byte_alignment=1024) # per group QB (4 KiB) | Gram/column partials (2 KiB), then compact Q0B (2 KiB)
|
| 882 |
+
rs_raw = smem.allocate_array(Int8, NG * 512, byte_alignment=16)
|
| 883 |
+
bd_raw = smem.allocate_array(Int8, NG * 128 + 64, byte_alignment=16)
|
| 884 |
+
mb_raw = smem.allocate_array(Int64, 3 * NSTAGE + NG, byte_alignment=8)
|
| 885 |
+
misc = smem.allocate_array(Int32, NSTAGE + 4, byte_alignment=16)
|
| 886 |
+
|
| 887 |
+
stage0 = Uint32(stages_raw.toint())
|
| 888 |
+
au0 = Uint32(au_raw.toint())
|
| 889 |
+
ao0 = Uint32(ao_raw.toint())
|
| 890 |
+
qb0 = Uint32(qb_raw.toint())
|
| 891 |
+
ys0 = qb0 + Uint32(4096)
|
| 892 |
+
cp0 = qb0 + Uint32(4096)
|
| 893 |
+
rs0 = Uint32(rs_raw.toint())
|
| 894 |
+
bd0 = Uint32(bd_raw.toint())
|
| 895 |
+
mb0 = Uint32(mb_raw.toint())
|
| 896 |
+
misc0 = Uint32(misc.toint())
|
| 897 |
+
full0 = mb0
|
| 898 |
+
empty0 = mb0 + Uint32(8 * NSTAGE)
|
| 899 |
+
mma0 = mb0 + Uint32(16 * NSTAGE)
|
| 900 |
+
code0 = mb0 + Uint32(16 * NSTAGE + 8 * NG)
|
| 901 |
+
|
| 902 |
+
if tid == 0:
|
| 903 |
+
for s in cutlass.range_constexpr(NSTAGE):
|
| 904 |
+
mbar_init(full0 + Uint32(8 * s), 1)
|
| 905 |
+
mbar_init(code0 + Uint32(8 * s), 1)
|
| 906 |
+
mbar_init(empty0 + Uint32(8 * s), 1)
|
| 907 |
+
for g in cutlass.range_constexpr(NG):
|
| 908 |
+
mbar_init(mma0 + Uint32(8 * g), 1)
|
| 909 |
+
for s in cutlass.range_constexpr(NSTAGE):
|
| 910 |
+
sts32(misc0 + Uint32(4 * s), Uint32(0xFFFFFFFF)) # no program held by the stage yet
|
| 911 |
+
if cutlass.const_expr(not early_exit):
|
| 912 |
+
if warp == 0:
|
| 913 |
+
tmem_alloc(misc0 + Uint32(4 * NSTAGE), 512)
|
| 914 |
+
cute.arch.mbarrier_init_fence()
|
| 915 |
+
|
| 916 |
+
# global byte addresses
|
| 917 |
+
raw_b = Int64(raw.toint())
|
| 918 |
+
kb_b = Int64(kbp.toint())
|
| 919 |
+
ub_b = Int64(ubp.toint())
|
| 920 |
+
w_b = Int64(wp.toint())
|
| 921 |
+
p_b = Int64(pp.toint())
|
| 922 |
+
hc_b = Int64(hcnt.toint())
|
| 923 |
+
idx_b = Int64(idx.toint())
|
| 924 |
+
tmap_codes = Int64(tmaps.toint())
|
| 925 |
+
tmap_kb = tmap_codes + Int64(128)
|
| 926 |
+
tmap_c32 = tmap_codes + Int64(256)
|
| 927 |
+
tmap_ub = tmap_codes + Int64(384)
|
| 928 |
+
|
| 929 |
+
# the producer's first batch of due checks is issued before the init barrier (their latency overlaps it)
|
| 930 |
+
total = n * Int32(HV)
|
| 931 |
+
due0 = Boolean(False)
|
| 932 |
+
prog0 = Int32(0)
|
| 933 |
+
if warp == PROD_WARP + 1:
|
| 934 |
+
if lane < 4:
|
| 935 |
+
prefetch_tmap(tmap_codes + Int64(128) * Int64(lane)) # codes, kbuf, codes32, ubuf descriptors (idle warp)
|
| 936 |
+
if warp == PROD_WARP + 3:
|
| 937 |
+
if lane == 0:
|
| 938 |
+
prefetch_l2_bulk(Int64(q0p.toint()), Uint32(V * R * 4)) # q0 (2 KB), read by the consumer setup
|
| 939 |
+
if warp == PROD_WARP + 2:
|
| 940 |
+
# the due check's second (dependent) load reads the fill counters: bring the counter array into L2, one slice
|
| 941 |
+
# per CTA, while the first loads are in flight
|
| 942 |
+
hbytes = ns * Int32(HV * 4)
|
| 943 |
+
if lane == 0:
|
| 944 |
+
if (ns > Int32(0)) & (ns <= Int32((1 << 22) // (HV * 4))): # counter arrays up to 4 MB
|
| 945 |
+
chunk = ((hbytes + nblk - Int32(1)) // nblk + Int32(15)) & Int32(-16)
|
| 946 |
+
start = Int32(bid) * chunk
|
| 947 |
+
if start < hbytes:
|
| 948 |
+
prefetch_l2_bulk(hc_b + Int64(start), cutlass.min(chunk, hbytes - start).to(Uint32))
|
| 949 |
+
if warp == PROD_WARP:
|
| 950 |
+
c = Int32(bid) + Int32(lane) * nblk
|
| 951 |
+
if c < total:
|
| 952 |
+
nn = c // Int32(HV)
|
| 953 |
+
hh = (c + Int32(21) * nn) & Int32(HV - 1)
|
| 954 |
+
slot = ldg32(idx_b + Int64(nn) * Int64(4)).to(Int32)
|
| 955 |
+
if slot > Int32(0):
|
| 956 |
+
hc = ldg32_volatile(hc_b + (Int64(slot) * Int64(HV) + Int64(hh)) * Int64(4)).to(Int32)
|
| 957 |
+
if hc == Int32(L):
|
| 958 |
+
due0 = Boolean(True)
|
| 959 |
+
prog0 = slot * Int32(HV) + hh
|
| 960 |
+
|
| 961 |
+
seed_due = Boolean(False)
|
| 962 |
+
if cutlass.const_expr(early_exit):
|
| 963 |
+
if warp == 0:
|
| 964 |
+
c = Int32(bid)
|
| 965 |
+
if c < total:
|
| 966 |
+
nn = c // Int32(HV)
|
| 967 |
+
hh = (c + Int32(21) * nn) & Int32(HV - 1)
|
| 968 |
+
slot = ldg32(idx_b + Int64(nn) * Int64(4)).to(Int32)
|
| 969 |
+
if slot > Int32(0):
|
| 970 |
+
hc = ldg32_volatile(hc_b + (Int64(slot) * Int64(HV) + Int64(hh)) * Int64(4)).to(Int32)
|
| 971 |
+
seed_due = hc == Int32(L)
|
| 972 |
+
if seed_due:
|
| 973 |
+
tmem_alloc(misc0 + Uint32(4 * NSTAGE), 512)
|
| 974 |
+
# A CTA that has no due heads need not initialize q0 or publish four
|
| 975 |
+
# empty stages. Scan later batches only when the current mask is empty.
|
| 976 |
+
first_mask = Uint32(0)
|
| 977 |
+
first_cand = Int32(bid) + Int32(32) * nblk
|
| 978 |
+
if warp == PROD_WARP:
|
| 979 |
+
first_mask = Uint32(cute.arch.vote_ballot_sync(due0))
|
| 980 |
+
while (first_mask == Uint32(0)) & (first_cand < total):
|
| 981 |
+
c = first_cand + Int32(lane) * nblk
|
| 982 |
+
due = Boolean(False)
|
| 983 |
+
prog0 = Int32(0)
|
| 984 |
+
if c < total:
|
| 985 |
+
nn = c // Int32(HV)
|
| 986 |
+
hh = (c + Int32(21) * nn) & Int32(HV - 1)
|
| 987 |
+
slot = ldg32(idx_b + Int64(nn) * Int64(4)).to(Int32)
|
| 988 |
+
if slot > Int32(0):
|
| 989 |
+
hc = ldg32_volatile(hc_b + (Int64(slot) * Int64(HV) + Int64(hh)) * Int64(4)).to(Int32)
|
| 990 |
+
if hc == Int32(L):
|
| 991 |
+
due = Boolean(True)
|
| 992 |
+
prog0 = slot * Int32(HV) + hh
|
| 993 |
+
first_mask = Uint32(cute.arch.vote_ballot_sync(due))
|
| 994 |
+
first_cand = first_cand + Int32(32) * nblk
|
| 995 |
+
if lane == 0:
|
| 996 |
+
sts32(misc0 + Uint32(4 * (NSTAGE + 1)), first_mask)
|
| 997 |
+
|
| 998 |
+
cute.arch.sync_threads() # barriers initialized and initial scan published: producer can start
|
| 999 |
+
tmem_base = Uint32(0)
|
| 1000 |
+
if cutlass.const_expr(not early_exit):
|
| 1001 |
+
tmem_base = lds32(misc0 + Uint32(4 * NSTAGE))
|
| 1002 |
+
|
| 1003 |
+
has_work = Boolean(True)
|
| 1004 |
+
if cutlass.const_expr(early_exit):
|
| 1005 |
+
has_work = lds32(misc0 + Uint32(4 * (NSTAGE + 1))) != Uint32(0)
|
| 1006 |
+
if has_work:
|
| 1007 |
+
if warp >= PROD_WARP:
|
| 1008 |
+
cute.arch.setmaxregister_decrease(REG_PROD)
|
| 1009 |
+
if warp == PROD_WARP:
|
| 1010 |
+
# ------------------------------------------------------------------ producer
|
| 1011 |
+
if cutlass.const_expr(early_exit):
|
| 1012 |
+
mask = first_mask
|
| 1013 |
+
cand = first_cand
|
| 1014 |
+
else:
|
| 1015 |
+
mask = Uint32(cute.arch.vote_ballot_sync(due0))
|
| 1016 |
+
cand = Int32(bid) + Int32(32) * nblk
|
| 1017 |
+
prog = prog0
|
| 1018 |
+
k = Int32(0)
|
| 1019 |
+
ends = Int32(0)
|
| 1020 |
+
while ends < Int32(NG):
|
| 1021 |
+
# next due program: iterate over the cached due mask of a batch of 32 candidates (one per lane)
|
| 1022 |
+
pid = Int32(-1)
|
| 1023 |
+
looking = Boolean(True)
|
| 1024 |
+
while looking:
|
| 1025 |
+
if mask == Uint32(0):
|
| 1026 |
+
if cand >= total:
|
| 1027 |
+
looking = Boolean(False)
|
| 1028 |
+
else:
|
| 1029 |
+
c = cand + Int32(lane) * nblk
|
| 1030 |
+
due = Boolean(False)
|
| 1031 |
+
prog = Int32(0)
|
| 1032 |
+
if c < total:
|
| 1033 |
+
nn = c // Int32(HV)
|
| 1034 |
+
hh = (c + Int32(21) * nn) & Int32(HV - 1)
|
| 1035 |
+
slot = ldg32(idx_b + Int64(nn) * Int64(4)).to(Int32)
|
| 1036 |
+
if slot > Int32(0):
|
| 1037 |
+
hc = ldg32_volatile(hc_b + (Int64(slot) * Int64(HV) + Int64(hh)) * Int64(4)).to(Int32)
|
| 1038 |
+
if hc == Int32(L):
|
| 1039 |
+
due = Boolean(True)
|
| 1040 |
+
prog = slot * Int32(HV) + hh
|
| 1041 |
+
mask = Uint32(cute.arch.vote_ballot_sync(due))
|
| 1042 |
+
cand = cand + Int32(32) * nblk
|
| 1043 |
+
if mask != Uint32(0):
|
| 1044 |
+
first = cute.arch.popc((mask & (Uint32(0) - mask)) - Uint32(1)).to(Int32)
|
| 1045 |
+
pid = cute.arch.shuffle_sync(prog, first)
|
| 1046 |
+
mask = mask & (mask - Uint32(1))
|
| 1047 |
+
looking = Boolean(False)
|
| 1048 |
+
s = k % Int32(NSTAGE)
|
| 1049 |
+
ph = (k // Int32(NSTAGE)) & Int32(1)
|
| 1050 |
+
mbar_wait(empty0 + Uint32(8) * s.to(Uint32), (ph ^ Int32(1)).to(Uint32))
|
| 1051 |
+
# window reset (w = 0, p = 1) of the program this stage held before: its inputs have been consumed
|
| 1052 |
+
old = lds32(misc0 + Uint32(4) * s.to(Uint32)).to(Int32)
|
| 1053 |
+
if old >= Int32(0):
|
| 1054 |
+
if lane < 16:
|
| 1055 |
+
stg32(w_b + Int64(old) * Int64(64) + Int64(4) * Int64(lane), Uint32(0))
|
| 1056 |
+
if lane == 16:
|
| 1057 |
+
stg32(p_b + Int64(old) * Int64(4), Float32(1.0).bitcast(Uint32))
|
| 1058 |
+
cute.arch.sync_warp()
|
| 1059 |
+
if lane == 0:
|
| 1060 |
+
sts32(misc0 + Uint32(4) * s.to(Uint32), pid.to(Uint32))
|
| 1061 |
+
fb = full0 + Uint32(8) * s.to(Uint32)
|
| 1062 |
+
if pid >= Int32(0):
|
| 1063 |
+
slot = pid // Int32(HV)
|
| 1064 |
+
hh = pid - slot * Int32(HV)
|
| 1065 |
+
st = stage0 + Uint32(STAGE) * s.to(Uint32)
|
| 1066 |
+
mbar_arrive_tx(fb, LOAD_BYTES)
|
| 1067 |
+
head_b = raw_b + (Int64(OFF) + Int64(slot) * Int64(SS) + Int64(hh) * Int64(16384)) * Int64(4)
|
| 1068 |
+
bulk_load(st + Uint32(ST_SC), head_b + Int64(16384), Uint32(3072), fb)
|
| 1069 |
+
bulk_load(st + Uint32(ST_W), w_b + Int64(pid) * Int64(64), Uint32(64), fb)
|
| 1070 |
+
bulk_load(st + Uint32(ST_P), (p_b + Int64(pid) * Int64(4)) & Int64(-16), Uint32(16), fb)
|
| 1071 |
+
tma_load_4d(st + Uint32(ST_UB), tmap_ub, Int32(0), Int32(0), Int32(0), pid, fb)
|
| 1072 |
+
tma_load_4d(st + Uint32(ST_KB), tmap_kb, Int32(0), Int32(0), Int32(0), pid, fb)
|
| 1073 |
+
else:
|
| 1074 |
+
mbar_arrive(fb)
|
| 1075 |
+
# steady state: the 16 KB code tile (needed ~1.3K cycles after the small inputs) follows after a short
|
| 1076 |
+
# pause, which reduces the refill's interference with the other groups' phases
|
| 1077 |
+
if k >= Int32(NSTAGE):
|
| 1078 |
+
nanosleep_ns(200)
|
| 1079 |
+
if lane == 0:
|
| 1080 |
+
if pid >= Int32(0):
|
| 1081 |
+
slot = pid // Int32(HV)
|
| 1082 |
+
hh = pid - slot * Int32(HV)
|
| 1083 |
+
cb = code0 + Uint32(8) * s.to(Uint32)
|
| 1084 |
+
mbar_arrive_tx(cb, 16384)
|
| 1085 |
+
tma_load_4d(stage0 + Uint32(STAGE) * s.to(Uint32) + Uint32(ST_CODES), tmap_codes, Int32(0), Int32(0), hh, slot, cb)
|
| 1086 |
+
if pid < Int32(0):
|
| 1087 |
+
ends = ends + Int32(1)
|
| 1088 |
+
k = k + Int32(1)
|
| 1089 |
+
else:
|
| 1090 |
+
cute.arch.setmaxregister_increase(REG_CONS)
|
| 1091 |
+
if cutlass.const_expr(early_exit):
|
| 1092 |
+
if warp == 0:
|
| 1093 |
+
if not seed_due:
|
| 1094 |
+
tmem_alloc(misc0 + Uint32(4 * NSTAGE), 512)
|
| 1095 |
+
# ------------------------------------------------------------------ consumers
|
| 1096 |
+
# Q0 operand (MN-major INTER [K=128 v x N=8]: fp16 hi of q0 | fp16 lo of q0).
|
| 1097 |
+
# Normalize each column by its own power of two to preserve small columns of the starting subspace.
|
| 1098 |
+
# Consumer warps set it up while the producer streams the first stages.
|
| 1099 |
+
q0f = cute.recast_ptr(q0p, dtype=Float32)
|
| 1100 |
+
qv = cute.make_rmem_tensor(4, Float32)
|
| 1101 |
+
for c in cutlass.range_constexpr(4):
|
| 1102 |
+
qv[c] = Float32(0)
|
| 1103 |
+
if warp < 4:
|
| 1104 |
+
qmb = cute.make_rmem_tensor(4, Uint32)
|
| 1105 |
+
for c in cutlass.range_constexpr(4):
|
| 1106 |
+
qv[c] = q0f[tid * 4 + c]
|
| 1107 |
+
for c in cutlass.range_constexpr(4):
|
| 1108 |
+
qmb[c] = redux_max(qv[c].bitcast(Uint32) & Uint32(0x7FFFFFFF))
|
| 1109 |
+
if lane == 0:
|
| 1110 |
+
sts128(bd0 + Uint32(NG * 128 + 16 * warp), qmb[0], qmb[1], qmb[2], qmb[3])
|
| 1111 |
+
named_bar(Uint32(15), 128 * NG)
|
| 1112 |
+
if warp < 4:
|
| 1113 |
+
# Lanes 0..3 reduce one column each, and broadcast their power-of-two scales.
|
| 1114 |
+
qc = Uint32(lane & 3)
|
| 1115 |
+
qmax = Uint32(0)
|
| 1116 |
+
for w4 in cutlass.range_constexpr(4):
|
| 1117 |
+
qmax = cutlass.max(qmax, lds32(bd0 + Uint32(NG * 128 + 16 * w4) + Uint32(4) * qc))
|
| 1118 |
+
qe = ((qmax >> Uint32(23)) & Uint32(255)).to(Int32)
|
| 1119 |
+
qscale = Float32(1.0)
|
| 1120 |
+
if qmax != Uint32(0):
|
| 1121 |
+
qscale = exp2_int(cutlass.min(cutlass.max(Int32(126) - qe, Int32(-126)), Int32(127)))
|
| 1122 |
+
for c in cutlass.range_constexpr(4):
|
| 1123 |
+
qv[c] = qv[c] * shfl_idx(qscale, c)
|
| 1124 |
+
h01, l01 = half_split2(qv[0], qv[1])
|
| 1125 |
+
h23, l23 = half_split2(qv[2], qv[3])
|
| 1126 |
+
sts128(qb0 + Uint32(NG * 6144) + Uint32(16) * Uint32(tid), h01, h23, l01, l23)
|
| 1127 |
+
if warp < 4 * NG:
|
| 1128 |
+
a, b = sw32_row(qb0 + Uint32(6144) * Uint32(warp // 4), tid % 128)
|
| 1129 |
+
sts128(b, Uint32(0), Uint32(0), Uint32(0), Uint32(0))
|
| 1130 |
+
a, b = sw32_row(stage0 + Uint32(STAGE) * Uint32(warp // 4) + Uint32(28672), tid % 128)
|
| 1131 |
+
sts128(b, Uint32(0), Uint32(0), Uint32(0), Uint32(0))
|
| 1132 |
+
fence_async_smem()
|
| 1133 |
+
named_bar(Uint32(15), 128 * NG)
|
| 1134 |
+
if cutlass.const_expr(early_exit):
|
| 1135 |
+
tmem_base = lds32(misc0 + Uint32(4 * NSTAGE))
|
| 1136 |
+
g = warp // 4
|
| 1137 |
+
gw = warp % 4
|
| 1138 |
+
t = tid % 128
|
| 1139 |
+
bar = Uint32(1) + g.to(Uint32)
|
| 1140 |
+
leader = gw == g
|
| 1141 |
+
tmS = tmem_base + Uint32(128) * g.to(Uint32)
|
| 1142 |
+
tmY = tmS + Uint32(112)
|
| 1143 |
+
lane_off = (Uint32(32) * gw.to(Uint32)) << Uint32(16)
|
| 1144 |
+
mbar_g = mma0 + Uint32(8) * g.to(Uint32)
|
| 1145 |
+
au = au0 + Uint32(8192) * g.to(Uint32)
|
| 1146 |
+
ao = ao0 + Uint32(8192) * g.to(Uint32)
|
| 1147 |
+
bo = ao + Uint32(4096)
|
| 1148 |
+
qb = qb0 + Uint32(6144) * g.to(Uint32)
|
| 1149 |
+
q0b = qb0 + Uint32(6144 * NG)
|
| 1150 |
+
ys = ys0 + Uint32(6144) * g.to(Uint32)
|
| 1151 |
+
cpg = cp0 + Uint32(6144) * g.to(Uint32)
|
| 1152 |
+
da = qb # scale-product A in QB; B uses the tail of the current input stage
|
| 1153 |
+
rsg = rs0 + Uint32(512) * g.to(Uint32)
|
| 1154 |
+
bdg = bd0 + Uint32(128) * g.to(Uint32)
|
| 1155 |
+
|
| 1156 |
+
mph = Uint32(0)
|
| 1157 |
+
s = g # stage s == group g (NSTAGE == NG)
|
| 1158 |
+
fph = Uint32(0)
|
| 1159 |
+
mbar_wait(full0 + Uint32(8) * s.to(Uint32), fph)
|
| 1160 |
+
pid = lds32(misc0 + Uint32(4) * s.to(Uint32)).to(Int32)
|
| 1161 |
+
while pid >= Int32(0):
|
| 1162 |
+
st = stage0 + Uint32(STAGE) * s.to(Uint32)
|
| 1163 |
+
db = st + Uint32(28672) # 4 KiB unused by TMA inputs, consumed before S overwrites the stage
|
| 1164 |
+
slot = pid // Int32(HV)
|
| 1165 |
+
hh = pid - slot * Int32(HV)
|
| 1166 |
+
head_b = raw_b + (Int64(OFF) + Int64(slot) * Int64(SS) + Int64(hh) * Int64(16384)) * Int64(4)
|
| 1167 |
+
# ---------------------------------------------------------- P1: inputs and the power-of-two scale
|
| 1168 |
+
pval = lds32f(st + Uint32(ST_P) + Uint32(4) * (pid & Int32(3)).to(Uint32))
|
| 1169 |
+
skt = lds32f(st + Uint32(ST_SC) + Uint32(4) * t.to(Uint32))
|
| 1170 |
+
svt = lds32f(st + Uint32(ST_SC + 512) + Uint32(4) * t.to(Uint32))
|
| 1171 |
+
uo = cute.make_rmem_tensor(4, Float32)
|
| 1172 |
+
qo = cute.make_rmem_tensor(4, Float32)
|
| 1173 |
+
mq = Float32(0)
|
| 1174 |
+
mu = Float32(0)
|
| 1175 |
+
for r in cutlass.range_constexpr(4):
|
| 1176 |
+
uo[r] = h2f(lds16(st + Uint32(ST_SC + 1024 + 512 * r) + Uint32(2) * t.to(Uint32)))
|
| 1177 |
+
qo[r] = h2f(lds16(st + Uint32(ST_SC + 1024 + 512 * r + 256) + Uint32(2) * t.to(Uint32)))
|
| 1178 |
+
mu = cute.arch.fmax(mu, cute.math.abs(uo[r]))
|
| 1179 |
+
mq = cute.arch.fmax(mq, cute.math.abs(qo[r]))
|
| 1180 |
+
# thread t covers the 16 values at byte 16 t of both 64-column halves of the (SW128) kbuf and ubuf tiles:
|
| 1181 |
+
# row j = t // 8 of each; the B operand of the update product is 2^sig w_j kbuf_j (ubuf is A as loaded)
|
| 1182 |
+
wj = lds32f(st + Uint32(ST_W) + Uint32(4) * (t.to(Uint32) >> Uint32(3)))
|
| 1183 |
+
kw = lds128(st + Uint32(ST_KB) + Uint32(16) * t.to(Uint32))
|
| 1184 |
+
kw2 = lds128(st + Uint32(ST_KB + 2048) + Uint32(16) * t.to(Uint32))
|
| 1185 |
+
uw = lds128(st + Uint32(ST_UB) + Uint32(16) * t.to(Uint32))
|
| 1186 |
+
uw2 = lds128(st + Uint32(ST_UB + 2048) + Uint32(16) * t.to(Uint32))
|
| 1187 |
+
kx = [bmaxabs2(kw[e], kw2[e]) for e in range(4)]
|
| 1188 |
+
kx = bmaxabs2(bmaxabs2(kx[0], kx[1]), bmaxabs2(kx[2], kx[3]))
|
| 1189 |
+
mkb = (cute.math.abs(wj) * cutlass.max((kx << Uint32(16)) & Uint32(0x7FFF0000), kx & Uint32(0x7FFF0000)).bitcast(Float32)).bitcast(Uint32)
|
| 1190 |
+
ux = [bmaxabs2(uw[e], uw2[e]) for e in range(4)]
|
| 1191 |
+
ux = bmaxabs2(bmaxabs2(ux[0], ux[1]), bmaxabs2(ux[2], ux[3]))
|
| 1192 |
+
mub = cutlass.max((ux << Uint32(16)) & Uint32(0x7FFF0000), ux & Uint32(0x7FFF0000))
|
| 1193 |
+
r0 = redux_max(skt.bitcast(Uint32) & Uint32(0x7FFFFFFF))
|
| 1194 |
+
r1 = redux_max(svt.bitcast(Uint32) & Uint32(0x7FFFFFFF))
|
| 1195 |
+
r2 = redux_max(mq.bitcast(Uint32))
|
| 1196 |
+
r3 = redux_max(mu.bitcast(Uint32))
|
| 1197 |
+
r4 = redux_max(mub)
|
| 1198 |
+
r5 = redux_max(mkb)
|
| 1199 |
+
# scale product D[v][k] = (p s_v[v] / 127) s_k[k] by one tf32 MMA: (bh + bl)(ah + al) from two-term
|
| 1200 |
+
# truncation splits (relative error < 2^-19); A's K slots 4-7 stay zero (written once), B's hold finite data
|
| 1201 |
+
bh, bl = tf32_split((pval * svt) * Float32(256.0 / 127.0))
|
| 1202 |
+
ah, al = tf32_split(skt)
|
| 1203 |
+
a, b = sw32_row(da, t)
|
| 1204 |
+
sts128(a, bh.bitcast(Uint32), bh.bitcast(Uint32), bl.bitcast(Uint32), bl.bitcast(Uint32))
|
| 1205 |
+
a, b = sw32_row(db, t)
|
| 1206 |
+
sts128(a, ah.bitcast(Uint32), al.bitcast(Uint32), ah.bitcast(Uint32), al.bitcast(Uint32))
|
| 1207 |
+
tc_before()
|
| 1208 |
+
if lane == 0:
|
| 1209 |
+
bulk_wait_read0() # previous program's code tiles (AU/AO) read
|
| 1210 |
+
b = bdg + Uint32(32) * gw.to(Uint32)
|
| 1211 |
+
sts128(b, r0, r1, r2, r3)
|
| 1212 |
+
sts32(b + Uint32(16), r4)
|
| 1213 |
+
sts32(b + Uint32(20), r5)
|
| 1214 |
+
named_bar(bar, 128)
|
| 1215 |
+
if leader:
|
| 1216 |
+
# The barrier acquires every writer's stores; this fence publishes them to the async reader.
|
| 1217 |
+
fence_async_smem()
|
| 1218 |
+
tc_after()
|
| 1219 |
+
with cute.arch.elect_one():
|
| 1220 |
+
mma_list(tmS, mbar_g, [da >> Uint32(4), db >> Uint32(4)], [("tf32", 0, "0xC000401000010000", 1, "0xC000401000010000", "0x08200910", False)])
|
| 1221 |
+
# Six lanes reduce one bound component each; broadcast the six maxima to the warp.
|
| 1222 |
+
boff = Uint32(4) * cutlass.min(Uint32(lane), Uint32(5))
|
| 1223 |
+
mm = lds32(bdg + boff)
|
| 1224 |
+
for w4 in cutlass.range_constexpr(1, 4):
|
| 1225 |
+
mm = cutlass.max(mm, lds32(bdg + Uint32(32 * w4) + boff))
|
| 1226 |
+
m0 = shfl_idx(mm.bitcast(Float32), 0).bitcast(Uint32)
|
| 1227 |
+
m1 = shfl_idx(mm.bitcast(Float32), 1).bitcast(Uint32)
|
| 1228 |
+
m2 = shfl_idx(mm.bitcast(Float32), 2).bitcast(Uint32)
|
| 1229 |
+
m3 = shfl_idx(mm.bitcast(Float32), 3).bitcast(Uint32)
|
| 1230 |
+
m4 = shfl_idx(mm.bitcast(Float32), 4).bitcast(Uint32)
|
| 1231 |
+
m5 = shfl_idx(mm.bitcast(Float32), 5).bitcast(Uint32)
|
| 1232 |
+
bound = pval * (m0.bitcast(Float32) * m1.bitcast(Float32) + Float32(4.0) * m2.bitcast(Float32) * m3.bitcast(Float32)) \
|
| 1233 |
+
+ Float32(16.0) * m4.bitcast(Float32) * m5.bitcast(Float32)
|
| 1234 |
+
be = ((bound.bitcast(Uint32) >> Uint32(23)) & Uint32(255)).to(Int32) - Int32(127) # bound < 2^(be+1)
|
| 1235 |
+
sig = Int32(0)
|
| 1236 |
+
if bound > Float32(0):
|
| 1237 |
+
sig = (Int32(6) - be) & Int32(-2) # bound 2^sig < 2^8: |S^T q0| <= 128 2^8 fits fp16
|
| 1238 |
+
sig = cutlass.min(cutlass.max(sig, Int32(-120)), Int32(104))
|
| 1239 |
+
sh = sig // Int32(2)
|
| 1240 |
+
sc_h = exp2_int(sh) # 2^(sig/2)
|
| 1241 |
+
sc = sc_h * sc_h # 2^sig
|
| 1242 |
+
isc_h = exp2_int(-sh)
|
| 1243 |
+
isc = isc_h * isc_h # 2^-sig (normal: sig in [-120, 104])
|
| 1244 |
+
# ---------------------------------------------------------- P1b: MMA operands
|
| 1245 |
+
# KW (in AU): hi/lo bf16 of 2^sig w_j kbuf[j][k], same SW128 MN-major layout as the kbuf tile
|
| 1246 |
+
hv = cute.make_rmem_tensor(8, Uint32)
|
| 1247 |
+
lv = cute.make_rmem_tensor(8, Uint32)
|
| 1248 |
+
fw = wj * sc
|
| 1249 |
+
kws = [kw[0], kw[1], kw[2], kw[3], kw2[0], kw2[1], kw2[2], kw2[3]]
|
| 1250 |
+
for e in cutlass.range_constexpr(8):
|
| 1251 |
+
k0, k1 = bf2f2(kws[e])
|
| 1252 |
+
x0, x1 = fmul2(k0, k1, fw, fw)
|
| 1253 |
+
hv[e] = prmt(x0.bitcast(Uint32), x1.bitcast(Uint32), Uint32(0x7632)) # truncated bf16 high parts
|
| 1254 |
+
n0, n1 = bfsub2(hv[e], x0, x1) # -(low parts), exact
|
| 1255 |
+
lv[e] = f2bf2(n0, n1) # bf16 of -lo: the second update MMA negates B
|
| 1256 |
+
sts128(au + Uint32(16) * t.to(Uint32), hv[0], hv[1], hv[2], hv[3])
|
| 1257 |
+
sts128(au + Uint32(2048) + Uint32(16) * t.to(Uint32), hv[4], hv[5], hv[6], hv[7])
|
| 1258 |
+
sts128(au + Uint32(4096) + Uint32(16) * t.to(Uint32), lv[0], lv[1], lv[2], lv[3])
|
| 1259 |
+
sts128(au + Uint32(6144) + Uint32(16) * t.to(Uint32), lv[4], lv[5], lv[6], lv[7])
|
| 1260 |
+
# AO row t: tf32 hi/lo of 2^sig p q_old[r][t]; BO row t: u_old[r][t] twice
|
| 1261 |
+
psc = pval * sc
|
| 1262 |
+
th = cute.make_rmem_tensor(4, Float32)
|
| 1263 |
+
tl = cute.make_rmem_tensor(4, Float32)
|
| 1264 |
+
for r in cutlass.range_constexpr(4):
|
| 1265 |
+
th[r], tl[r] = tf32_split(psc * qo[r])
|
| 1266 |
+
a, b = sw32_row(ao, t)
|
| 1267 |
+
sts128(a, th[0].bitcast(Uint32), th[1].bitcast(Uint32), th[2].bitcast(Uint32), th[3].bitcast(Uint32))
|
| 1268 |
+
sts128(b, tl[0].bitcast(Uint32), tl[1].bitcast(Uint32), tl[2].bitcast(Uint32), tl[3].bitcast(Uint32))
|
| 1269 |
+
a, b = sw32_row(bo, t)
|
| 1270 |
+
sts128(a, uo[0].bitcast(Uint32), uo[1].bitcast(Uint32), uo[2].bitcast(Uint32), uo[3].bitcast(Uint32))
|
| 1271 |
+
sts128(b, uo[0].bitcast(Uint32), uo[1].bitcast(Uint32), uo[2].bitcast(Uint32), uo[3].bitcast(Uint32))
|
| 1272 |
+
# ---------------------------------------------------------- P1c: dequantized residual -> TMEM (one code chunk ahead)
|
| 1273 |
+
# code c -> float 2^(23+sig) + (c + 128) 2^sig, minus (2^23 + 128) 2^sig = c 2^sig exactly; times D
|
| 1274 |
+
# the scale product in TMEM is 2^8 D: codes carry 2^(sig - 8)
|
| 1275 |
+
s8 = sig - Int32(8)
|
| 1276 |
+
s8c = cutlass.min(cutlass.max(s8, Int32(-24)), Int32(4))
|
| 1277 |
+
cbase = st + Uint32(ST_CODES) + Uint32(128) * t.to(Uint32)
|
| 1278 |
+
tx7 = Uint32(t % 8)
|
| 1279 |
+
mbar_wait(code0 + Uint32(8) * s.to(Uint32), fph)
|
| 1280 |
+
cks0 = [lds128(cbase + tx7 * Uint32(16)), lds128(cbase + ((Uint32(1) ^ tx7) * Uint32(16)))]
|
| 1281 |
+
mbar_wait(mbar_g, mph)
|
| 1282 |
+
mph = mph ^ Uint32(1)
|
| 1283 |
+
tc_after()
|
| 1284 |
+
if s8 != s8c:
|
| 1285 |
+
# rare (|S| far from the usual range): rescale the scale product exactly by 2^(s8 - s8c) so that
|
| 1286 |
+
# codes scaled by 2^s8c still give 2^sig c D
|
| 1287 |
+
fix = exp2_int(s8 - s8c)
|
| 1288 |
+
for blk in cutlass.range_constexpr(8):
|
| 1289 |
+
vv = tmem_wait_ld(tmem_ld16_nw(tmS + lane_off + Uint32(16 * blk)))
|
| 1290 |
+
for i in cutlass.range_constexpr(8):
|
| 1291 |
+
vv[2 * i], vv[2 * i + 1] = fmul2(vv[2 * i], vv[2 * i + 1], fix, fix)
|
| 1292 |
+
tmem_st16_nw(tmS + lane_off + Uint32(16 * blk), vv)
|
| 1293 |
+
tmem_wait_st()
|
| 1294 |
+
dsc0 = tmem_wait_ld(tmem_ld16_nw(tmS + lane_off))
|
| 1295 |
+
|
| 1296 |
+
mgw = ((Int32(25) + s8c).to(Uint32) << Uint32(2)) * Uint32(0x01010101) # fp16 exponent byte of 2^s8 1024
|
| 1297 |
+
na = Float32(-1152.0) * exp2_int(s8c)
|
| 1298 |
+
dsc = dsc0
|
| 1299 |
+
cks = [cks0[0], cks0[1]]
|
| 1300 |
+
vprev = []
|
| 1301 |
+
for blk in cutlass.range_constexpr(8):
|
| 1302 |
+
if cutlass.const_expr(blk < 7):
|
| 1303 |
+
dn = tmem_ld16_nw(tmS + lane_off + Uint32(16 * (blk + 1)))
|
| 1304 |
+
if cutlass.const_expr(blk < 6):
|
| 1305 |
+
cks.append(lds128(cbase + ((Uint32(blk + 2) ^ tx7) * Uint32(16))))
|
| 1306 |
+
cw = cks[blk]
|
| 1307 |
+
vals = []
|
| 1308 |
+
for w in cutlass.range_constexpr(4):
|
| 1309 |
+
wx = cw[w] ^ Uint32(0x80808080)
|
| 1310 |
+
c0, c1 = fhadd2(prmt(wx, mgw, Uint32(0x4140)), na)
|
| 1311 |
+
c2, c3 = fhadd2(prmt(wx, mgw, Uint32(0x4342)), na)
|
| 1312 |
+
c0, c1 = fmul2(c0, c1, dsc[4 * w], dsc[4 * w + 1])
|
| 1313 |
+
c2, c3 = fmul2(c2, c3, dsc[4 * w + 2], dsc[4 * w + 3])
|
| 1314 |
+
vals += [c0, c1, c2, c3]
|
| 1315 |
+
if cutlass.const_expr(blk % 2 == 1):
|
| 1316 |
+
tmem_st32_nw(tmS + lane_off + Uint32(16 * (blk - 1)), vprev + vals) # two blocks per store
|
| 1317 |
+
else:
|
| 1318 |
+
vprev = vals
|
| 1319 |
+
if cutlass.const_expr(blk < 7):
|
| 1320 |
+
dsc = tmem_wait_ld(dn)
|
| 1321 |
+
tmem_wait_st()
|
| 1322 |
+
# ---------------------------------------------------------- build MMA
|
| 1323 |
+
tc_before()
|
| 1324 |
+
named_bar(bar, 128)
|
| 1325 |
+
if leader:
|
| 1326 |
+
fence_async_smem()
|
| 1327 |
+
tc_after()
|
| 1328 |
+
with cute.arch.elect_one():
|
| 1329 |
+
mma_list(tmS, mbar_g, [(st + Uint32(ST_UB)) >> Uint32(4), au >> Uint32(4), (au + Uint32(4096)) >> Uint32(4),
|
| 1330 |
+
ao >> Uint32(4), bo >> Uint32(4)],
|
| 1331 |
+
[("f16", 0, "0x4000404000800000", 1, "0x4000404000800000", "0x08218490", True), ("f16", 0, "0x4000404000800000", 2, "0x4000404000800000", "0x0821C490", True),
|
| 1332 |
+
("tf32", 3, "0xC000401000010000", 4, "0xC000401000010000", "0x08200910", True)])
|
| 1333 |
+
mbar_wait(mbar_g, mph)
|
| 1334 |
+
mph = mph ^ Uint32(1)
|
| 1335 |
+
tc_after()
|
| 1336 |
+
tailS = cute.make_rmem_tensor(8, Float32)
|
| 1337 |
+
# ---------------------------------------------------------- P2: fp16 copy of S (SW128 K-major canonical in the stage)
|
| 1338 |
+
srow = st + (t.to(Uint32) >> Uint32(3)) * Uint32(1024) + tx7 * Uint32(128)
|
| 1339 |
+
v32 = tmem_wait_ld(tmem_ld32_nw(tmS + lane_off))
|
| 1340 |
+
for bp in cutlass.range_constexpr(4): # 32 columns per TMEM load
|
| 1341 |
+
if cutlass.const_expr(bp < 3):
|
| 1342 |
+
nxt = tmem_ld32_nw(tmS + lane_off + Uint32(32 * (bp + 1)))
|
| 1343 |
+
if cutlass.const_expr(bp == 3):
|
| 1344 |
+
for i in cutlass.range_constexpr(8):
|
| 1345 |
+
tailS[i] = v32[16 + i]
|
| 1346 |
+
for hb in cutlass.range_constexpr(2):
|
| 1347 |
+
blk = 2 * bp + hb
|
| 1348 |
+
for q4 in cutlass.range_constexpr(2):
|
| 1349 |
+
ch = Uint32((blk % 4) * 2 + q4)
|
| 1350 |
+
o = 16 * hb + q4 * 8
|
| 1351 |
+
h0 = f2h2(v32[o + 0], v32[o + 1])
|
| 1352 |
+
h1 = f2h2(v32[o + 2], v32[o + 3])
|
| 1353 |
+
h2 = f2h2(v32[o + 4], v32[o + 5])
|
| 1354 |
+
h3 = f2h2(v32[o + 6], v32[o + 7])
|
| 1355 |
+
sts128(srow + Uint32((blk // 4) * 16384) + ((ch ^ tx7) * Uint32(16)), h0, h1, h2, h3)
|
| 1356 |
+
if cutlass.const_expr(bp < 3):
|
| 1357 |
+
v32 = tmem_wait_ld(nxt)
|
| 1358 |
+
tc_before()
|
| 1359 |
+
named_bar(bar, 128)
|
| 1360 |
+
if leader:
|
| 1361 |
+
fence_async_smem()
|
| 1362 |
+
tc_after()
|
| 1363 |
+
with cute.arch.elect_one():
|
| 1364 |
+
mma8_f16(tmY, st >> Uint32(4), q0b >> Uint32(4), mbar_g, "0x4000404004000000", [0, 128, 256, 384, 512, 640, 768, 896], "0x0000400000080000", [0, 16, 32, 48, 64, 80, 96, 112], "0x08038010")
|
| 1365 |
+
mbar_wait(mbar_g, mph)
|
| 1366 |
+
mph = mph ^ Uint32(1)
|
| 1367 |
+
tc_after()
|
| 1368 |
+
# ---------------------------------------------------------- P3: S^T q0 (scaled into fp16 range) -> B operand of S @ .
|
| 1369 |
+
# qv = orth(S S^T q0): the intermediate orthonormalization does not change the span (as in the baseline kernel)
|
| 1370 |
+
yv = tmem_ld8(tmY + lane_off)
|
| 1371 |
+
y4 = cute.make_rmem_tensor(4, Float32)
|
| 1372 |
+
for rp in cutlass.range_constexpr(2):
|
| 1373 |
+
y4[2 * rp], y4[2 * rp + 1] = fadd2(yv[2 * rp], yv[2 * rp + 1], yv[2 * rp + 4], yv[2 * rp + 5])
|
| 1374 |
+
a, b = sw32_row(qb, t)
|
| 1375 |
+
sts64(a, f2h2(y4[0], y4[1]), f2h2(y4[2], y4[3])) # B columns 4-7 (never read) keep stale bytes
|
| 1376 |
+
tc_before()
|
| 1377 |
+
named_bar(bar, 128)
|
| 1378 |
+
if leader:
|
| 1379 |
+
fence_async_smem()
|
| 1380 |
+
tc_after()
|
| 1381 |
+
with cute.arch.elect_one():
|
| 1382 |
+
mma8_f16(tmY, st >> Uint32(4), qb >> Uint32(4), mbar_g, "0x4000404000010000", [0, 2, 4, 6, 1024, 1026, 1028, 1030], "0xC000401000000000", [0, 32, 64, 96, 128, 160, 192, 224], "0x08030010")
|
| 1383 |
+
mbar_wait(mbar_g, mph)
|
| 1384 |
+
mph = mph ^ Uint32(1)
|
| 1385 |
+
tc_after()
|
| 1386 |
+
# ---------------------------------------------------------- P4: CholeskyQR2 of Y2 = S S^T q0 (one row per thread); W = S^T Q1 overlaps pass 2
|
| 1387 |
+
y2v = tmem_ld4(tmY + lane_off) # Y1 has no low part: columns 4-7 of S Y1 are zero
|
| 1388 |
+
y4 = cute.make_rmem_tensor(4, Float32)
|
| 1389 |
+
for r in cutlass.range_constexpr(4):
|
| 1390 |
+
y4[r] = y2v[r]
|
| 1391 |
+
tc_before()
|
| 1392 |
+
gram_partial_store(y4, lane, gw, ys, 0)
|
| 1393 |
+
named_bar(bar, 128)
|
| 1394 |
+
cf1 = cute.make_rmem_tensor(10, Float32)
|
| 1395 |
+
bad, good = gram_chol(ys, 0, cf1, lane, early_exit)
|
| 1396 |
+
if not bad:
|
| 1397 |
+
tri_apply(cf1, y4)
|
| 1398 |
+
qh01 = f2h2(y4[0], y4[1])
|
| 1399 |
+
qh23 = f2h2(y4[2], y4[3])
|
| 1400 |
+
a, b = sw32_row(qb, t)
|
| 1401 |
+
sts64(a, qh01, qh23)
|
| 1402 |
+
if not good:
|
| 1403 |
+
gram_partial_store(y4, lane, gw, ys, 1)
|
| 1404 |
+
named_bar(bar, 128)
|
| 1405 |
+
if leader:
|
| 1406 |
+
fence_async_smem()
|
| 1407 |
+
tc_after()
|
| 1408 |
+
with cute.arch.elect_one():
|
| 1409 |
+
mma8_f16(tmY, st >> Uint32(4), qb >> Uint32(4), mbar_g, "0x4000404004000000", [0, 128, 256, 384, 512, 640, 768, 896], "0xC000401000000000", [0, 32, 64, 96, 128, 160, 192, 224], "0x08038010")
|
| 1410 |
+
# a well-conditioned first pass is already orthonormal far below the fp16 rounding of q: R2 = I
|
| 1411 |
+
cf2 = cute.make_rmem_tensor(10, Float32)
|
| 1412 |
+
for i in cutlass.range_constexpr(10):
|
| 1413 |
+
cf2[i] = Float32(1.0) if i in (0, 2, 5, 9) else Float32(0.0)
|
| 1414 |
+
if not good:
|
| 1415 |
+
unused_b, unused_g = gram_chol(ys, 1, cf2, lane, early_exit)
|
| 1416 |
+
tri_apply(cf2, y4)
|
| 1417 |
+
qh01 = f2h2(y4[0], y4[1])
|
| 1418 |
+
qh23 = f2h2(y4[2], y4[3])
|
| 1419 |
+
# half 0: q_new row -> fp16, A of the E product
|
| 1420 |
+
qnf = cute.make_rmem_tensor(4, Float32)
|
| 1421 |
+
qnf[0], qnf[1] = h2f2(qh01)
|
| 1422 |
+
qnf[2], qnf[3] = h2f2(qh23)
|
| 1423 |
+
qrow = head_b + Int64(17408 + 256) + Int64(2) * Int64(t)
|
| 1424 |
+
stg16(qrow, qh01)
|
| 1425 |
+
stg16_hi(qrow + Int64(512), qh01)
|
| 1426 |
+
stg16(qrow + Int64(1024), qh23)
|
| 1427 |
+
stg16_hi(qrow + Int64(1536), qh23)
|
| 1428 |
+
a, b = sw32_row(ao, t)
|
| 1429 |
+
sts128(a, qnf[0].bitcast(Uint32), qnf[1].bitcast(Uint32), qnf[2].bitcast(Uint32), qnf[3].bitcast(Uint32))
|
| 1430 |
+
sts128(b, Uint32(0), Uint32(0), Uint32(0), Uint32(0))
|
| 1431 |
+
# ---------------------------------------------------------- P5: u = W R^-1, E = S - q^T u (in TMEM)
|
| 1432 |
+
mbar_wait(mbar_g, mph)
|
| 1433 |
+
mph = mph ^ Uint32(1)
|
| 1434 |
+
tc_after()
|
| 1435 |
+
if t == 0:
|
| 1436 |
+
mbar_arrive(empty0 + Uint32(8) * s.to(Uint32)) # the fp16 copy of S has been read by all products
|
| 1437 |
+
|
| 1438 |
+
wv = tmem_ld4(tmY + lane_off) # Q1 has no low part: columns 4-7 of W are zero
|
| 1439 |
+
for r in cutlass.range_constexpr(4):
|
| 1440 |
+
y4[r] = wv[r]
|
| 1441 |
+
tmem_st8_nw(tmS + lane_off + Uint32(112), [tailS[i] for i in range(8)])
|
| 1442 |
+
tmem_wait_st()
|
| 1443 |
+
if not good:
|
| 1444 |
+
tri_apply(cf2, y4)
|
| 1445 |
+
un = cute.make_rmem_tensor(4, Float32)
|
| 1446 |
+
urow = head_b + Int64(17408) + Int64(2) * Int64(t)
|
| 1447 |
+
for rp in cutlass.range_constexpr(2):
|
| 1448 |
+
ua, ub = fmul2(y4[2 * rp], y4[2 * rp + 1], isc, isc)
|
| 1449 |
+
uh = f2h2(ua, ub)
|
| 1450 |
+
stg16(urow + Int64(1024 * rp), uh)
|
| 1451 |
+
stg16_hi(urow + Int64(1024 * rp + 512), uh)
|
| 1452 |
+
ua, ub = h2f2(uh)
|
| 1453 |
+
un[2 * rp], un[2 * rp + 1] = fmul2(ua, ub, -sc, -sc)
|
| 1454 |
+
a, b = sw32_row(bo, t)
|
| 1455 |
+
sts128(a, un[0].bitcast(Uint32), un[1].bitcast(Uint32), un[2].bitcast(Uint32), un[3].bitcast(Uint32))
|
| 1456 |
+
else:
|
| 1457 |
+
# Recompute the high-state projection, correct it with S_lo^T q0, then redo QR_k.
|
| 1458 |
+
named_bar(bar, 128)
|
| 1459 |
+
tl8 = tmem_ld8(tmS + lane_off + Uint32(120))
|
| 1460 |
+
tfull = [tailS[i] for i in range(8)] + tl8
|
| 1461 |
+
for i in cutlass.range_constexpr(4):
|
| 1462 |
+
sts128(au + Uint32(16) * t.to(Uint32) + Uint32(2048 * i),
|
| 1463 |
+
tfull[4 * i].bitcast(Uint32), tfull[4 * i + 1].bitcast(Uint32),
|
| 1464 |
+
tfull[4 * i + 2].bitcast(Uint32), tfull[4 * i + 3].bitcast(Uint32))
|
| 1465 |
+
# S_hi^T q0 again from the shared copy (still S_hi), then an empty commit keeps the number of
|
| 1466 |
+
# MMA-barrier phases of this path even
|
| 1467 |
+
tc_before()
|
| 1468 |
+
named_bar(bar, 128)
|
| 1469 |
+
if leader:
|
| 1470 |
+
tc_after()
|
| 1471 |
+
with cute.arch.elect_one():
|
| 1472 |
+
mma8_f16(tmY, st >> Uint32(4), q0b >> Uint32(4), mbar_g, "0x4000404004000000", [0, 128, 256, 384, 512, 640, 768, 896], "0x0000400000080000", [0, 16, 32, 48, 64, 80, 96, 112], "0x08038010")
|
| 1473 |
+
mbar_wait(mbar_g, mph)
|
| 1474 |
+
mph = mph ^ Uint32(1)
|
| 1475 |
+
if leader:
|
| 1476 |
+
with cute.arch.elect_one():
|
| 1477 |
+
tcgen05.commit(cute.make_ptr(Uint64, mbar_g, cute.AddressSpace.smem))
|
| 1478 |
+
mbar_wait(mbar_g, mph)
|
| 1479 |
+
mph = mph ^ Uint32(1)
|
| 1480 |
+
tc_after()
|
| 1481 |
+
write_state_part(st, tmS, lane_off, t, tx7, au, True)
|
| 1482 |
+
tc_before()
|
| 1483 |
+
named_bar(bar, 128)
|
| 1484 |
+
if leader:
|
| 1485 |
+
fence_async_smem()
|
| 1486 |
+
tc_after()
|
| 1487 |
+
with cute.arch.elect_one():
|
| 1488 |
+
mma8_f16(tmY, st >> Uint32(4), q0b >> Uint32(4), mbar_g, "0x4000404004000000", [0, 128, 256, 384, 512, 640, 768, 896], "0x0000400000080000", [0, 16, 32, 48, 64, 80, 96, 112], "0x08038010", True)
|
| 1489 |
+
mbar_wait(mbar_g, mph)
|
| 1490 |
+
mph = mph ^ Uint32(1)
|
| 1491 |
+
tc_after()
|
| 1492 |
+
yv = tmem_ld8(tmY + lane_off)
|
| 1493 |
+
for rp in cutlass.range_constexpr(2):
|
| 1494 |
+
ya, yb = fadd2(yv[2 * rp], yv[2 * rp + 1], yv[2 * rp + 4], yv[2 * rp + 5])
|
| 1495 |
+
y4[2 * rp] = ya
|
| 1496 |
+
y4[2 * rp + 1] = yb
|
| 1497 |
+
mgs_rows(y4, lane, gw, ys, bar)
|
| 1498 |
+
h01, l01 = half_split2(y4[0], y4[1])
|
| 1499 |
+
h23, l23 = half_split2(y4[2], y4[3])
|
| 1500 |
+
a, b = sw32_row(qb, t)
|
| 1501 |
+
sts128(a, h01, h23, l01, l23)
|
| 1502 |
+
tc_before()
|
| 1503 |
+
named_bar(bar, 128)
|
| 1504 |
+
if leader:
|
| 1505 |
+
fence_async_smem()
|
| 1506 |
+
tc_after()
|
| 1507 |
+
with cute.arch.elect_one():
|
| 1508 |
+
mma8_f16(tmY, st >> Uint32(4), qb >> Uint32(4), mbar_g, "0x4000404000010000", [0, 2, 4, 6, 1024, 1026, 1028, 1030], "0xC000401000000000", [0, 32, 64, 96, 128, 160, 192, 224], "0x08030010")
|
| 1509 |
+
mbar_wait(mbar_g, mph)
|
| 1510 |
+
mph = mph ^ Uint32(1)
|
| 1511 |
+
tc_after()
|
| 1512 |
+
# S_lo @ Qk is in Y; restore S_hi and accumulate its contribution into Y.
|
| 1513 |
+
write_state_part(st, tmS, lane_off, t, tx7, au, False)
|
| 1514 |
+
tc_before()
|
| 1515 |
+
named_bar(bar, 128)
|
| 1516 |
+
if leader:
|
| 1517 |
+
fence_async_smem()
|
| 1518 |
+
tc_after()
|
| 1519 |
+
with cute.arch.elect_one():
|
| 1520 |
+
mma8_f16(tmY, st >> Uint32(4), qb >> Uint32(4), mbar_g, "0x4000404000010000", [0, 2, 4, 6, 1024, 1026, 1028, 1030], "0xC000401000000000", [0, 32, 64, 96, 128, 160, 192, 224], "0x08030010", True)
|
| 1521 |
+
mbar_wait(mbar_g, mph)
|
| 1522 |
+
mph = mph ^ Uint32(1)
|
| 1523 |
+
tc_after()
|
| 1524 |
+
yv = tmem_ld8(tmY + lane_off)
|
| 1525 |
+
for rp in cutlass.range_constexpr(2):
|
| 1526 |
+
ya, yb = fadd2(yv[2 * rp], yv[2 * rp + 1], yv[2 * rp + 4], yv[2 * rp + 5])
|
| 1527 |
+
y4[2 * rp] = ya
|
| 1528 |
+
y4[2 * rp + 1] = yb
|
| 1529 |
+
mgs_rows(y4, lane, gw, ys, bar)
|
| 1530 |
+
h01, l01 = half_split2(y4[0], y4[1])
|
| 1531 |
+
h23, l23 = half_split2(y4[2], y4[3])
|
| 1532 |
+
a, b = sw32_row(qb, t)
|
| 1533 |
+
sts128(a, h01, h23, l01, l23)
|
| 1534 |
+
gram_partial_store(y4, lane, gw, ys, 1)
|
| 1535 |
+
named_bar(bar, 128)
|
| 1536 |
+
if leader:
|
| 1537 |
+
fence_async_smem()
|
| 1538 |
+
tc_after()
|
| 1539 |
+
with cute.arch.elect_one():
|
| 1540 |
+
mma8_f16(tmY, st >> Uint32(4), qb >> Uint32(4), mbar_g, "0x4000404004000000", [0, 128, 256, 384, 512, 640, 768, 896], "0xC000401000000000", [0, 32, 64, 96, 128, 160, 192, 224], "0x08038010")
|
| 1541 |
+
cf2 = cute.make_rmem_tensor(10, Float32)
|
| 1542 |
+
unused_b, unused_g = gram_chol(ys, 1, cf2, lane, early_exit)
|
| 1543 |
+
tri_apply(cf2, y4)
|
| 1544 |
+
# half 0: q_new row -> fp16, A of the E product
|
| 1545 |
+
qnf = cute.make_rmem_tensor(4, Float32)
|
| 1546 |
+
for r in cutlass.range_constexpr(4):
|
| 1547 |
+
qh = f2h(y4[r])
|
| 1548 |
+
qnf[r] = h2f(qh)
|
| 1549 |
+
stg16(head_b + Int64(17408 + 512 * r + 256) + Int64(2) * Int64(t), qh)
|
| 1550 |
+
a, b = sw32_row(ao, t)
|
| 1551 |
+
sts128(a, qnf[0].bitcast(Uint32), qnf[1].bitcast(Uint32), qnf[2].bitcast(Uint32), qnf[3].bitcast(Uint32))
|
| 1552 |
+
sts128(b, Uint32(0), Uint32(0), Uint32(0), Uint32(0))
|
| 1553 |
+
# ---------------------------------------------------------- P5: u = W R^-1, E = S - q^T u (in TMEM)
|
| 1554 |
+
mbar_wait(mbar_g, mph)
|
| 1555 |
+
mph = mph ^ Uint32(1)
|
| 1556 |
+
tc_after()
|
| 1557 |
+
# W_hi = S_hi^T Q1 has finished. Accumulate W_lo before releasing the input stage.
|
| 1558 |
+
write_state_part(st, tmS, lane_off, t, tx7, au, True)
|
| 1559 |
+
tc_before()
|
| 1560 |
+
named_bar(bar, 128)
|
| 1561 |
+
if leader:
|
| 1562 |
+
fence_async_smem()
|
| 1563 |
+
tc_after()
|
| 1564 |
+
with cute.arch.elect_one():
|
| 1565 |
+
mma8_f16(tmY, st >> Uint32(4), qb >> Uint32(4), mbar_g, "0x4000404004000000", [0, 128, 256, 384, 512, 640, 768, 896], "0xC000401000000000", [0, 32, 64, 96, 128, 160, 192, 224], "0x08038010", True)
|
| 1566 |
+
mbar_wait(mbar_g, mph)
|
| 1567 |
+
mph = mph ^ Uint32(1)
|
| 1568 |
+
tc_after()
|
| 1569 |
+
if t == 0:
|
| 1570 |
+
mbar_arrive(empty0 + Uint32(8) * s.to(Uint32)) # the fp16 copy of S has been read by all products
|
| 1571 |
+
|
| 1572 |
+
yv = tmem_ld8(tmY + lane_off)
|
| 1573 |
+
for rp in cutlass.range_constexpr(2):
|
| 1574 |
+
ya, yb = fadd2(yv[2 * rp], yv[2 * rp + 1], yv[2 * rp + 4], yv[2 * rp + 5])
|
| 1575 |
+
y4[2 * rp] = ya
|
| 1576 |
+
y4[2 * rp + 1] = yb
|
| 1577 |
+
tail_restore = []
|
| 1578 |
+
for i in cutlass.range_constexpr(4):
|
| 1579 |
+
tail_restore += lds128f(au + Uint32(16) * t.to(Uint32) + Uint32(2048 * i))
|
| 1580 |
+
tmem_st16_nw(tmS + lane_off + Uint32(112), tail_restore)
|
| 1581 |
+
tmem_wait_st()
|
| 1582 |
+
tri_apply(cf2, y4)
|
| 1583 |
+
un = cute.make_rmem_tensor(4, Float32)
|
| 1584 |
+
for r in cutlass.range_constexpr(4):
|
| 1585 |
+
uu = y4[r] * isc
|
| 1586 |
+
uh = f2h(uu)
|
| 1587 |
+
stg16(head_b + Int64(17408 + 512 * r) + Int64(2) * Int64(t), uh)
|
| 1588 |
+
un[r] = h2f(uh) * (-sc)
|
| 1589 |
+
a, b = sw32_row(bo, t)
|
| 1590 |
+
sts128(a, un[0].bitcast(Uint32), un[1].bitcast(Uint32), un[2].bitcast(Uint32), un[3].bitcast(Uint32))
|
| 1591 |
+
tc_before()
|
| 1592 |
+
named_bar(bar, 128)
|
| 1593 |
+
if leader:
|
| 1594 |
+
fence_async_smem()
|
| 1595 |
+
tc_after()
|
| 1596 |
+
with cute.arch.elect_one():
|
| 1597 |
+
mma_list(tmS, mbar_g, [ao >> Uint32(4), bo >> Uint32(4)], [("tf32", 0, "0xC000401000010000", 1, "0xC000401000010000", "0x08200910", True)])
|
| 1598 |
+
mbar_wait(mbar_g, mph)
|
| 1599 |
+
mph = mph ^ Uint32(1)
|
| 1600 |
+
tc_after()
|
| 1601 |
+
# ---------------------------------------------------------- P6: column sums of |E|
|
| 1602 |
+
part = cute.make_rmem_tensor(32, Float32)
|
| 1603 |
+
lane_off2 = (Uint32(32) * gw.to(Uint32) + Uint32(16)) << Uint32(16)
|
| 1604 |
+
vab = tmem_wait_ld(tmem_ld16x256x4_nw(tmS + lane_off) + tmem_ld16x256x4_nw(tmS + lane_off2))
|
| 1605 |
+
for blk in cutlass.range_constexpr(4):
|
| 1606 |
+
va = vab[0:16]
|
| 1607 |
+
vb = vab[16:32]
|
| 1608 |
+
if cutlass.const_expr(blk < 3):
|
| 1609 |
+
nxt = tmem_ld16x256x4_nw(tmS + lane_off + Uint32(32 * (blk + 1))) + tmem_ld16x256x4_nw(tmS + lane_off2 + Uint32(32 * (blk + 1)))
|
| 1610 |
+
for m in cutlass.range_constexpr(4):
|
| 1611 |
+
a0, a1 = fadd2(cute.math.abs(va[m * 4]), cute.math.abs(va[m * 4 + 1]),
|
| 1612 |
+
cute.math.abs(va[m * 4 + 2]), cute.math.abs(va[m * 4 + 3]))
|
| 1613 |
+
b0, b1 = fadd2(cute.math.abs(vb[m * 4]), cute.math.abs(vb[m * 4 + 1]),
|
| 1614 |
+
cute.math.abs(vb[m * 4 + 2]), cute.math.abs(vb[m * 4 + 3]))
|
| 1615 |
+
part[blk * 8 + m * 2], part[blk * 8 + m * 2 + 1] = fadd2(a0, a1, b0, b1)
|
| 1616 |
+
if cutlass.const_expr(blk < 3):
|
| 1617 |
+
vab = tmem_wait_ld(nxt)
|
| 1618 |
+
# thread (g8 = lane // 4, q = lane % 4) holds columns 8 m' + 2 q + c, m' = blk * 4 + m (index blk*8+m*2+c)
|
| 1619 |
+
# transposed reduction over g8 (xor 16, 8, 4) on fp16x2 pairs of adjacent columns: keep halves of the m'
|
| 1620 |
+
# range. Every column sum is < 128 max|S| < 2^14 (Cauchy-Schwarz on the projected column), so fp16 cannot
|
| 1621 |
+
# overflow; its rounding only perturbs the column scale, which stays consistent with the stored codes.
|
| 1622 |
+
ph = cute.make_rmem_tensor(16, Uint32)
|
| 1623 |
+
for j in cutlass.range_constexpr(16):
|
| 1624 |
+
ph[j] = f2h2(part[2 * j], part[2 * j + 1])
|
| 1625 |
+
cnt = 16
|
| 1626 |
+
for lvl in cutlass.range_constexpr(3):
|
| 1627 |
+
msk = 16 >> lvl
|
| 1628 |
+
half = cnt // 2
|
| 1629 |
+
upper = (lane & msk) != 0
|
| 1630 |
+
for i in cutlass.range_constexpr(half):
|
| 1631 |
+
send = ph[half + i]
|
| 1632 |
+
keep = ph[i]
|
| 1633 |
+
if upper:
|
| 1634 |
+
send = ph[i]
|
| 1635 |
+
keep = ph[half + i]
|
| 1636 |
+
ph[i] = hadd2(keep, shfl_bfly(send.bitcast(Float32), msk).bitcast(Uint32))
|
| 1637 |
+
cnt = half
|
| 1638 |
+
part[0], part[1] = h2f2(ph[0])
|
| 1639 |
+
part[2], part[3] = h2f2(ph[1])
|
| 1640 |
+
# now part[0..3] = sums for m'-group selected by lane bits (4,3,2) and columns 2q + c
|
| 1641 |
+
# m' index: bit4 (lane&16) selected the upper half of 16 m', bit3 -> next, bit2 -> next
|
| 1642 |
+
sel = ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2
|
| 1643 |
+
for i in cutlass.range_constexpr(4):
|
| 1644 |
+
mp = sel + i // 2
|
| 1645 |
+
col = mp * 8 + (lane % 4) * 2 + (i % 2)
|
| 1646 |
+
sts32(cpg + Uint32(512) * gw.to(Uint32) + Uint32(4) * col.to(Uint32), part[i].bitcast(Uint32))
|
| 1647 |
+
named_bar(bar, 128)
|
| 1648 |
+
csum = Float32(0)
|
| 1649 |
+
for w4 in cutlass.range_constexpr(4):
|
| 1650 |
+
csum = csum + lds32f(cpg + Uint32(512 * w4) + Uint32(4) * t.to(Uint32))
|
| 1651 |
+
# sk' = max(sqrt(mean |E|), eps) and its reciprocal from one rsqrt (sqrt(x) = x rsqrt(x); x = 0 -> eps)
|
| 1652 |
+
xm = csum * Float32(1.0 / 128.0)
|
| 1653 |
+
rq = rsqrt_approx(xm)
|
| 1654 |
+
skp = cute.arch.fmax(xm * rq, Float32(EPS) * sc_h)
|
| 1655 |
+
stg32(head_b + Int64(16384) + Int64(4) * Int64(t), (skp * isc_h).bitcast(Uint32))
|
| 1656 |
+
sts32(rsg + Uint32(4) * t.to(Uint32), cute.arch.fmin(rq, Float32(1.0 / EPS) * isc_h).bitcast(Uint32))
|
| 1657 |
+
named_bar(bar, 128)
|
| 1658 |
+
# ---------------------------------------------------------- P7: t = E / sk', row max, sv
|
| 1659 |
+
mxa = Float32(0)
|
| 1660 |
+
mxb = Float32(0)
|
| 1661 |
+
mxc = Float32(0)
|
| 1662 |
+
mxd = Float32(0)
|
| 1663 |
+
rcur = []
|
| 1664 |
+
for q4 in cutlass.range_constexpr(4):
|
| 1665 |
+
rcur += lds128f(rsg + Uint32(16 * q4))
|
| 1666 |
+
v = tmem_wait_ld(tmem_ld16_nw(tmS + lane_off))
|
| 1667 |
+
for blk in cutlass.range_constexpr(8):
|
| 1668 |
+
if cutlass.const_expr(blk < 7):
|
| 1669 |
+
nxt = tmem_ld16_nw(tmS + lane_off + Uint32(16 * (blk + 1)))
|
| 1670 |
+
rnxt = []
|
| 1671 |
+
for q4 in cutlass.range_constexpr(4):
|
| 1672 |
+
rnxt += lds128f(rsg + Uint32(4 * ((blk + 1) * 16 + q4 * 4)))
|
| 1673 |
+
tv = []
|
| 1674 |
+
for q4 in cutlass.range_constexpr(4):
|
| 1675 |
+
t0, t1 = fmul2(v[q4 * 4], v[q4 * 4 + 1], rcur[q4 * 4], rcur[q4 * 4 + 1])
|
| 1676 |
+
t2, t3 = fmul2(v[q4 * 4 + 2], v[q4 * 4 + 3], rcur[q4 * 4 + 2], rcur[q4 * 4 + 3])
|
| 1677 |
+
if cutlass.const_expr(q4 % 2 == 0):
|
| 1678 |
+
mxa = maxabs3(mxa, t0, t1)
|
| 1679 |
+
mxb = maxabs3(mxb, t2, t3)
|
| 1680 |
+
else:
|
| 1681 |
+
mxc = maxabs3(mxc, t0, t1)
|
| 1682 |
+
mxd = maxabs3(mxd, t2, t3)
|
| 1683 |
+
tv += [t0, t1, t2, t3]
|
| 1684 |
+
tmem_st16_nw(tmS + lane_off + Uint32(16 * blk), tv)
|
| 1685 |
+
if cutlass.const_expr(blk < 7):
|
| 1686 |
+
v = tmem_wait_ld(nxt)
|
| 1687 |
+
rcur = rnxt
|
| 1688 |
+
tmem_wait_st()
|
| 1689 |
+
mx = cute.arch.fmax(cute.arch.fmax(mxa, mxb), cute.arch.fmax(mxc, mxd))
|
| 1690 |
+
svp = cute.arch.fmax(mx, Float32(EPS) * sc_h)
|
| 1691 |
+
stg32(head_b + Int64(16896) + Int64(4) * Int64(t), (svp * isc_h).bitcast(Uint32))
|
| 1692 |
+
# Hardware reciprocal in the normal range; retain accurate rounding at extreme row scales.
|
| 1693 |
+
rinv = rcp_approx(svp)
|
| 1694 |
+
if (svp <= Float32(1e-20)) | (svp >= Float32(1e20)):
|
| 1695 |
+
rinv = rcp_rn(svp)
|
| 1696 |
+
inv = Float32(127.0) * rinv
|
| 1697 |
+
# ---------------------------------------------------------- P8: codes -> staging (SW128 rows) -> TMA store
|
| 1698 |
+
ctile = au + Uint32(4096) * gw.to(Uint32)
|
| 1699 |
+
if gw >= Int32(2):
|
| 1700 |
+
ctile = ao + Uint32(4096) * (gw - Int32(2)).to(Uint32)
|
| 1701 |
+
cwx = (ctile + Uint32(128) * Uint32(lane)) | (tx7 << Uint32(4))
|
| 1702 |
+
v = tmem_wait_ld(tmem_ld16_nw(tmS + lane_off))
|
| 1703 |
+
for blk in cutlass.range_constexpr(8):
|
| 1704 |
+
if cutlass.const_expr(blk < 7):
|
| 1705 |
+
nxt = tmem_ld16_nw(tmS + lane_off + Uint32(16 * (blk + 1)))
|
| 1706 |
+
wd = cute.make_rmem_tensor(4, Uint32)
|
| 1707 |
+
for q4 in cutlass.range_constexpr(4):
|
| 1708 |
+
x0, x1 = ffma2(v[q4 * 4], v[q4 * 4 + 1], inv, inv, Float32(MAGIC_RND), Float32(MAGIC_RND))
|
| 1709 |
+
x2, x3 = ffma2(v[q4 * 4 + 2], v[q4 * 4 + 3], inv, inv, Float32(MAGIC_RND), Float32(MAGIC_RND))
|
| 1710 |
+
lo = prmt(x0.bitcast(Uint32), x1.bitcast(Uint32), Uint32(0x0040))
|
| 1711 |
+
hi = prmt(x2.bitcast(Uint32), x3.bitcast(Uint32), Uint32(0x0040))
|
| 1712 |
+
wd[q4] = prmt(lo, hi, Uint32(0x5410))
|
| 1713 |
+
sts128(cwx ^ Uint32(16 * blk), wd[0], wd[1], wd[2], wd[3])
|
| 1714 |
+
if cutlass.const_expr(blk < 7):
|
| 1715 |
+
v = tmem_wait_ld(nxt)
|
| 1716 |
+
fence_async_smem()
|
| 1717 |
+
cute.arch.sync_warp()
|
| 1718 |
+
if lane == 0:
|
| 1719 |
+
tma_store_4d(tmap_c32, Int32(0), Int32(32) * gw, hh, slot, ctile)
|
| 1720 |
+
bulk_commit()
|
| 1721 |
+
# next program for this group
|
| 1722 |
+
fph = fph ^ Uint32(1)
|
| 1723 |
+
mbar_wait(full0 + Uint32(8) * s.to(Uint32), fph)
|
| 1724 |
+
pid = lds32(misc0 + Uint32(4) * s.to(Uint32)).to(Int32)
|
| 1725 |
+
if lane == 0:
|
| 1726 |
+
bulk_wait0()
|
| 1727 |
+
tc_before()
|
| 1728 |
+
cute.arch.sync_threads()
|
| 1729 |
+
if warp == 0:
|
| 1730 |
+
allocated = Boolean(True)
|
| 1731 |
+
if cutlass.const_expr(early_exit):
|
| 1732 |
+
allocated = lds32(misc0 + Uint32(4 * (NSTAGE + 1))) != Uint32(0)
|
| 1733 |
+
if allocated:
|
| 1734 |
+
tc_after()
|
| 1735 |
+
tmem_free(tmem_base, 512)
|
| 1736 |
+
tmem_relinquish()
|
| 1737 |
+
|
| 1738 |
+
|
| 1739 |
+
@cute.jit
|
| 1740 |
+
def launch(raw: cute.Pointer, kbp: cute.Pointer, ubp: cute.Pointer, wp: cute.Pointer, pp: cute.Pointer,
|
| 1741 |
+
hcnt: cute.Pointer, idx: cute.Pointer, q0p: cute.Pointer, n: Int32, ns: Int32, tmaps: cute.Pointer,
|
| 1742 |
+
grid: Int32, stream: cuda.CUstream, early_exit: cutlass.Constexpr):
|
| 1743 |
+
flush_kernel(raw, kbp, ubp, wp, pp, hcnt, idx, q0p, n, ns, tmaps, early_exit).launch(
|
| 1744 |
+
grid=(grid, 1, 1), block=(NTHREADS, 1, 1), stream=stream)
|
| 1745 |
+
|
| 1746 |
+
|
| 1747 |
+
# ----------------------------------------------------------------------------------------------
|
| 1748 |
+
# host side
|
| 1749 |
+
# ----------------------------------------------------------------------------------------------
|
| 1750 |
+
_KERNELS = {}
|
| 1751 |
+
|
| 1752 |
+
|
| 1753 |
+
def _ptr(t, dtype=Float32):
|
| 1754 |
+
return make_ptr(dtype, t.data_ptr(), cute.AddressSpace.generic, assumed_align=16)
|
| 1755 |
+
|
| 1756 |
+
|
| 1757 |
+
def _tensor_map(dtype, addr, dims, strides, box):
|
| 1758 |
+
res, tmap = cuda.cuTensorMapEncodeTiled(
|
| 1759 |
+
dtype, len(dims), addr, [cuda.cuuint64_t(d) for d in dims], [cuda.cuuint64_t(s) for s in strides],
|
| 1760 |
+
[cuda.cuuint32_t(b) for b in box], [cuda.cuuint32_t(1)] * len(dims),
|
| 1761 |
+
cuda.CUtensorMapInterleave.CU_TENSOR_MAP_INTERLEAVE_NONE,
|
| 1762 |
+
cuda.CUtensorMapSwizzle.CU_TENSOR_MAP_SWIZZLE_128B,
|
| 1763 |
+
cuda.CUtensorMapL2promotion.CU_TENSOR_MAP_L2_PROMOTION_L2_256B,
|
| 1764 |
+
cuda.CUtensorMapFloatOOBfill.CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE)
|
| 1765 |
+
assert res == cuda.CUresult.CUDA_SUCCESS, res
|
| 1766 |
+
return b''.join(int(x).to_bytes(8, 'little') for x in tmap.opaque)
|
| 1767 |
+
|
| 1768 |
+
|
| 1769 |
+
class Pool:
|
| 1770 |
+
"""Caller-owned state pool (the serving engine's layout). Every (slot, head) owns a 64 KB region of raw;
|
| 1771 |
+
bytes [0,16384) int8 codes [V,K], [16384,16896) fp32 s_k, [16896,17408) fp32 s_v, [17408,19456) fp16
|
| 1772 |
+
Compensator Tokens [R, K+V] (u | q). Slot stride SS words with one spare head; raw starts at OFF words.
|
| 1773 |
+
Slot 0 is reserved (idx 0 = no sequence). kbuf/ubuf/w/p/hcnt are dense [NS, HV, ...] tensors."""
|
| 1774 |
+
|
| 1775 |
+
def __init__(self, num_slots, device="cuda"):
|
| 1776 |
+
NS = self.NS = num_slots
|
| 1777 |
+
self.raw = torch.zeros(NS * SS + OFF, dtype=torch.float32, device=device)
|
| 1778 |
+
st = self.raw.untyped_storage()
|
| 1779 |
+
|
| 1780 |
+
def view(dtype, shape, strides, off):
|
| 1781 |
+
return torch.empty(0, dtype=dtype, device=device).set_(st).as_strided(shape, strides, off)
|
| 1782 |
+
self.codes = view(torch.int8, (NS, HV, V, K), (4 * SS, 4 * V * K, K, 1), 4 * OFF)
|
| 1783 |
+
self.codes32 = view(torch.int32, (NS, HV, V, K // 4), (SS, V * K, K // 4, 1), OFF)
|
| 1784 |
+
self.codes16 = view(torch.int16, (NS, HV, V, K // 2), (2 * SS, 2 * V * K, K // 2, 1), 2 * OFF)
|
| 1785 |
+
self.s_k = view(torch.float32, (NS, HV, K), (SS, V * K, 1), OFF + V * K // 4)
|
| 1786 |
+
self.s_v = view(torch.float32, (NS, HV, V), (SS, V * K, 1), OFF + V * K // 4 + K)
|
| 1787 |
+
self.s_kv = view(torch.float32, (NS, HV, K + V), (SS, V * K, 1), OFF + V * K // 4)
|
| 1788 |
+
self.uq = view(torch.float16, (NS, HV, R, K + V), (2 * SS, 2 * V * K, K + V, 1), 2 * (OFF + V * K // 4 + K + V))
|
| 1789 |
+
self.kbuf = torch.zeros(NS, HV, L, K, dtype=torch.bfloat16, device=device)
|
| 1790 |
+
self.ubuf = torch.zeros(NS, HV, L, V, dtype=torch.bfloat16, device=device)
|
| 1791 |
+
self.w = torch.zeros(NS, HV, L, dtype=torch.float32, device=device)
|
| 1792 |
+
self.p = torch.ones(NS, HV, 1, dtype=torch.float32, device=device)
|
| 1793 |
+
self.hcnt = torch.zeros(NS, HV, dtype=torch.int32, device=device)
|
| 1794 |
+
dt = cuda.CUtensorMapDataType
|
| 1795 |
+
m_codes = _tensor_map(dt.CU_TENSOR_MAP_DATA_TYPE_UINT8, self.raw.data_ptr() + 4 * OFF,
|
| 1796 |
+
[128, 128, HV + 1, NS], [128, 65536, 4 * SS], [128, 128, 1, 1])
|
| 1797 |
+
m_kb = _tensor_map(dt.CU_TENSOR_MAP_DATA_TYPE_UINT16, self.kbuf.data_ptr(),
|
| 1798 |
+
[64, 16, 2, NS * HV], [256, 128, 4096], [64, 16, 2, 1])
|
| 1799 |
+
m_ub = _tensor_map(dt.CU_TENSOR_MAP_DATA_TYPE_UINT16, self.ubuf.data_ptr(),
|
| 1800 |
+
[64, 16, 2, NS * HV], [256, 128, 4096], [64, 16, 2, 1])
|
| 1801 |
+
m_c32 = _tensor_map(dt.CU_TENSOR_MAP_DATA_TYPE_UINT8, self.raw.data_ptr() + 4 * OFF,
|
| 1802 |
+
[128, 128, HV + 1, NS], [128, 65536, 4 * SS], [128, 32, 1, 1])
|
| 1803 |
+
self.tmaps = torch.frombuffer(bytearray(m_codes + m_kb + m_c32 + m_ub), dtype=torch.uint8).to(device)
|
| 1804 |
+
dev = self.raw.device
|
| 1805 |
+
self.sms = torch.cuda.get_device_properties(dev).multi_processor_count
|
| 1806 |
+
key = dev.index
|
| 1807 |
+
with torch.cuda.device(dev):
|
| 1808 |
+
if key not in _KERNELS:
|
| 1809 |
+
stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)
|
| 1810 |
+
args = (_ptr(self.raw), _ptr(self.kbuf, BFloat16), _ptr(self.ubuf, BFloat16), _ptr(self.w), _ptr(self.p),
|
| 1811 |
+
_ptr(self.hcnt, Int32), _ptr(self.hcnt, Int32), _ptr(self.w), Int32(1), Int32(1), _ptr(self.tmaps, Int8),
|
| 1812 |
+
Int32(1), stream)
|
| 1813 |
+
_KERNELS[key] = tuple(cute.compile(launch, *args, flag, options="--enable-tvm-ffi") for flag in (True, False))
|
| 1814 |
+
self.kernel, self.small_kernel = _KERNELS[key]
|
| 1815 |
+
|
| 1816 |
+
|
| 1817 |
+
def flush_inplace(pool, idx, q0):
|
| 1818 |
+
"""Flush every (idx[n], head) whose fill counter equals L (idx 0 = skip): new checkpoint in place, w = 0, p = 1."""
|
| 1819 |
+
n = idx.numel()
|
| 1820 |
+
if n == 0:
|
| 1821 |
+
return
|
| 1822 |
+
if idx.dtype != torch.int32 or not idx.is_contiguous() or idx.data_ptr() % 16:
|
| 1823 |
+
idx = idx.to(torch.int32).contiguous().clone()
|
| 1824 |
+
if q0.dtype != torch.float32 or not q0.is_contiguous() or q0.data_ptr() % 16:
|
| 1825 |
+
q0 = q0.to(torch.float32).contiguous().clone()
|
| 1826 |
+
grid = min(pool.sms, n * HV)
|
| 1827 |
+
with torch.cuda.device(pool.raw.device):
|
| 1828 |
+
stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)
|
| 1829 |
+
kernel = pool.small_kernel if n * HV < 16 * pool.sms else pool.kernel
|
| 1830 |
+
kernel(_ptr(pool.raw), _ptr(pool.kbuf, BFloat16), _ptr(pool.ubuf, BFloat16), _ptr(pool.w), _ptr(pool.p),
|
| 1831 |
+
_ptr(pool.hcnt, Int32), _ptr(idx, Int32), _ptr(q0), Int32(n), Int32(pool.NS), _ptr(pool.tmaps, Int8), Int32(grid), stream)
|
| 1832 |
+
|
| 1833 |
+
|
| 1834 |
+
_POOLS = {}
|
| 1835 |
+
|
| 1836 |
+
|
| 1837 |
+
def run(codes, s_k, s_v, u, q, kbuf, ubuf, w, p, q0):
|
| 1838 |
+
"""Functional form: pack into a pool, flush, return the new checkpoint as fresh tensors."""
|
| 1839 |
+
B = codes.shape[0]
|
| 1840 |
+
key = (B, codes.device)
|
| 1841 |
+
pool = _POOLS.get(key)
|
| 1842 |
+
if pool is None:
|
| 1843 |
+
pool = _POOLS[key] = Pool(B + 8, codes.device)
|
| 1844 |
+
sl = slice(1, B + 1)
|
| 1845 |
+
pool.codes[sl] = codes
|
| 1846 |
+
pool.s_k[sl] = s_k
|
| 1847 |
+
pool.s_v[sl] = s_v
|
| 1848 |
+
pool.uq[sl, :, :, :K] = u
|
| 1849 |
+
pool.uq[sl, :, :, K:] = q
|
| 1850 |
+
pool.kbuf[sl] = kbuf
|
| 1851 |
+
pool.ubuf[sl] = ubuf
|
| 1852 |
+
pool.w[sl] = w
|
| 1853 |
+
pool.p[sl, :, 0] = p
|
| 1854 |
+
pool.hcnt.zero_()
|
| 1855 |
+
pool.hcnt[sl] = L
|
| 1856 |
+
flush_inplace(pool, torch.arange(1, B + 1, dtype=torch.int32, device=codes.device), q0.contiguous())
|
| 1857 |
+
return (pool.codes[sl].clone(), pool.s_k[sl].clone(), pool.s_v[sl].clone(),
|
| 1858 |
+
pool.uq[sl, :, :, :K].clone(), pool.uq[sl, :, :, K:].clone())
|
build/torch-cuda/_kda.py
ADDED
|
@@ -0,0 +1,1242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
"""CuTe DSL window flush for the caller-owned LeapQuant KDA pool (v2 layout).
|
| 3 |
+
|
| 4 |
+
One persistent CTA of four warps per program slot, four CTAs per SM. The fp32 state lives in tensor memory with
|
| 5 |
+
its key columns permuted (TMEM column n holds key pi(n)) so that the row-wise passes, the column reduction and the
|
| 6 |
+
code stores all use cheap register layouts. Inputs arrive by bulk/TMA copies, the new codes leave by a TMA store.
|
| 7 |
+
The start basis of the subspace iteration enters its first skinny product as fp16 high + low parts.
|
| 8 |
+
Pool setup compiles three variants that differ only in L2 eviction hints and, for calls of up to 64 sequences, in the
|
| 9 |
+
startup (the first window is sent before the setup barriers) and in where the window resets are issued.
|
| 10 |
+
"""
|
| 11 |
+
import torch
|
| 12 |
+
import cutlass
|
| 13 |
+
import cutlass.cute as cute
|
| 14 |
+
from cutlass import Float32, Float16, BFloat16, Int8, Int32, Int64, Uint64, TFloat32
|
| 15 |
+
from cutlass.cute.runtime import make_ptr
|
| 16 |
+
from cutlass.utils import SmemAllocator
|
| 17 |
+
from cutlass._mlir.dialects import llvm, arith
|
| 18 |
+
from cutlass._mlir import ir
|
| 19 |
+
from cutlass.cutlass_dsl import dsl_user_op, T
|
| 20 |
+
from cutlass.cute.nvgpu import tcgen05 as tc
|
| 21 |
+
from cutlass.cute.nvgpu import cpasync
|
| 22 |
+
from cuda.bindings import driver as cuda
|
| 23 |
+
|
| 24 |
+
HV, K, V, L, R = 32, 128, 128, 16, 4
|
| 25 |
+
SS, OFF = 33 * V * K, 12288
|
| 26 |
+
CTAS_PER_SM = 4
|
| 27 |
+
MAXDUE = 128
|
| 28 |
+
TAU = 2.0 ** -9 # one CholeskyQR pass suffices when every normalized pivot exceeds TAU
|
| 29 |
+
|
| 30 |
+
# shared-memory map (bytes from a 1024-aligned base)
|
| 31 |
+
SF = 0 # 32 KB: fp16 state copy | old-factor operands | codes in (upper half) | |E| bf16 | codes out
|
| 32 |
+
KB = 32768 # raw kbuf -> keys hi operand
|
| 33 |
+
GB = 36864 # raw gbuf -> keys lo operand
|
| 34 |
+
UB = 40960 # raw ubuf -> window A operand
|
| 35 |
+
META = 45056 # s_k (512) | s_v (512) | uq (2048)
|
| 36 |
+
PCM = 48128 # pcum (512)
|
| 37 |
+
WGT = 48640 # w (64)
|
| 38 |
+
SKB = 48768 # skinny B operand, 128 x 8 halves
|
| 39 |
+
QVB = 50816 # Q rows (fp32 128 x 4) for the QR
|
| 40 |
+
ONES = 52864 # 1 KB of fp16 ones: source of the bulk gbuf window resets
|
| 41 |
+
SKP = 53888 # per-TMEM-column scale (skpc' then 1/sk')
|
| 42 |
+
BND = 54400 # bound partials 4 warps x 8
|
| 43 |
+
DUE = 54528 # due list
|
| 44 |
+
CNT = DUE + 4 * MAXDUE
|
| 45 |
+
MBAR = CNT + 16 # 3 mbarriers: mma, window, codes
|
| 46 |
+
TMH = MBAR + 24
|
| 47 |
+
SEEDB = (TMH + 8 + 127) // 128 * 128 # conditioned start basis as the first skinny B operand (128 x 8 halves)
|
| 48 |
+
SMEM_BYTES = SEEDB + 2048
|
| 49 |
+
WIN_BYTES = 4096 * 3 + 3072 + 512 + 64
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def encode_map(ptr, dims, strides, box, dtype, swizzle, device):
|
| 53 |
+
status, mapping = cuda.cuTensorMapEncodeTiled(dtype, len(dims), ptr,
|
| 54 |
+
tuple(cuda.cuuint64_t(x) for x in dims), tuple(cuda.cuuint64_t(x) for x in strides),
|
| 55 |
+
tuple(cuda.cuuint32_t(x) for x in box), tuple(cuda.cuuint32_t(1) for _ in dims),
|
| 56 |
+
cuda.CUtensorMapInterleave.CU_TENSOR_MAP_INTERLEAVE_NONE, swizzle,
|
| 57 |
+
cuda.CUtensorMapL2promotion.CU_TENSOR_MAP_L2_PROMOTION_L2_128B,
|
| 58 |
+
cuda.CUtensorMapFloatOOBfill.CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE)
|
| 59 |
+
assert status == cuda.CUresult.CUDA_SUCCESS, status
|
| 60 |
+
return torch.tensor([int(x) for x in mapping.opaque], dtype=torch.uint64, device=device)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _asm(text, cons, args=(), loc=None, ip=None, ret=None):
|
| 64 |
+
return llvm.inline_asm(ret, list(args), text, cons, has_side_effects=True, is_align_stack=False,
|
| 65 |
+
asm_dialect=llvm.AsmDialect.AD_ATT, loc=loc, ip=ip)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dsl_user_op
|
| 69 |
+
def tma_acquire(desc, *, loc=None, ip=None):
|
| 70 |
+
_asm('fence.proxy.tensormap::generic.acquire.gpu [$0],128;', 'l,~{memory}', [Int64(desc).ir_value(loc=loc, ip=ip)], loc, ip)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@dsl_user_op
|
| 74 |
+
def tma_load_codes(dst, desc, head, slot, mbar, *, loc=None, ip=None):
|
| 75 |
+
args = [Int32(dst).ir_value(loc=loc, ip=ip), Int64(desc).ir_value(loc=loc, ip=ip), Int32(head).ir_value(loc=loc, ip=ip),
|
| 76 |
+
Int32(slot).ir_value(loc=loc, ip=ip), Int32(mbar).ir_value(loc=loc, ip=ip)]
|
| 77 |
+
_asm('cp.async.bulk.tensor.4d.shared::cluster.global.tile.mbarrier::complete_tx::bytes [$0], [$1, {0, 0, $2, $3}], [$4];',
|
| 78 |
+
'r,l,r,r,r,~{memory}', args, loc, ip)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@dsl_user_op
|
| 82 |
+
def tma_store_codes(src, desc, head, slot, *, loc=None, ip=None):
|
| 83 |
+
args = [Int64(desc).ir_value(loc=loc, ip=ip), Int32(head).ir_value(loc=loc, ip=ip),
|
| 84 |
+
Int32(slot).ir_value(loc=loc, ip=ip), Int32(src).ir_value(loc=loc, ip=ip)]
|
| 85 |
+
_asm('cp.async.bulk.tensor.4d.global.shared::cta.bulk_group [$0, {0, 0, $1, $2}], [$3];', 'l,r,r,r,~{memory}', args, loc, ip)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@dsl_user_op
|
| 89 |
+
def bulk_load(dst, src, nbytes: int, mbar, fraction: float, *, loc=None, ip=None):
|
| 90 |
+
args = [Int32(dst).ir_value(loc=loc, ip=ip), Int64(src).ir_value(loc=loc, ip=ip), Int32(mbar).ir_value(loc=loc, ip=ip)]
|
| 91 |
+
if fraction is None:
|
| 92 |
+
_asm(f'cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [$0], [$1], {nbytes}, [$2];', 'r,l,r,~{memory}', args, loc, ip)
|
| 93 |
+
else:
|
| 94 |
+
args.append(l2_policy(fraction, loc=loc, ip=ip).ir_value(loc=loc, ip=ip))
|
| 95 |
+
_asm(f'cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [$0], [$1], {nbytes}, [$2], $3;', 'r,l,r,l,~{memory}', args, loc, ip)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@dsl_user_op
|
| 99 |
+
def mbar_expect(mbar, nbytes: int, *, loc=None, ip=None):
|
| 100 |
+
_asm(f'mbarrier.arrive.expect_tx.shared::cta.b64 _, [$0], {nbytes};', 'r,~{memory}', [Int32(mbar).ir_value(loc=loc, ip=ip)], loc, ip)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dsl_user_op
|
| 104 |
+
def mbar_wait(mbar, phase, *, loc=None, ip=None):
|
| 105 |
+
"""mbarrier wait followed by a compiler memory fence (plain loads must not be hoisted above it)."""
|
| 106 |
+
cute.arch.mbarrier_wait(mbar, phase, loc=loc, ip=ip)
|
| 107 |
+
_asm('', '~{memory}', [], loc, ip)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@dsl_user_op
|
| 111 |
+
def mbar_spin(mbar, phase, *, loc=None, ip=None):
|
| 112 |
+
"""mbarrier phase wait as a test_wait spin, then a compiler memory fence. Used for the tensor-core products,
|
| 113 |
+
which complete within a few hundred cycles: the suspending try_wait of cute.arch.mbarrier_wait wakes up late."""
|
| 114 |
+
args = [Int32(mbar).ir_value(loc=loc, ip=ip), Int32(phase).ir_value(loc=loc, ip=ip)]
|
| 115 |
+
_asm('{ .reg .pred p; WAIT_${:uid}: mbarrier.test_wait.parity.shared::cta.b64 p, [$0], $1; @!p bra WAIT_${:uid}; }', 'r,r,~{memory}', args, loc, ip)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@dsl_user_op
|
| 119 |
+
def prefetch_l2(src, nbytes: int, *, loc=None, ip=None):
|
| 120 |
+
_asm(f'cp.async.bulk.prefetch.L2.global [$0], {nbytes};', 'l,~{memory}', [Int64(src).ir_value(loc=loc, ip=ip)], loc, ip)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dsl_user_op
|
| 124 |
+
def bulk_store(dst, src, nbytes: int, fraction: float, *, loc=None, ip=None):
|
| 125 |
+
args = [Int64(dst).ir_value(loc=loc, ip=ip), Int32(src).ir_value(loc=loc, ip=ip)]
|
| 126 |
+
if fraction is None:
|
| 127 |
+
_asm(f'cp.async.bulk.global.shared::cta.bulk_group [$0], [$1], {nbytes};', 'l,r,~{memory}', args, loc, ip)
|
| 128 |
+
else:
|
| 129 |
+
args.append(l2_policy(fraction, loc=loc, ip=ip).ir_value(loc=loc, ip=ip))
|
| 130 |
+
_asm(f'cp.async.bulk.global.shared::cta.bulk_group.L2::cache_hint [$0], [$1], {nbytes}, $2;', 'l,r,l,~{memory}', args, loc, ip)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@dsl_user_op
|
| 134 |
+
def bulk_commit(*, loc=None, ip=None):
|
| 135 |
+
_asm('cp.async.bulk.commit_group;', '~{memory}', [], loc, ip)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@dsl_user_op
|
| 139 |
+
def bulk_wait(*, loc=None, ip=None):
|
| 140 |
+
_asm('cp.async.bulk.wait_group 0;', '~{memory}', [], loc, ip)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@dsl_user_op
|
| 144 |
+
def bulk_wait_read(*, loc=None, ip=None):
|
| 145 |
+
_asm('cp.async.bulk.wait_group.read 0;', '~{memory}', [], loc, ip)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@dsl_user_op
|
| 149 |
+
def fence_async_smem(*, loc=None, ip=None):
|
| 150 |
+
_asm('fence.proxy.async.shared::cta;', '~{memory}', [], loc, ip)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@dsl_user_op
|
| 154 |
+
def tc_before(*, loc=None, ip=None):
|
| 155 |
+
_asm('tcgen05.fence::before_thread_sync;', '~{memory}', [], loc, ip)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@dsl_user_op
|
| 159 |
+
def tc_after(*, loc=None, ip=None):
|
| 160 |
+
_asm('tcgen05.fence::after_thread_sync;', '~{memory}', [], loc, ip)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@dsl_user_op
|
| 164 |
+
def tc_wait_st(*, loc=None, ip=None):
|
| 165 |
+
_asm('tcgen05.wait::st.sync.aligned;', '~{memory}', [], loc, ip)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@dsl_user_op
|
| 169 |
+
def tmem_load(addr, shape: str, count: int, *, loc=None, ip=None):
|
| 170 |
+
ty = ir.Type.parse('!llvm.struct<(' + ','.join(['f32'] * count) + ')>')
|
| 171 |
+
outs = ','.join(f'${i}' for i in range(count))
|
| 172 |
+
out = _asm(f'tcgen05.ld.sync.aligned.{shape}.b32 {{{outs}}}, [${count}]; tcgen05.wait::ld.sync.aligned;',
|
| 173 |
+
','.join(['=f'] * count + ['r']), [Int32(addr).ir_value(loc=loc, ip=ip)], loc, ip, ty)
|
| 174 |
+
return [Float32(llvm.extractvalue(T.f32(), out, [i], loc=loc, ip=ip)) for i in range(count)]
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@dsl_user_op
|
| 178 |
+
def tmem_load_nowait(addr, shape: str, count: int, *, loc=None, ip=None):
|
| 179 |
+
"""tcgen05.ld without the wait (tc_wait_ld must precede any use of the values)."""
|
| 180 |
+
ty = ir.Type.parse('!llvm.struct<(' + ','.join(['f32'] * count) + ')>')
|
| 181 |
+
outs = ','.join(f'${i}' for i in range(count))
|
| 182 |
+
out = _asm(f'tcgen05.ld.sync.aligned.{shape}.b32 {{{outs}}}, [${count}];',
|
| 183 |
+
','.join(['=f'] * count + ['r']), [Int32(addr).ir_value(loc=loc, ip=ip)], loc, ip, ty)
|
| 184 |
+
return [Float32(llvm.extractvalue(T.f32(), out, [i], loc=loc, ip=ip)) for i in range(count)]
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@dsl_user_op
|
| 188 |
+
def tc_wait_ld(*, loc=None, ip=None):
|
| 189 |
+
_asm('tcgen05.wait::ld.sync.aligned;', '~{memory}', [], loc, ip)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
@dsl_user_op
|
| 193 |
+
def tmem_store(addr, shape: str, values, *, loc=None, ip=None):
|
| 194 |
+
count = len(values)
|
| 195 |
+
args = [Int32(addr).ir_value(loc=loc, ip=ip)] + [Float32(x).ir_value(loc=loc, ip=ip) for x in values]
|
| 196 |
+
regs = ','.join(f'${i + 1}' for i in range(count))
|
| 197 |
+
_asm(f'tcgen05.st.sync.aligned.{shape}.b32 [$0], {{{regs}}};', ','.join(['r'] + ['f'] * count + ['~{memory}']), args, loc, ip)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@dsl_user_op
|
| 201 |
+
def sts128(addr, a, b, c, d, *, loc=None, ip=None):
|
| 202 |
+
args = [Int32(addr).ir_value(loc=loc, ip=ip)] + [Int32(x).ir_value(loc=loc, ip=ip) for x in (a, b, c, d)]
|
| 203 |
+
_asm('st.shared.v4.b32 [$0], {$1,$2,$3,$4};', 'r,r,r,r,r,~{memory}', args, loc, ip)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _smem_vec(dtype, addr, n, align):
|
| 207 |
+
t = cute.make_tensor(cute.make_ptr(dtype, addr, cute.AddressSpace.smem, assumed_align=align), cute.make_layout(n))
|
| 208 |
+
r = cute.make_rmem_tensor(n, dtype)
|
| 209 |
+
cute.autovec_copy(t, r)
|
| 210 |
+
return [r[i] for i in range(n)]
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def lds128(addr):
|
| 214 |
+
"""Plain (compiler-schedulable) 16-byte shared load as four Int32."""
|
| 215 |
+
return _smem_vec(Int32, addr, 4, 16)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def lds128f(addr):
|
| 219 |
+
return _smem_vec(Float32, addr, 4, 16)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def lds64f(addr):
|
| 223 |
+
return _smem_vec(Float32, addr, 2, 8)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def lds_u16(addr):
|
| 227 |
+
return cute.make_tensor(cute.make_ptr(cutlass.Uint16, addr, cute.AddressSpace.smem, assumed_align=2), cute.make_layout(1))[0].to(Int32) & Int32(0xFFFF)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
@dsl_user_op
|
| 231 |
+
def stsm4(addr, a, b, c, d, *, loc=None, ip=None):
|
| 232 |
+
args = [Int32(addr).ir_value(loc=loc, ip=ip)] + [Int32(x).ir_value(loc=loc, ip=ip) for x in (a, b, c, d)]
|
| 233 |
+
_asm('stmatrix.sync.aligned.m8n8.x4.shared.b16 [$0],{$1,$2,$3,$4};', 'r,r,r,r,r,~{memory}', args, loc, ip)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@dsl_user_op
|
| 237 |
+
def bits_float(x, *, loc=None, ip=None):
|
| 238 |
+
return Float32(arith.bitcast(T.f32(), Int32(x).ir_value(loc=loc, ip=ip), loc=loc, ip=ip))
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
@dsl_user_op
|
| 242 |
+
def float_bits(x, *, loc=None, ip=None):
|
| 243 |
+
return Int32(arith.bitcast(T.i32(), Float32(x).ir_value(loc=loc, ip=ip), loc=loc, ip=ip))
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _pure(text, cons, args, ret, loc, ip):
|
| 247 |
+
return llvm.inline_asm(ret, list(args), text, cons, has_side_effects=False, is_align_stack=False,
|
| 248 |
+
asm_dialect=llvm.AsmDialect.AD_ATT, loc=loc, ip=ip)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
@dsl_user_op
|
| 252 |
+
def l2_policy(fraction: float, *, loc=None, ip=None):
|
| 253 |
+
"""None keeps the default policy; a fraction gives early eviction priority."""
|
| 254 |
+
if fraction is None:
|
| 255 |
+
return None
|
| 256 |
+
return Int64(_pure(f'createpolicy.fractional.L2::evict_first.b64 $0, {fraction};', '=l', [], T.i64(), loc, ip))
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@dsl_user_op
|
| 260 |
+
def pack_half(a, b, *, loc=None, ip=None):
|
| 261 |
+
"""fp16x2 word: a in the low half."""
|
| 262 |
+
return Int32(_pure('cvt.rn.f16x2.f32 $0,$2,$1;', '=r,f,f', [Float32(a).ir_value(loc=loc, ip=ip), Float32(b).ir_value(loc=loc, ip=ip)], T.i32(), loc, ip))
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@dsl_user_op
|
| 266 |
+
def pack_bf16(a, b, *, loc=None, ip=None):
|
| 267 |
+
"""bf16x2 word: a in the low half."""
|
| 268 |
+
return Int32(_pure('cvt.rn.bf16x2.f32 $0,$2,$1;', '=r,f,f', [Float32(a).ir_value(loc=loc, ip=ip), Float32(b).ir_value(loc=loc, ip=ip)], T.i32(), loc, ip))
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@dsl_user_op
|
| 272 |
+
def prmt(a, b, sel: int, *, loc=None, ip=None):
|
| 273 |
+
return Int32(_pure(f'prmt.b32 $0,$1,$2,{sel:#x};', '=r,r,r', [Int32(a).ir_value(loc=loc, ip=ip), Int32(b).ir_value(loc=loc, ip=ip)], T.i32(), loc, ip))
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
@dsl_user_op
|
| 277 |
+
def sext_byte(w, b: int, *, loc=None, ip=None):
|
| 278 |
+
"""Byte b of w sign-extended to 32 bits (one PRMT)."""
|
| 279 |
+
sel = 0x8880 | b | ((b | 8) << 4) | ((b | 8) << 8) | ((b | 8) << 12)
|
| 280 |
+
return Int32(_pure(f'prmt.b32 $0,$1,0,{sel:#x};', '=r,r', [Int32(w).ir_value(loc=loc, ip=ip)], T.i32(), loc, ip))
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
@dsl_user_op
|
| 284 |
+
def magic_byte(wx, b: int, *, loc=None, ip=None):
|
| 285 |
+
"""Float 32768 + byte b of wx (byte placed in mantissa bits 8..15 under exponent 2^15), one PRMT."""
|
| 286 |
+
sel = 0x7404 | (b << 4)
|
| 287 |
+
return bits_float(Int32(_pure(f'prmt.b32 $0,$1,0x47000000,{sel:#x};', '=r,r', [Int32(wx).ir_value(loc=loc, ip=ip)], T.i32(), loc, ip)))
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
@dsl_user_op
|
| 291 |
+
def max_u16x2(a, b, *, loc=None, ip=None):
|
| 292 |
+
return Int32(_pure('max.u16x2 $0,$1,$2;', '=r,r,r', [Int32(a).ir_value(loc=loc, ip=ip), Int32(b).ir_value(loc=loc, ip=ip)], T.i32(), loc, ip))
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
@dsl_user_op
|
| 296 |
+
def f16x2_f32(w, *, loc=None, ip=None):
|
| 297 |
+
"""The two fp16 halves of w as fp32 (low half first)."""
|
| 298 |
+
ty = ir.Type.parse('!llvm.struct<(f32,f32)>')
|
| 299 |
+
out = _pure('{ .reg .b16 l, h; mov.b32 {l, h}, $2; cvt.f32.f16 $0, l; cvt.f32.f16 $1, h; }', '=f,=f,r',
|
| 300 |
+
[Int32(w).ir_value(loc=loc, ip=ip)], ty, loc, ip)
|
| 301 |
+
return Float32(llvm.extractvalue(T.f32(), out, [0], loc=loc, ip=ip)), Float32(llvm.extractvalue(T.f32(), out, [1], loc=loc, ip=ip))
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
@dsl_user_op
|
| 305 |
+
def redux_max(x, *, loc=None, ip=None):
|
| 306 |
+
"""Warp maximum of a nonnegative float (unsigned order of its bits)."""
|
| 307 |
+
raw = arith.bitcast(T.i32(), Float32(x).ir_value(loc=loc, ip=ip), loc=loc, ip=ip)
|
| 308 |
+
out = _asm('redux.sync.max.u32 $0,$1,0xffffffff;', '=r,r', [raw], loc, ip, T.i32())
|
| 309 |
+
return Float32(arith.bitcast(T.f32(), out, loc=loc, ip=ip))
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@dsl_user_op
|
| 313 |
+
def tf32_bits(x, *, loc=None, ip=None):
|
| 314 |
+
return Int32(_pure('cvt.rn.tf32.f32 $0,$1;', '=r,f',
|
| 315 |
+
[Float32(x).ir_value(loc=loc, ip=ip)], T.i32(), loc, ip))
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@dsl_user_op
|
| 319 |
+
def quant_pack(a, b, c, d, scale, *, loc=None, ip=None):
|
| 320 |
+
"""Round a..d * scale to nearest (even) integers and pack their low bytes, a in byte 0."""
|
| 321 |
+
bias = Float32(12582912)
|
| 322 |
+
q0, q1 = cute.arch.fma_packed_f32x2((Float32(a), Float32(b)), (Float32(scale), Float32(scale)), (bias, bias), ftz=False, loc=loc, ip=ip)
|
| 323 |
+
q2, q3 = cute.arch.fma_packed_f32x2((Float32(c), Float32(d)), (Float32(scale), Float32(scale)), (bias, bias), ftz=False, loc=loc, ip=ip)
|
| 324 |
+
args = [x.ir_value(loc=loc, ip=ip) for x in (q0, q1, q2, q3)]
|
| 325 |
+
return Int32(_pure('{ .reg .b32 p0,p1; prmt.b32 p0,$1,$2,0x0040; prmt.b32 p1,$3,$4,0x0040; prmt.b32 $0,p0,p1,0x5410; }',
|
| 326 |
+
'=r,f,f,f,f', args, T.i32(), loc, ip))
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def pi_inv(t):
|
| 330 |
+
"""TMEM column of key t: k = 16m + 4c + 2h + i -> n = 16m + 8h + 2c + i."""
|
| 331 |
+
return (t & 0x71) | ((t & 2) << 2) | ((t >> 1) & 6)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def pi_of(n):
|
| 335 |
+
"""Key held by TMEM column n."""
|
| 336 |
+
return (n & 0x71) | ((n >> 2) & 2) | ((n << 1) & 12)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def sw32(base, row, chunk):
|
| 340 |
+
"""Byte address of 16-byte chunk (0/1) of a 32-byte row in a 128B-aligned SW32 tile."""
|
| 341 |
+
return base + row * 32 + ((chunk ^ ((row >> 2) & 1)) << 4)
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def sw128(base, row, chunk):
|
| 345 |
+
"""Byte address of 16-byte chunk (0..7) of a 128-byte row in a 1024B-aligned SW128 tile."""
|
| 346 |
+
return base + row * 128 + ((chunk ^ (row & 7)) << 4)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
@cute.jit
|
| 350 |
+
def seed_load(a: cute.Pointer, tid: Int32):
|
| 351 |
+
"""The start matrix rows tid + 32i into warp 0's registers (issued at kernel entry)."""
|
| 352 |
+
z = cute.make_rmem_tensor((4, 4), Float32)
|
| 353 |
+
for i in cutlass.range_constexpr(4):
|
| 354 |
+
for r in cutlass.range_constexpr(4):
|
| 355 |
+
z[r, i] = Float32(0)
|
| 356 |
+
if cute.arch.make_warp_uniform(tid // 32) == 0:
|
| 357 |
+
for i in cutlass.range_constexpr(4):
|
| 358 |
+
ap = cute.make_ptr(Float32, a.toint() + (tid + 32 * i) * 16, cute.AddressSpace.gmem, assumed_align=16)
|
| 359 |
+
row = cute.make_rmem_tensor(4, Float32)
|
| 360 |
+
cute.autovec_copy(cute.make_tensor(ap, cute.make_layout(4)), row)
|
| 361 |
+
for r in cutlass.range_constexpr(4):
|
| 362 |
+
z[r, i] = row[r]
|
| 363 |
+
return z
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
@cute.jit
|
| 367 |
+
def seed_scale(z: cute.Tensor, qv_addr: Int32, tid: Int32):
|
| 368 |
+
"""Start matrix rows to qv (fp32, warp 0), each column scaled by an exact power of two (orthogonalize follows)."""
|
| 369 |
+
if cute.arch.make_warp_uniform(tid // 32) == 0:
|
| 370 |
+
for r in cutlass.range_constexpr(4):
|
| 371 |
+
peak = Float32(0)
|
| 372 |
+
for i in cutlass.range_constexpr(4):
|
| 373 |
+
peak = cute.arch.fmax(peak, cute.math.abs(z[r, i]))
|
| 374 |
+
peak = redux_max(peak)
|
| 375 |
+
eb = cutlass.min(cutlass.max(Int32(254) - ((float_bits(peak) >> 23) & 255), Int32(1)), Int32(252))
|
| 376 |
+
scale = bits_float(eb << 23)
|
| 377 |
+
for i in cutlass.range_constexpr(4):
|
| 378 |
+
z[r, i] *= scale
|
| 379 |
+
for i in cutlass.range_constexpr(4):
|
| 380 |
+
row = cute.make_rmem_tensor(4, Float32)
|
| 381 |
+
for r in cutlass.range_constexpr(4):
|
| 382 |
+
row[r] = z[r, i]
|
| 383 |
+
cute.autovec_copy(row, cute.make_tensor(cute.make_ptr(Float32, qv_addr + (tid + 32 * i) * 16, cute.AddressSpace.smem, assumed_align=16), cute.make_layout(4)))
|
| 384 |
+
cute.arch.sync_warp()
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
@cute.jit
|
| 388 |
+
def chol_pass(z: cute.Tensor, qv_addr: Int32, tid: Int32, tau: Float32):
|
| 389 |
+
"""One CholeskyQR pass with relative pivot floors on warp 0's rows z (4 per lane, in place). Returns True when
|
| 390 |
+
every pivot keeps more than tau of its column's squared norm (the pass is then accurate to about 1e-4)."""
|
| 391 |
+
g = cute.make_rmem_tensor(10, Float32)
|
| 392 |
+
for r in cutlass.range_constexpr(4):
|
| 393 |
+
for c in cutlass.range_constexpr(r + 1):
|
| 394 |
+
dot = Float32(0)
|
| 395 |
+
for i in cutlass.range_constexpr(4):
|
| 396 |
+
dot += z[r, i] * z[c, i]
|
| 397 |
+
g[r * (r + 1) // 2 + c] = dot
|
| 398 |
+
# warp sums of the 10 Gram partials through shared memory (rows of 36 floats at qv: the Q rows are
|
| 399 |
+
# already in registers): lane e < 10 adds up entry e, then every lane reads the 10 totals
|
| 400 |
+
cute.arch.sync_warp()
|
| 401 |
+
for i in cutlass.range_constexpr(10):
|
| 402 |
+
scr = cute.make_ptr(Float32, qv_addr + (i * 36 + tid) * 4, cute.AddressSpace.smem, assumed_align=4)
|
| 403 |
+
cute.make_tensor(scr, cute.make_layout(1))[0] = g[i]
|
| 404 |
+
cute.arch.sync_warp()
|
| 405 |
+
row = qv_addr + cutlass.min(tid, Int32(9)) * 144
|
| 406 |
+
part = lds128f(row)
|
| 407 |
+
for j in cutlass.range_constexpr(1, 8):
|
| 408 |
+
nxt = lds128f(row + 16 * j)
|
| 409 |
+
for k in cutlass.range_constexpr(4):
|
| 410 |
+
part[k] = part[k] + nxt[k]
|
| 411 |
+
tot = (part[0] + part[1]) + (part[2] + part[3])
|
| 412 |
+
if tid < 10:
|
| 413 |
+
cute.make_tensor(cute.make_ptr(Float32, qv_addr + (360 + tid) * 4, cute.AddressSpace.smem, assumed_align=4), cute.make_layout(1))[0] = tot
|
| 414 |
+
cute.arch.sync_warp()
|
| 415 |
+
gt = lds128f(qv_addr + 1440) + lds128f(qv_addr + 1456) + lds64f(qv_addr + 1472)
|
| 416 |
+
for i in cutlass.range_constexpr(10):
|
| 417 |
+
g[i] = gt[i]
|
| 418 |
+
d0 = cute.math.rsqrt(cute.arch.fmax(g[0], Float32(1e-30)), fastmath=True)
|
| 419 |
+
l10 = g[1] * d0
|
| 420 |
+
p1 = g[2] - l10 * l10
|
| 421 |
+
d1 = cute.math.rsqrt(cute.arch.fmax(cute.arch.fmax(p1, Float32(1e-6) * g[2]), Float32(1e-30)), fastmath=True)
|
| 422 |
+
l20 = g[3] * d0
|
| 423 |
+
l21 = (g[4] - l20 * l10) * d1
|
| 424 |
+
p2 = g[5] - l20 * l20 - l21 * l21
|
| 425 |
+
d2 = cute.math.rsqrt(cute.arch.fmax(cute.arch.fmax(p2, Float32(1e-6) * g[5]), Float32(1e-30)), fastmath=True)
|
| 426 |
+
l30 = g[6] * d0
|
| 427 |
+
l31 = (g[7] - l30 * l10) * d1
|
| 428 |
+
l32 = (g[8] - l30 * l20 - l31 * l21) * d2
|
| 429 |
+
p3 = g[9] - l30 * l30 - l31 * l31 - l32 * l32
|
| 430 |
+
d3 = cute.math.rsqrt(cute.arch.fmax(cute.arch.fmax(p3, Float32(1e-6) * g[9]), Float32(1e-30)), fastmath=True)
|
| 431 |
+
for i in cutlass.range_constexpr(4):
|
| 432 |
+
z[0, i] *= d0
|
| 433 |
+
z[1, i] = (z[1, i] - z[0, i] * l10) * d1
|
| 434 |
+
z[2, i] = (z[2, i] - z[0, i] * l20 - z[1, i] * l21) * d2
|
| 435 |
+
z[3, i] = (z[3, i] - z[0, i] * l30 - z[1, i] * l31 - z[2, i] * l32) * d3
|
| 436 |
+
margin = cute.arch.fmin(cute.arch.fmin(p1 - tau * g[2], p2 - tau * g[5]), p3 - tau * g[9])
|
| 437 |
+
return (margin > Float32(0)) & (g[0] > Float32(1e-30))
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
@cute.jit
|
| 441 |
+
def orthogonalize(qv_addr: Int32, sk_addr: Int32, tid: Int32, tau: Float32, lo: cutlass.Constexpr):
|
| 442 |
+
"""CholeskyQR on the 128 x 4 fp32 rows at qv (warp 0); fp16 Q rows (lo: plus their fp16 remainders in columns 4-7)
|
| 443 |
+
to the skinny tile. The second pass only runs
|
| 444 |
+
when the first one met a pivot below tau of its column's squared norm (ill-conditioned or rank-deficient
|
| 445 |
+
bases): one pass leaves an orthogonality defect of about 2e-7 / min normalized pivot."""
|
| 446 |
+
if cute.arch.make_warp_uniform(tid // 32) == 0:
|
| 447 |
+
z = cute.make_rmem_tensor((4, 4), Float32)
|
| 448 |
+
for i in cutlass.range_constexpr(4):
|
| 449 |
+
vals = lds128f(qv_addr + (tid + 32 * i) * 16)
|
| 450 |
+
for r in cutlass.range_constexpr(4):
|
| 451 |
+
z[r, i] = vals[r]
|
| 452 |
+
good = chol_pass(z, qv_addr, tid, tau)
|
| 453 |
+
if not good:
|
| 454 |
+
chol_pass(z, qv_addr, tid, tau)
|
| 455 |
+
for i in cutlass.range_constexpr(4):
|
| 456 |
+
sp = cute.make_ptr(Int32, sk_addr + (tid + 32 * i) * 16, cute.AddressSpace.smem, assumed_align=16)
|
| 457 |
+
if cutlass.const_expr(lo):
|
| 458 |
+
# start basis: columns 0-3 the fp16 high parts, 4-7 their remainders (the subspace iteration's
|
| 459 |
+
# result is sensitive to its start in ill-conditioned heads)
|
| 460 |
+
packed = cute.make_rmem_tensor(4, Int32)
|
| 461 |
+
packed[0], packed[1] = pack_half(z[0, i], z[1, i]), pack_half(z[2, i], z[3, i])
|
| 462 |
+
h0, h1 = f16x2_f32(packed[0]), f16x2_f32(packed[1])
|
| 463 |
+
lo0 = cute.arch.sub_packed_f32x2((z[0, i], z[1, i]), h0, ftz=False)
|
| 464 |
+
lo1 = cute.arch.sub_packed_f32x2((z[2, i], z[3, i]), h1, ftz=False)
|
| 465 |
+
packed[2], packed[3] = pack_half(*lo0), pack_half(*lo1)
|
| 466 |
+
cute.autovec_copy(packed, cute.make_tensor(sp, cute.make_layout(4)))
|
| 467 |
+
else:
|
| 468 |
+
# the new Q: fp16 rows in columns 0-3 (columns 4-7 of the skinny tile stay zero)
|
| 469 |
+
packed = cute.make_rmem_tensor(2, Int32)
|
| 470 |
+
packed[0], packed[1] = pack_half(z[0, i], z[1, i]), pack_half(z[2, i], z[3, i])
|
| 471 |
+
cute.autovec_copy(packed, cute.make_tensor(sp, cute.make_layout(2)))
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
@cute.jit
|
| 475 |
+
def issue_copy_pair(base: Int32, off0: int, src0: Int64, n0: int, off1: int, src1: Int64, n1: int, mbar: Int32, fraction: cutlass.Constexpr):
|
| 476 |
+
"""Two bulk copies into shared memory, one expect + arrival on the window mbarrier."""
|
| 477 |
+
mbar_expect(mbar, n0 + n1)
|
| 478 |
+
bulk_load(base + off0, src0, n0, mbar, fraction)
|
| 479 |
+
bulk_load(base + off1, src1, n1, mbar, fraction)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
@cute.jit
|
| 483 |
+
def issue_window(base: Int32, kb: cute.Pointer, gb: cute.Pointer, wb: cute.Pointer, pb: cute.Pointer,
|
| 484 |
+
raw: cute.Pointer, ph: Int32, mbar: Int32, mb_win: cute.Pointer, warp: Int32, lane: Int32,
|
| 485 |
+
tma_atom_u: cute.CopyAtom, t_gu: cute.Tensor, t_su: cute.Tensor, fraction: cutlass.Constexpr):
|
| 486 |
+
"""Program ph's window by warps 1-3 (three arrivals; warp 0 issues the products, and a bulk-copy issue keeps a
|
| 487 |
+
warp busy for ~150 cycles): two bulk copies on lane 0 of warps 1 / 2; warp 3 sends ubuf through the TMA atom
|
| 488 |
+
(MN-major window operand as loaded) and META by a bulk copy."""
|
| 489 |
+
pw = ph.to(Int64)
|
| 490 |
+
if warp == 1:
|
| 491 |
+
if lane == 0:
|
| 492 |
+
issue_copy_pair(base, KB, kb.toint() + pw * 4096, 4096, WGT, wb.toint() + pw * 64, 64, mbar, fraction)
|
| 493 |
+
if warp == 2:
|
| 494 |
+
if lane == 0:
|
| 495 |
+
issue_copy_pair(base, GB, gb.toint() + pw * 4096, 4096, PCM, pb.toint() + pw * 512, 512, mbar, fraction)
|
| 496 |
+
if warp == 3:
|
| 497 |
+
if lane == 0:
|
| 498 |
+
rp = raw.toint() + (Int64(OFF) + (ph // 32).to(Int64) * SS + (ph % 32).to(Int64) * 16384) * 4
|
| 499 |
+
mbar_expect(mbar, 4096 + 3072)
|
| 500 |
+
bulk_load(base + META, rp + 16384, 3072, mbar, fraction)
|
| 501 |
+
cute.copy(tma_atom_u, t_gu[(None, ph)], t_su, tma_bar_ptr=mb_win, cache_policy=l2_policy(fraction))
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
@cute.jit
|
| 505 |
+
def reset_window(base: Int32, gb: cute.Pointer, wb: cute.Pointer, pb: cute.Pointer, ph: Int32, tid: Int32, fraction: cutlass.Constexpr):
|
| 506 |
+
"""Program ph's window reset: pcum and w to zero, gbuf to ones by four bulk copies from the ones buffer (thread 0;
|
| 507 |
+
the bulk group is waited with the code store's)."""
|
| 508 |
+
logs = cute.make_tensor(pb + ph.to(Int64) * 128, cute.make_layout(128))
|
| 509 |
+
logs[tid] = Float32(0)
|
| 510 |
+
if tid < 16:
|
| 511 |
+
weights = cute.make_tensor(wb + ph.to(Int64) * 16, cute.make_layout(16))
|
| 512 |
+
weights[tid] = Float32(0)
|
| 513 |
+
if tid == 0:
|
| 514 |
+
for q in cutlass.range_constexpr(4):
|
| 515 |
+
bulk_store(gb.toint() + ph.to(Int64) * 4096 + q * 1024, base + ONES, 1024, fraction)
|
| 516 |
+
bulk_commit()
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
@cute.jit
|
| 520 |
+
def issue_codes(base: Int32, desc_addr: Int64, ph: Int32, mbar: Int32):
|
| 521 |
+
mbar_expect(mbar, 16384)
|
| 522 |
+
tma_load_codes(base + SF + 16384, desc_addr, ph % 32, ph // 32, mbar)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
@cute.kernel
|
| 526 |
+
def flush_kernel(raw_addr: Int64, kb_addr: Int64, ub_addr: Int64, gb_addr: Int64,
|
| 527 |
+
wb_addr: Int64, pb_addr: Int64, hc_addr: Int64, desc_addr: Int64, start_addr: Int64,
|
| 528 |
+
idx_addr: Int64, dbg_addr: Int64, n: Int32, tma_atom_c: cute.CopyAtom, tma_c: cute.Tensor,
|
| 529 |
+
tma_atom_s: cute.CopyAtom, tma_s: cute.Tensor, tma_atom_u: cute.CopyAtom, tma_u: cute.Tensor,
|
| 530 |
+
blocks: cutlass.Constexpr, dbg: cutlass.Constexpr, fraction: cutlass.Constexpr = None):
|
| 531 |
+
raw = cute.make_ptr(Float32, raw_addr, cute.AddressSpace.gmem, assumed_align=16)
|
| 532 |
+
kb = cute.make_ptr(BFloat16, kb_addr, cute.AddressSpace.gmem, assumed_align=16)
|
| 533 |
+
ub = cute.make_ptr(BFloat16, ub_addr, cute.AddressSpace.gmem, assumed_align=16)
|
| 534 |
+
gb = cute.make_ptr(Float16, gb_addr, cute.AddressSpace.gmem, assumed_align=16)
|
| 535 |
+
wb = cute.make_ptr(Float32, wb_addr, cute.AddressSpace.gmem, assumed_align=16)
|
| 536 |
+
pb = cute.make_ptr(Float32, pb_addr, cute.AddressSpace.gmem, assumed_align=16)
|
| 537 |
+
hc = cute.make_ptr(Int32, hc_addr, cute.AddressSpace.gmem, assumed_align=16)
|
| 538 |
+
start = cute.make_ptr(Float32, start_addr, cute.AddressSpace.gmem, assumed_align=16)
|
| 539 |
+
indices = cute.make_ptr(Int32, idx_addr, cute.AddressSpace.gmem, assumed_align=16)
|
| 540 |
+
dbgp = cute.make_ptr(Float32, dbg_addr, cute.AddressSpace.gmem, assumed_align=16)
|
| 541 |
+
tid, _, _ = cute.arch.thread_idx()
|
| 542 |
+
bid, _, _ = cute.arch.block_idx()
|
| 543 |
+
lane, warp = tid % 32, cute.arch.make_warp_uniform(tid // 32)
|
| 544 |
+
smem = SmemAllocator()
|
| 545 |
+
buf = smem.allocate_tensor(Int8, cute.make_layout(SMEM_BYTES), byte_alignment=1024)
|
| 546 |
+
base = buf.iterator.toint().to(Int32)
|
| 547 |
+
due = cute.make_tensor(cute.make_ptr(Int32, base + DUE, cute.AddressSpace.smem, assumed_align=16), cute.make_layout(MAXDUE))
|
| 548 |
+
counts = cute.make_tensor(cute.make_ptr(Int32, base + CNT, cute.AddressSpace.smem, assumed_align=16), cute.make_layout(4))
|
| 549 |
+
bnd = cute.make_tensor(cute.make_ptr(Float32, base + BND, cute.AddressSpace.smem, assumed_align=16), cute.make_layout((4, 8), stride=(8, 1)))
|
| 550 |
+
mb_mma = cute.make_ptr(Uint64, base + MBAR, cute.AddressSpace.smem, assumed_align=8)
|
| 551 |
+
mb_win = cute.make_ptr(Uint64, base + MBAR + 8, cute.AddressSpace.smem, assumed_align=8)
|
| 552 |
+
mb_codes = cute.make_ptr(Uint64, base + MBAR + 16, cute.AddressSpace.smem, assumed_align=8)
|
| 553 |
+
tmh = cute.make_ptr(Int32, base + TMH, cute.AddressSpace.smem, assumed_align=4)
|
| 554 |
+
skp = cute.make_tensor(cute.make_ptr(Float32, base + SKP, cute.AddressSpace.smem, assumed_align=16), cute.make_layout(128))
|
| 555 |
+
if warp == 0: # first: the next CTA on this SM launches once the permit is relinquished
|
| 556 |
+
cute.arch.alloc_tmem(128, tmh)
|
| 557 |
+
cute.arch.relinquish_tmem_alloc_permit()
|
| 558 |
+
if tid == 32: # the shared start matrix into L2 ahead of the first windows' DRAM burst
|
| 559 |
+
prefetch_l2(start_addr, 2048)
|
| 560 |
+
if cutlass.const_expr(fraction is not None):
|
| 561 |
+
# small calls: the start matrix rows (warp 0) load during the due selection, and warps 1-3 may send the first
|
| 562 |
+
# window before the setup barriers (mb_win is initialized here for them)
|
| 563 |
+
zseed_e = seed_load(start, tid)
|
| 564 |
+
if tid == 32:
|
| 565 |
+
cute.arch.mbarrier_init(mb_win, 3)
|
| 566 |
+
cute.arch.mbarrier_init_fence()
|
| 567 |
+
if warp != 0:
|
| 568 |
+
cute.arch.barrier(barrier_id=1, number_of_threads=96)
|
| 569 |
+
ub_layout_e = cute.tile_to_shape(tc.make_smem_layout_atom(tc.SmemLayoutAtomKind.MN_SW128, BFloat16), (128, 16), order=(1, 0))
|
| 570 |
+
ub_tile_e = cute.make_tensor(cute.make_ptr(BFloat16, base + UB, cute.AddressSpace.smem, assumed_align=1024, swizzle_=ub_layout_e.inner),
|
| 571 |
+
ub_layout_e.outer)
|
| 572 |
+
g_u_e = cute.local_tile(tma_u, (128, 16), (0, 0, None))
|
| 573 |
+
t_su_e, t_gu_e = cpasync.tma_partition(tma_atom_u, 0, cute.make_layout(1), cute.group_modes(ub_tile_e, 0, 2), cute.group_modes(g_u_e, 0, 2))
|
| 574 |
+
# GPU-side due-selection and start-matrix loads are in flight during setup.
|
| 575 |
+
ix = cute.make_tensor(indices, cute.make_layout(n))
|
| 576 |
+
hcnt = cute.make_tensor(hc, cute.make_layout(n * 32 + 1))
|
| 577 |
+
# Weighted round-robin: the k-th program of CTA b is the rank of (2k + 1) / W[wave(b)] in a global virtual-time
|
| 578 |
+
# order (ties: lower wave, then lower index), so every round stays an interleaved compact block of programs while
|
| 579 |
+
# the CTAs launched first on each SM (wave = bid // SMs; they run faster under the scheduler's age priority) get
|
| 580 |
+
# proportionally more programs. Equal weights give p = bid + k * blocks. The skew only applies from 6
|
| 581 |
+
# programs per CTA on.
|
| 582 |
+
nprog = n * 32
|
| 583 |
+
p = bid + tid * blocks
|
| 584 |
+
if nprog >= 6 * blocks and nprog < 100 * blocks: # 128 candidates per CTA cover the weighted ranks below 100
|
| 585 |
+
sms_c = blocks // 4
|
| 586 |
+
wave_i = bid // sms_c
|
| 587 |
+
t2 = 2 * tid + 1
|
| 588 |
+
base_p = tid * sms_c + (bid - wave_i * sms_c)
|
| 589 |
+
strong = nprog < 12 * blocks # fewer programs per CTA: the late launch waves weigh more
|
| 590 |
+
for ws, wtab in ((0, (1091, 1036, 964, 909)), (1, (1130, 1050, 950, 870))):
|
| 591 |
+
for i in cutlass.range_constexpr(4): # the rank for each possible wave (constant divisors), keep our own
|
| 592 |
+
pw = base_p
|
| 593 |
+
for j in cutlass.range_constexpr(4):
|
| 594 |
+
if cutlass.const_expr(j < i):
|
| 595 |
+
num = t2 * wtab[j] - wtab[i] # >= 0 for every tid since wtab[j] > wtab[i]
|
| 596 |
+
pw += (num // (2 * wtab[i]) + 1) * sms_c
|
| 597 |
+
if cutlass.const_expr(j > i):
|
| 598 |
+
num = t2 * wtab[j] - wtab[i]
|
| 599 |
+
pw += (cutlass.max(num + 2 * wtab[i] - 1, Int32(0)) // (2 * wtab[i])) * sms_c
|
| 600 |
+
if wave_i == i:
|
| 601 |
+
if strong == (ws == 1):
|
| 602 |
+
p = pw
|
| 603 |
+
# The first due program is program bid whenever that one is due (thread 0's candidate): for small calls warps 1-3
|
| 604 |
+
# read its fill counter themselves and send its window now instead of after the setup barriers.
|
| 605 |
+
early = cutlass.Boolean(False)
|
| 606 |
+
if cutlass.const_expr(fraction is not None):
|
| 607 |
+
if warp != 0:
|
| 608 |
+
if bid < nprog:
|
| 609 |
+
s0 = ix[bid // 32]
|
| 610 |
+
if s0 > 0:
|
| 611 |
+
early = hcnt[s0 * 32 + bid % 32] == 16
|
| 612 |
+
if early:
|
| 613 |
+
issue_window(base, kb, gb, wb, pb, raw, s0 * 32 + bid % 32, mb_win.toint().to(Int32), mb_win, warp, lane, tma_atom_u, t_gu_e, t_su_e, fraction)
|
| 614 |
+
slot0 = Int32(0)
|
| 615 |
+
flag = cutlass.Boolean(False)
|
| 616 |
+
if p < nprog:
|
| 617 |
+
slot0 = ix[p // 32]
|
| 618 |
+
if slot0 > 0:
|
| 619 |
+
flag = hcnt[slot0 * 32 + p % 32] == 16
|
| 620 |
+
# ---- due programs ranked in (warp, lane) order ----
|
| 621 |
+
mask = cute.arch.vote_ballot_sync(flag)
|
| 622 |
+
if lane == 0:
|
| 623 |
+
counts[warp] = cute.arch.popc(mask)
|
| 624 |
+
cute.arch.sync_threads()
|
| 625 |
+
base_rank, total = Int32(0), Int32(0)
|
| 626 |
+
count4 = lds128(base + CNT)
|
| 627 |
+
for j in cutlass.range_constexpr(4):
|
| 628 |
+
if j < warp:
|
| 629 |
+
base_rank += count4[j]
|
| 630 |
+
total += count4[j]
|
| 631 |
+
rank = base_rank + cute.arch.popc(mask & ((cutlass.Uint32(1) << lane) - 1))
|
| 632 |
+
if flag:
|
| 633 |
+
due[rank] = slot0 * 32 + p % 32
|
| 634 |
+
cute.arch.sync_threads()
|
| 635 |
+
if cutlass.const_expr(fraction is not None):
|
| 636 |
+
if warp != 0:
|
| 637 |
+
if not early:
|
| 638 |
+
if total > 0:
|
| 639 |
+
issue_window(base, kb, gb, wb, pb, raw, due[0], mb_win.toint().to(Int32), mb_win, warp, lane, tma_atom_u, t_gu_e, t_su_e, fraction)
|
| 640 |
+
|
| 641 |
+
tp = cute.arch.retrieve_tmem_ptr(Float32, 16, tmh)
|
| 642 |
+
tbase = tp.toint().to(Int32) + ((warp * 32) << 16)
|
| 643 |
+
|
| 644 |
+
# ---- MMA atoms and operand views (all descriptors built by CuTe from the smem layouts) ----
|
| 645 |
+
sw32b = cute.make_swizzle(1, 4, 3)
|
| 646 |
+
def tile16(off, dtype):
|
| 647 |
+
return cute.make_tensor(cute.make_ptr(dtype, base + off, cute.AddressSpace.smem, assumed_align=128, swizzle_=sw32b),
|
| 648 |
+
cute.make_layout((128, 16), stride=(16, 1)))
|
| 649 |
+
# window products: A = ubuf exactly as the TMA lands it (MN-major SW128, j-atoms first), B = keys hi / lo
|
| 650 |
+
mma_rb = cute.make_tiled_mma(tc.MmaF16BF16Op(BFloat16, Float32, (128, 128, 16), tc.CtaGroup.ONE, tc.OperandSource.SMEM,
|
| 651 |
+
cute.nvgpu.OperandMajorMode.MN, cute.nvgpu.OperandMajorMode.K))
|
| 652 |
+
thr_rb = mma_rb.get_slice(0)
|
| 653 |
+
ub_layout = cute.tile_to_shape(tc.make_smem_layout_atom(tc.SmemLayoutAtomKind.MN_SW128, BFloat16), (128, 16), order=(1, 0))
|
| 654 |
+
ub_tile = cute.make_tensor(cute.make_ptr(BFloat16, base + UB, cute.AddressSpace.smem, assumed_align=1024, swizzle_=ub_layout.inner),
|
| 655 |
+
ub_layout.outer)
|
| 656 |
+
a_win = mma_rb.make_fragment_A(thr_rb.partition_A(ub_tile))
|
| 657 |
+
b_hi = mma_rb.make_fragment_B(thr_rb.partition_B(tile16(KB, BFloat16)))
|
| 658 |
+
b_lo = mma_rb.make_fragment_B(thr_rb.partition_B(tile16(GB, BFloat16)))
|
| 659 |
+
g_u = cute.local_tile(tma_u, (128, 16), (0, 0, None))
|
| 660 |
+
t_su, t_gu = cpasync.tma_partition(tma_atom_u, 0, cute.make_layout(1), cute.group_modes(ub_tile, 0, 2), cute.group_modes(g_u, 0, 2))
|
| 661 |
+
frag = mma_rb.make_fragment_C(mma_rb.partition_shape_C((128, 128)))
|
| 662 |
+
acc_t = cute.make_tensor(tp, frag.layout)
|
| 663 |
+
|
| 664 |
+
codes_layout = cute.tile_to_shape(tc.make_smem_layout_atom(tc.SmemLayoutAtomKind.K_SW128, Int8), (128, 128), order=(0, 1))
|
| 665 |
+
codes_in = cute.make_tensor(cute.make_ptr(Int8, base + SF + 16384, cute.AddressSpace.smem, assumed_align=1024, swizzle_=codes_layout.inner),
|
| 666 |
+
codes_layout.outer)
|
| 667 |
+
g_c = cute.local_tile(tma_c, (128, 128), (0, 0, None, None))
|
| 668 |
+
t_sc, t_gc = cpasync.tma_partition(tma_atom_c, 0, cute.make_layout(1), cute.group_modes(codes_in, 0, 2), cute.group_modes(g_c, 0, 2))
|
| 669 |
+
codes_out = cute.make_tensor(cute.make_ptr(Int8, base + SF, cute.AddressSpace.smem, assumed_align=1024, swizzle_=codes_layout.inner),
|
| 670 |
+
codes_layout.outer)
|
| 671 |
+
g_s = cute.local_tile(tma_s, (128, 128), (0, 0, None, None))
|
| 672 |
+
t_ss, t_gs = cpasync.tma_partition(tma_atom_s, 0, cute.make_layout(1), cute.group_modes(codes_out, 0, 2), cute.group_modes(g_s, 0, 2))
|
| 673 |
+
state_atom = tc.make_smem_layout_atom(tc.SmemLayoutAtomKind.K_SW128, Float16)
|
| 674 |
+
state_layout = cute.tile_to_shape(state_atom, (128, 128), order=(0, 1))
|
| 675 |
+
state = cute.make_tensor(cute.make_ptr(Float16, base + SF, cute.AddressSpace.smem, assumed_align=1024, swizzle_=state_layout.inner),
|
| 676 |
+
state_layout.outer)
|
| 677 |
+
state_t = cute.make_tensor(state.iterator, cute.select(state.layout, mode=[1, 0]))
|
| 678 |
+
src16 = cute.make_tensor(cute.make_ptr(Float16, base + SKB, cute.AddressSpace.smem, assumed_align=128), cute.make_layout((8, 128), stride=(1, 8)))
|
| 679 |
+
mma_p = cute.make_tiled_mma(tc.MmaF16BF16Op(Float16, Float32, (128, 8, 16), tc.CtaGroup.ONE, tc.OperandSource.SMEM,
|
| 680 |
+
cute.nvgpu.OperandMajorMode.MN, cute.nvgpu.OperandMajorMode.MN))
|
| 681 |
+
mma_q = cute.make_tiled_mma(tc.MmaF16BF16Op(Float16, Float32, (128, 8, 16), tc.CtaGroup.ONE, tc.OperandSource.SMEM,
|
| 682 |
+
cute.nvgpu.OperandMajorMode.K, cute.nvgpu.OperandMajorMode.MN))
|
| 683 |
+
thp, thq = mma_p.get_slice(0), mma_q.get_slice(0)
|
| 684 |
+
ps_a = mma_p.make_fragment_A(thp.partition_A(state_t))
|
| 685 |
+
ps_b = mma_p.make_fragment_B(thp.partition_B(src16))
|
| 686 |
+
seed16 = cute.make_tensor(cute.make_ptr(Float16, base + SEEDB, cute.AddressSpace.smem, assumed_align=128), cute.make_layout((8, 128), stride=(1, 8)))
|
| 687 |
+
ps_seed = mma_p.make_fragment_B(thp.partition_B(seed16))
|
| 688 |
+
qs_a = mma_q.make_fragment_A(thq.partition_A(state))
|
| 689 |
+
qs_b = mma_q.make_fragment_B(thq.partition_B(src16))
|
| 690 |
+
skinny_frag = mma_p.make_fragment_C(mma_p.partition_shape_C((128, 8)))
|
| 691 |
+
# the skinny products land in TMEM columns 120-127 (S' columns saved in `keep` from pass A's last chunk, so the
|
| 692 |
+
# saved values are not live during pass A)
|
| 693 |
+
skinny_acc = cute.make_tensor(cute.make_tensor(tp, skinny_frag.layout).iterator + Int32(120), skinny_frag.layout)
|
| 694 |
+
res_layout = cute.tile_to_shape(tc.make_smem_layout_atom(tc.SmemLayoutAtomKind.K_SW32, TFloat32), (128, 8), order=(0, 1))
|
| 695 |
+
mma_r = cute.make_tiled_mma(tc.MmaTF32Op((128, 128, 8), tc.CtaGroup.ONE, tc.OperandSource.SMEM,
|
| 696 |
+
cute.nvgpu.OperandMajorMode.K, cute.nvgpu.OperandMajorMode.K))
|
| 697 |
+
thr_r = mma_r.get_slice(0)
|
| 698 |
+
ra = cute.make_tensor(cute.make_ptr(TFloat32, base + SF, cute.AddressSpace.smem, assumed_align=1024, swizzle_=res_layout.inner), res_layout.outer)
|
| 699 |
+
rb = cute.make_tensor(cute.make_ptr(TFloat32, base + SF + 4096, cute.AddressSpace.smem, assumed_align=1024, swizzle_=res_layout.inner), res_layout.outer)
|
| 700 |
+
r_a = mma_r.make_fragment_A(thr_r.partition_A(ra))
|
| 701 |
+
r_b = mma_r.make_fragment_B(thr_r.partition_B(rb))
|
| 702 |
+
|
| 703 |
+
if total > 0:
|
| 704 |
+
if tid == 0:
|
| 705 |
+
cute.arch.mbarrier_init(mb_mma, 1)
|
| 706 |
+
if cutlass.const_expr(fraction is None):
|
| 707 |
+
cute.arch.mbarrier_init(mb_win, 3)
|
| 708 |
+
cute.arch.mbarrier_init(mb_codes, 1)
|
| 709 |
+
cute.arch.mbarrier_init_fence()
|
| 710 |
+
zv = cute.make_rmem_tensor(2, Int32) # columns 4..7 of the skinny operand stay zero
|
| 711 |
+
zv[0], zv[1] = Int32(0), Int32(0)
|
| 712 |
+
cute.autovec_copy(zv, cute.make_tensor(cute.make_ptr(Int32, base + SKB + tid * 16 + 8, cute.AddressSpace.smem, assumed_align=8), cute.make_layout(2)))
|
| 713 |
+
ov = cute.make_rmem_tensor(2, Int32)
|
| 714 |
+
ov[0], ov[1] = Int32(0x3c003c00), Int32(0x3c003c00)
|
| 715 |
+
cute.autovec_copy(ov, cute.make_tensor(cute.make_ptr(Int32, base + ONES + tid * 8, cute.AddressSpace.smem, assumed_align=8), cute.make_layout(2)))
|
| 716 |
+
fence_async_smem()
|
| 717 |
+
cute.arch.sync_threads()
|
| 718 |
+
if total > 0:
|
| 719 |
+
if cutlass.const_expr(fraction is None):
|
| 720 |
+
if warp != 0:
|
| 721 |
+
issue_window(base, kb, gb, wb, pb, raw, due[0], mb_win.toint().to(Int32), mb_win, warp, lane, tma_atom_u, t_gu, t_su, fraction)
|
| 722 |
+
zseed = seed_load(start, tid)
|
| 723 |
+
else:
|
| 724 |
+
zseed = zseed_e
|
| 725 |
+
# conditioned start basis: power-of-two column scaling, then CholeskyQR2 (QVB is free until the Q stage)
|
| 726 |
+
seed_scale(zseed, base + QVB, tid)
|
| 727 |
+
orthogonalize(base + QVB, base + SEEDB, tid, Float32(TAU), True)
|
| 728 |
+
for work in range(total):
|
| 729 |
+
ph = due[work]
|
| 730 |
+
slot, head = ph // 32, ph % 32
|
| 731 |
+
rawhead = raw + (Int64(OFF) + slot.to(Int64) * SS + head.to(Int64) * 16384)
|
| 732 |
+
mbar_wait(mb_win, work & 1)
|
| 733 |
+
if work == 0: # the first codes follow the first window (the initial DRAM burst serves windows first)
|
| 734 |
+
if tid == 0:
|
| 735 |
+
mbar_expect(mb_codes.toint().to(Int32), 16384)
|
| 736 |
+
if warp == 0:
|
| 737 |
+
cute.copy(tma_atom_c, t_gc[(None, head, slot)], t_sc, tma_bar_ptr=mb_codes, cache_policy=l2_policy(fraction))
|
| 738 |
+
# ---------------- prep part 1: everything into registers, bound partials ----------------
|
| 739 |
+
# thread t prepares key pi(t), so that its operand rows (TMEM column t) are stored conflict-free
|
| 740 |
+
kcol = pi_of(tid)
|
| 741 |
+
pcv = cute.math.exp(cute.make_tensor(cute.make_ptr(Float32, base + PCM, cute.AddressSpace.smem, assumed_align=16), cute.make_layout(128))[kcol])
|
| 742 |
+
meta = cute.make_tensor(cute.make_ptr(Float32, base + META, cute.AddressSpace.smem, assumed_align=16), cute.make_layout(256))
|
| 743 |
+
skv = meta[kcol] * pcv
|
| 744 |
+
svv = meta[128 + tid]
|
| 745 |
+
wv = cute.make_rmem_tensor(16, Float32)
|
| 746 |
+
for q in cutlass.range_constexpr(4):
|
| 747 |
+
w4 = lds128f(base + WGT + q * 16)
|
| 748 |
+
for i in cutlass.range_constexpr(4):
|
| 749 |
+
wv[q * 4 + i] = w4[i]
|
| 750 |
+
keys = cute.make_rmem_tensor(16, Float32)
|
| 751 |
+
prod = Float32(1)
|
| 752 |
+
kmax = Float32(0)
|
| 753 |
+
for jj in cutlass.range_constexpr(16):
|
| 754 |
+
j = 15 - jj
|
| 755 |
+
kbits = lds_u16(base + KB + j * 256 + kcol * 2)
|
| 756 |
+
gbits = lds_u16(base + GB + j * 256 + kcol * 2)
|
| 757 |
+
kf = bits_float(kbits << 16)
|
| 758 |
+
keys[j] = kf * wv[j] * prod
|
| 759 |
+
kmax = cute.arch.fmax(kmax, cute.math.abs(keys[j]))
|
| 760 |
+
gh = cute.make_rmem_tensor(1, Int32)
|
| 761 |
+
gh[0] = gbits
|
| 762 |
+
prod = prod * (cute.recast_tensor(gh, Float16)[0]).to(Float32)
|
| 763 |
+
uw8 = lds128(base + UB + tid * 16) + lds128(base + UB + 2048 + tid * 16) # any 16 values: only the tile maximum
|
| 764 |
+
um = uw8[0] & Int32(0x7FFF7FFF)
|
| 765 |
+
for i in cutlass.range_constexpr(1, 8):
|
| 766 |
+
um = max_u16x2(um, uw8[i] & Int32(0x7FFF7FFF))
|
| 767 |
+
umax = cute.arch.fmax(bits_float(um << 16), bits_float(um & Int32(-65536)))
|
| 768 |
+
uqw = cute.make_rmem_tensor(8, Int32) # u_old[r][kcol] (r 0..3) and q_old[r][tid]
|
| 769 |
+
for r in cutlass.range_constexpr(4):
|
| 770 |
+
uqw[r] = lds_u16(base + META + 1024 + r * 512 + kcol * 2)
|
| 771 |
+
uqw[4 + r] = lds_u16(base + META + 1024 + r * 512 + 256 + tid * 2)
|
| 772 |
+
uo = cute.make_rmem_tensor(4, Float32)
|
| 773 |
+
qo = cute.make_rmem_tensor(4, Float32)
|
| 774 |
+
qmax, uomax = Float32(0), Float32(0)
|
| 775 |
+
for r in cutlass.range_constexpr(4):
|
| 776 |
+
hu = cute.make_rmem_tensor(2, Int32)
|
| 777 |
+
hu[0], hu[1] = uqw[r], uqw[4 + r]
|
| 778 |
+
hv = cute.recast_tensor(hu, Float16)
|
| 779 |
+
uo[r] = hv[0].to(Float32) * pcv
|
| 780 |
+
qo[r] = hv[2].to(Float32)
|
| 781 |
+
uomax = cute.arch.fmax(uomax, cute.math.abs(uo[r]))
|
| 782 |
+
qmax = cute.arch.fmax(qmax, cute.math.abs(qo[r]))
|
| 783 |
+
parts = (cute.math.abs(skv), cute.math.abs(svv), qmax, uomax, umax, kmax)
|
| 784 |
+
if warp == 0:
|
| 785 |
+
bulk_wait_read() # the previous program's code store no longer reads SF (warp 0 issued it)
|
| 786 |
+
for j in cutlass.range_constexpr(6):
|
| 787 |
+
m = redux_max(parts[j])
|
| 788 |
+
if lane == 0:
|
| 789 |
+
bnd[warp, j] = m
|
| 790 |
+
cute.arch.sync_threads()
|
| 791 |
+
mx = cute.make_rmem_tensor(6, Float32)
|
| 792 |
+
for j in cutlass.range_constexpr(6):
|
| 793 |
+
mx[j] = cute.arch.fmax(cute.arch.fmax(bnd[0, j], bnd[1, j]), cute.arch.fmax(bnd[2, j], bnd[3, j]))
|
| 794 |
+
residual_bound = mx[0] * mx[1]
|
| 795 |
+
update_bound = Float32(4) * mx[2] * mx[3] + Float32(16) * mx[4] * mx[5]
|
| 796 |
+
bound = mx[0] * mx[1] + Float32(4) * mx[2] * mx[3] + Float32(16) * mx[4] * mx[5]
|
| 797 |
+
# Positive scales can remain on an empty old residual. If their bound
|
| 798 |
+
# overwhelms the factors and window, it can underflow the fp16 state.
|
| 799 |
+
# Remove that contribution only after confirming zero codes on the GPU.
|
| 800 |
+
if residual_bound > update_bound * Float32(65536):
|
| 801 |
+
mbar_wait(mb_codes, work & 1)
|
| 802 |
+
nz = Int32(0)
|
| 803 |
+
for cc in cutlass.range_constexpr(8):
|
| 804 |
+
cv = lds128(base + SF + 16384 + tid * 16 + cc * 2048)
|
| 805 |
+
for jj in cutlass.range_constexpr(4):
|
| 806 |
+
nz = nz | cv[jj]
|
| 807 |
+
vote = cute.arch.vote_ballot_sync(nz != Int32(0))
|
| 808 |
+
if lane == 0:
|
| 809 |
+
counts[warp] = vote.to(Int32)
|
| 810 |
+
cute.arch.sync_threads()
|
| 811 |
+
if (counts[0] | counts[1] | counts[2] | counts[3]) == Int32(0):
|
| 812 |
+
bound = update_bound
|
| 813 |
+
skv = Float32(0) # confirmed zero codes: avoid 0 * infinity after scaling
|
| 814 |
+
bexp = ((float_bits(bound) >> 23) & 255) - 127
|
| 815 |
+
e = cutlass.min(cutlass.max((Int32(13) - bexp) & Int32(-2), Int32(-120)), Int32(120))
|
| 816 |
+
# Keep the scaled key and old-U operands finite even if their matching A operand is zero.
|
| 817 |
+
operand_peak = cute.arch.fmax(mx[3], mx[5])
|
| 818 |
+
operand_cap = (Int32(247) - ((float_bits(operand_peak) >> 23) & 255)) & Int32(-2)
|
| 819 |
+
e = cutlass.min(e, operand_cap)
|
| 820 |
+
up = bits_float((e + 127) << 23)
|
| 821 |
+
half_down = bits_float((127 - (e >> 1)) << 23)
|
| 822 |
+
# ---------------- prep part 2: scaled operands ----------------
|
| 823 |
+
ncol = tid
|
| 824 |
+
skp[ncol] = skv * Float32(1.0 / 127.0) * up
|
| 825 |
+
kh = cute.make_rmem_tensor(8, Int32)
|
| 826 |
+
kl = cute.make_rmem_tensor(8, Int32)
|
| 827 |
+
for jp in cutlass.range_constexpr(8):
|
| 828 |
+
a0, a1 = cute.arch.mul_packed_f32x2((keys[2 * jp], keys[2 * jp + 1]), (up, up), ftz=False)
|
| 829 |
+
h = pack_bf16(a0, a1)
|
| 830 |
+
r0 = a0 - bits_float(h << 16)
|
| 831 |
+
r1 = a1 - bits_float(h & Int32(-65536))
|
| 832 |
+
kh[jp] = h
|
| 833 |
+
kl[jp] = pack_bf16(r0, r1)
|
| 834 |
+
for c in cutlass.range_constexpr(2):
|
| 835 |
+
sts128(sw32(base + KB, ncol, c), kh[4 * c], kh[4 * c + 1], kh[4 * c + 2], kh[4 * c + 3])
|
| 836 |
+
sts128(sw32(base + GB, ncol, c), kl[4 * c], kl[4 * c + 1], kl[4 * c + 2], kl[4 * c + 3])
|
| 837 |
+
# fp16 Q is exact in TF32; split scaled, decayed U into two TF32 terms.
|
| 838 |
+
qrow = cute.make_rmem_tensor(4, Float32)
|
| 839 |
+
uhi = cute.make_rmem_tensor(4, Int32)
|
| 840 |
+
ulo = cute.make_rmem_tensor(4, Int32)
|
| 841 |
+
for r in cutlass.range_constexpr(4):
|
| 842 |
+
qrow[r] = qo[r]
|
| 843 |
+
us = uo[r] * up
|
| 844 |
+
uhi[r] = tf32_bits(us)
|
| 845 |
+
ulo[r] = tf32_bits(us - bits_float(uhi[r]))
|
| 846 |
+
for c in cutlass.range_constexpr(2):
|
| 847 |
+
cute.autovec_copy(qrow, cute.make_tensor(cute.make_ptr(Float32, sw32(base + SF, tid, c), cute.AddressSpace.smem, assumed_align=16), cute.make_layout(4)))
|
| 848 |
+
usrc = uhi if c == 0 else ulo
|
| 849 |
+
cute.autovec_copy(usrc, cute.make_tensor(cute.make_ptr(Int32, sw32(base + SF + 4096, ncol, c), cute.AddressSpace.smem, assumed_align=16), cute.make_layout(4)))
|
| 850 |
+
fence_async_smem()
|
| 851 |
+
cute.arch.sync_threads()
|
| 852 |
+
if warp == 0:
|
| 853 |
+
mma_rb.set(tc.Field.ACCUMULATE, False)
|
| 854 |
+
cute.gemm(mma_rb, acc_t, a_win, b_hi, acc_t)
|
| 855 |
+
mma_rb.set(tc.Field.ACCUMULATE, True)
|
| 856 |
+
cute.gemm(mma_rb, acc_t, a_win, b_lo, acc_t)
|
| 857 |
+
mma_r.set(tc.Field.ACCUMULATE, True)
|
| 858 |
+
cute.gemm(mma_r, acc_t, r_a, r_b, acc_t)
|
| 859 |
+
with cute.arch.elect_one():
|
| 860 |
+
tc.commit(mb_mma, None, tc.CtaGroup.ONE)
|
| 861 |
+
# window resets (the inputs are in smem; issued while the rebuild product runs; for small calls in the P wait,
|
| 862 |
+
# after the codes' DRAM burst)
|
| 863 |
+
if cutlass.const_expr(fraction is None):
|
| 864 |
+
reset_window(base, gb, wb, pb, ph, tid, fraction)
|
| 865 |
+
mbar_spin(mb_mma.toint().to(Int32), work & 1)
|
| 866 |
+
tc_after()
|
| 867 |
+
mbar_wait(mb_codes, work & 1)
|
| 868 |
+
# ---------------- pass A: S' = acc + c * skpc' * sv (thread = row), back to TMEM, fp16 copy ----------------
|
| 869 |
+
r8 = tid & 7
|
| 870 |
+
keep = cute.make_rmem_tensor(8, Float32)
|
| 871 |
+
# 16-column chunks, software-pipelined: chunk h+1's TMEM values and codes are in flight while chunk h is
|
| 872 |
+
# converted (each thread reads and rewrites only its own row; chunk h's fp16 stores reach only code
|
| 873 |
+
# chunks that are already consumed)
|
| 874 |
+
acc_n = tmem_load_nowait(tbase, '32x32b.x16', 16)
|
| 875 |
+
cw_n = lds128(sw128(base + SF + 16384, tid, 0))
|
| 876 |
+
tc_wait_ld()
|
| 877 |
+
for h in cutlass.range_constexpr(8):
|
| 878 |
+
j, g = h // 2, h % 2
|
| 879 |
+
acc, cw = acc_n, cw_n
|
| 880 |
+
if cutlass.const_expr(h < 7):
|
| 881 |
+
acc_n = tmem_load_nowait(tbase + 16 * (h + 1), '32x32b.x16', 16)
|
| 882 |
+
cw_n = lds128(sw128(base + SF + 16384, tid, h + 1))
|
| 883 |
+
sk16 = []
|
| 884 |
+
for q in cutlass.range_constexpr(4):
|
| 885 |
+
sk16 += lds128f(base + SKP + (16 * h + 4 * q) * 4)
|
| 886 |
+
out = [None] * 16
|
| 887 |
+
for hh in cutlass.range_constexpr(2):
|
| 888 |
+
for c in cutlass.range_constexpr(4):
|
| 889 |
+
n0 = 8 * hh + 2 * c
|
| 890 |
+
word = cw[c]
|
| 891 |
+
# Exact byte-to-float conversion through the fp32 mantissa,
|
| 892 |
+
# keeping both bytes on the packed arithmetic path.
|
| 893 |
+
wx = word ^ Int32(-2139062144)
|
| 894 |
+
c0, c1 = cute.arch.add_packed_f32x2((magic_byte(wx, 2 * hh), magic_byte(wx, 2 * hh + 1)), (Float32(-32896.0), Float32(-32896.0)))
|
| 895 |
+
d0, d1 = cute.arch.mul_packed_f32x2((c0, c1), (sk16[n0], sk16[n0 + 1]), ftz=False)
|
| 896 |
+
out[n0], out[n0 + 1] = cute.arch.fma_packed_f32x2((d0, d1), (svv, svv), (acc[n0], acc[n0 + 1]), ftz=False)
|
| 897 |
+
tmem_store(tbase + 16 * h, '32x32b.x16', out)
|
| 898 |
+
if cutlass.const_expr(h == 7):
|
| 899 |
+
for i in cutlass.range_constexpr(8):
|
| 900 |
+
keep[i] = out[8 + i]
|
| 901 |
+
hw = [pack_half(out[2 * i], out[2 * i + 1]) for i in range(8)]
|
| 902 |
+
for qq in cutlass.range_constexpr(2):
|
| 903 |
+
q = 2 * g + qq
|
| 904 |
+
sts128(base + SF + (j // 2) * 16384 + tid * 128 + (((4 * (j % 2) + q) ^ r8) << 4), hw[4 * qq], hw[4 * qq + 1], hw[4 * qq + 2], hw[4 * qq + 3])
|
| 905 |
+
if cutlass.const_expr(h < 7):
|
| 906 |
+
tc_wait_ld()
|
| 907 |
+
if cutlass.const_expr(dbg == 1):
|
| 908 |
+
for j in cutlass.range_constexpr(4):
|
| 909 |
+
vals = tmem_load(tbase + 32 * j, '32x32b.x32', 32)
|
| 910 |
+
for i in cutlass.range_constexpr(32):
|
| 911 |
+
dbgp[(ph * 128 + tid) * 129 + 32 * j + i] = vals[i]
|
| 912 |
+
dbgp[(ph * 128 + tid) * 129 + 128] = up
|
| 913 |
+
tc_wait_st()
|
| 914 |
+
fence_async_smem()
|
| 915 |
+
tc_before()
|
| 916 |
+
cute.arch.sync_threads()
|
| 917 |
+
# ---------------- subspace iteration: P = S'^T q0, Q = S' P, QR, U = S'^T Q ----------------
|
| 918 |
+
if warp == 0:
|
| 919 |
+
tc_after()
|
| 920 |
+
mma_p.set(tc.Field.ACCUMULATE, False)
|
| 921 |
+
for it in cutlass.range_constexpr(8):
|
| 922 |
+
cute.gemm(mma_p, skinny_acc, ps_a[None, None, it], ps_seed[None, None, it], skinny_acc)
|
| 923 |
+
mma_p.set(tc.Field.ACCUMULATE, True)
|
| 924 |
+
with cute.arch.elect_one():
|
| 925 |
+
tc.commit(mb_mma, None, tc.CtaGroup.ONE)
|
| 926 |
+
if cutlass.const_expr(fraction is not None):
|
| 927 |
+
reset_window(base, gb, wb, pb, ph, tid, fraction)
|
| 928 |
+
mbar_spin(mb_mma.toint().to(Int32), (work & 1) ^ 1)
|
| 929 |
+
tc_after()
|
| 930 |
+
pv8 = tmem_load(tbase + 120, '32x32b.x8', 8) # S'^T (q0 high) and S'^T (q0 low)
|
| 931 |
+
pv = [None] * 4
|
| 932 |
+
for r in cutlass.range_constexpr(2):
|
| 933 |
+
pv[2*r], pv[2*r+1] = cute.arch.add_packed_f32x2((pv8[2*r],pv8[2*r+1]),(pv8[4+2*r],pv8[5+2*r]))
|
| 934 |
+
psc = [None] * 4
|
| 935 |
+
for rr in cutlass.range_constexpr(2):
|
| 936 |
+
psc[2*rr], psc[2*rr+1] = cute.arch.mul_packed_f32x2((pv[2*rr],pv[2*rr+1]),(Float32(1.0/256),Float32(1.0/256)),ftz=False)
|
| 937 |
+
pw2 = cute.make_rmem_tensor(2, Int32)
|
| 938 |
+
pw2[0], pw2[1] = pack_half(psc[0],psc[1]), pack_half(psc[2],psc[3])
|
| 939 |
+
cute.autovec_copy(pw2, cute.make_tensor(cute.make_ptr(Int32, base + SKB + tid * 16, cute.AddressSpace.smem, assumed_align=8), cute.make_layout(2)))
|
| 940 |
+
fence_async_smem()
|
| 941 |
+
tc_before()
|
| 942 |
+
cute.arch.sync_threads()
|
| 943 |
+
if warp == 0:
|
| 944 |
+
tc_after()
|
| 945 |
+
mma_q.set(tc.Field.ACCUMULATE, False)
|
| 946 |
+
for it in cutlass.range_constexpr(8):
|
| 947 |
+
cute.gemm(mma_q, skinny_acc, qs_a[None, None, it], qs_b[None, None, it], skinny_acc)
|
| 948 |
+
mma_q.set(tc.Field.ACCUMULATE, True)
|
| 949 |
+
with cute.arch.elect_one():
|
| 950 |
+
tc.commit(mb_mma, None, tc.CtaGroup.ONE)
|
| 951 |
+
# the next window (its regions are free since the rebuild product) while Q runs: issued in the P wait, its
|
| 952 |
+
# copies kept warps 0 / 1 ~300 cycles behind the others at the P-stage barrier
|
| 953 |
+
if warp != 0:
|
| 954 |
+
if work + 1 < total:
|
| 955 |
+
issue_window(base, kb, gb, wb, pb, raw, due[work + 1], mb_win.toint().to(Int32), mb_win, warp, lane, tma_atom_u, t_gu, t_su, fraction)
|
| 956 |
+
mbar_spin(mb_mma.toint().to(Int32), work & 1)
|
| 957 |
+
tc_after()
|
| 958 |
+
qv4 = tmem_load(tbase + 120, '32x32b.x4', 4) # (the skinny operand's columns 4-7 are zero)
|
| 959 |
+
qrow = cute.make_rmem_tensor(4, Float32)
|
| 960 |
+
for r in cutlass.range_constexpr(4):
|
| 961 |
+
qrow[r] = qv4[r]
|
| 962 |
+
cute.autovec_copy(qrow, cute.make_tensor(cute.make_ptr(Float32, base + QVB + tid * 16, cute.AddressSpace.smem, assumed_align=16), cute.make_layout(4)))
|
| 963 |
+
tc_before()
|
| 964 |
+
cute.arch.sync_threads()
|
| 965 |
+
orthogonalize(base + QVB, base + SKB, tid, Float32(TAU), False)
|
| 966 |
+
# U = S'^T Q: only warp 0 wrote Q (the fp16 state and the skinny accumulator columns are ordered by the
|
| 967 |
+
# earlier barriers), so warp 0 issues the product right after its QR; the barrier only orders warps 1-3's
|
| 968 |
+
# reads of their Q rows in the U stage
|
| 969 |
+
if warp == 0:
|
| 970 |
+
fence_async_smem()
|
| 971 |
+
cute.arch.sync_warp() # every lane's Q rows (and fence) before the elected lane's MMA issue
|
| 972 |
+
tc_after()
|
| 973 |
+
mma_p.set(tc.Field.ACCUMULATE, False)
|
| 974 |
+
for it in cutlass.range_constexpr(8):
|
| 975 |
+
cute.gemm(mma_p, skinny_acc, ps_a[None, None, it], ps_b[None, None, it], skinny_acc)
|
| 976 |
+
mma_p.set(tc.Field.ACCUMULATE, True)
|
| 977 |
+
with cute.arch.elect_one():
|
| 978 |
+
tc.commit(mb_mma, None, tc.CtaGroup.ONE)
|
| 979 |
+
cute.arch.sync_threads()
|
| 980 |
+
mbar_spin(mb_mma.toint().to(Int32), (work & 1) ^ 1)
|
| 981 |
+
tc_after()
|
| 982 |
+
uv = tmem_load(tbase + 120, '32x32b.x4', 4) # (the skinny operand's columns 4-7 are zero)
|
| 983 |
+
tmem_store(tbase + 120, '32x32b.x8', [keep[i] for i in range(8)]) # restore S' columns 120-127 (U is read)
|
| 984 |
+
# new factors: u_new = fp16(U' 2^-e) at key pi(tid), q_new = fp16 Q row tid
|
| 985 |
+
down = bits_float((127 - e) << 23)
|
| 986 |
+
uq = cute.make_tensor(cute.recast_ptr(rawhead + 4352, dtype=Float16), cute.make_layout((4, 256), stride=(256, 1)))
|
| 987 |
+
kq = pi_of(tid)
|
| 988 |
+
qh = cute.make_rmem_tensor(2, Int32)
|
| 989 |
+
cute.autovec_copy(cute.make_tensor(cute.make_ptr(Int32, base + SKB + tid * 16, cute.AddressSpace.smem, assumed_align=8), cute.make_layout(2)), qh)
|
| 990 |
+
qhh = cute.recast_tensor(qh, Float16)
|
| 991 |
+
rbw = cute.make_rmem_tensor(4, Float32)
|
| 992 |
+
raw4 = cute.make_rmem_tensor(4, Float32)
|
| 993 |
+
uns = []
|
| 994 |
+
for r in cutlass.range_constexpr(4):
|
| 995 |
+
un = (uv[r] * down).to(Float16)
|
| 996 |
+
uns.append(un)
|
| 997 |
+
rbw[r] = -(un.to(Float32) * up)
|
| 998 |
+
raw4[r] = qhh[r].to(Float32)
|
| 999 |
+
zero4 = cute.make_rmem_tensor(4, Float32)
|
| 1000 |
+
for r in cutlass.range_constexpr(4):
|
| 1001 |
+
zero4[r] = Float32(0)
|
| 1002 |
+
# residual operands (tf32, K-major SW32): A row tid = q_new, B row tid = -2^e u_new
|
| 1003 |
+
# (A's upper half keeps fp16 state bytes, always finite as tf32, and meets B's zero half)
|
| 1004 |
+
cute.autovec_copy(raw4, cute.make_tensor(cute.make_ptr(Float32, sw32(base + SF, tid, 0), cute.AddressSpace.smem, assumed_align=16), cute.make_layout(4)))
|
| 1005 |
+
for c in cutlass.range_constexpr(2):
|
| 1006 |
+
src_b = rbw if c == 0 else zero4
|
| 1007 |
+
cute.autovec_copy(src_b, cute.make_tensor(cute.make_ptr(Float32, sw32(base + SF + 4096, tid, c), cute.AddressSpace.smem, assumed_align=16), cute.make_layout(4)))
|
| 1008 |
+
tc_wait_st()
|
| 1009 |
+
fence_async_smem()
|
| 1010 |
+
tc_before()
|
| 1011 |
+
cute.arch.sync_threads()
|
| 1012 |
+
if warp == 0:
|
| 1013 |
+
tc_after()
|
| 1014 |
+
mma_r.set(tc.Field.ACCUMULATE, True)
|
| 1015 |
+
cute.gemm(mma_r, acc_t, r_a, r_b, acc_t)
|
| 1016 |
+
with cute.arch.elect_one():
|
| 1017 |
+
tc.commit(mb_mma, None, tc.CtaGroup.ONE)
|
| 1018 |
+
# the fp16 state is no longer read (U is done): the next program's codes may land in its upper half
|
| 1019 |
+
if warp == 3: # (warp 0 issues the products)
|
| 1020 |
+
if work + 1 < total:
|
| 1021 |
+
pn = due[work + 1]
|
| 1022 |
+
if lane == 0:
|
| 1023 |
+
mbar_expect(mb_codes.toint().to(Int32), 16384)
|
| 1024 |
+
cute.copy(tma_atom_c, t_gc[(None, pn % 32, pn // 32)], t_sc, tma_bar_ptr=mb_codes, cache_policy=l2_policy(fraction))
|
| 1025 |
+
# the new factors leave while the residual product runs
|
| 1026 |
+
for r in cutlass.range_constexpr(4):
|
| 1027 |
+
uq[r, kq] = uns[r]
|
| 1028 |
+
uq[r, 128 + tid] = qhh[r]
|
| 1029 |
+
mbar_spin(mb_mma.toint().to(Int32), work & 1)
|
| 1030 |
+
tc_after()
|
| 1031 |
+
if cutlass.const_expr(dbg == 2):
|
| 1032 |
+
for j in cutlass.range_constexpr(4):
|
| 1033 |
+
vals = tmem_load(tbase + 32 * j, '32x32b.x32', 32)
|
| 1034 |
+
for i in cutlass.range_constexpr(32):
|
| 1035 |
+
dbgp[(ph * 128 + tid) * 129 + 32 * j + i] = vals[i]
|
| 1036 |
+
dbgp[(ph * 128 + tid) * 129 + 128] = up
|
| 1037 |
+
# ---------------- pass B: column sums of |E'| in registers (16x256b, transpose-reduce over 8 lanes) ----------------
|
| 1038 |
+
cs = [None] * 32
|
| 1039 |
+
for lb in cutlass.range_constexpr(2):
|
| 1040 |
+
ev = tmem_load(tbase + ((16 * lb) << 16), '16x256b.x16', 64)
|
| 1041 |
+
for b in cutlass.range_constexpr(16):
|
| 1042 |
+
p0, p1 = cute.arch.add_packed_f32x2((cute.math.abs(ev[4 * b]), cute.math.abs(ev[4 * b + 1])),
|
| 1043 |
+
(cute.math.abs(ev[4 * b + 2]), cute.math.abs(ev[4 * b + 3])))
|
| 1044 |
+
if cutlass.const_expr(lb == 0):
|
| 1045 |
+
cs[2 * b], cs[2 * b + 1] = p0, p1
|
| 1046 |
+
else:
|
| 1047 |
+
cs[2 * b], cs[2 * b + 1] = cute.arch.add_packed_f32x2((cs[2 * b], cs[2 * b + 1]), (p0, p1))
|
| 1048 |
+
cur = cs
|
| 1049 |
+
for st in cutlass.range_constexpr(3):
|
| 1050 |
+
half = 16 >> st
|
| 1051 |
+
hb = ((lane >> (4 - st)) & 1) == 1
|
| 1052 |
+
nxt = []
|
| 1053 |
+
for j in cutlass.range_constexpr(half):
|
| 1054 |
+
snd = Float32(cutlass.select_(hb, cur[j], cur[half + j]))
|
| 1055 |
+
kp = Float32(cutlass.select_(hb, cur[half + j], cur[j]))
|
| 1056 |
+
nxt.append(kp + cute.arch.shuffle_sync_bfly(snd, half))
|
| 1057 |
+
cur = nxt
|
| 1058 |
+
colp = cute.make_rmem_tensor(4, Float32)
|
| 1059 |
+
for j in cutlass.range_constexpr(4):
|
| 1060 |
+
colp[j] = cur[j]
|
| 1061 |
+
cute.autovec_copy(colp, cute.make_tensor(cute.make_ptr(Float32, base + QVB + warp * 512 + lane * 16, cute.AddressSpace.smem, assumed_align=16), cute.make_layout(4)))
|
| 1062 |
+
cute.arch.sync_threads()
|
| 1063 |
+
colsum = cute.make_tensor(cute.make_ptr(Float32, base + QVB, cute.AddressSpace.smem, assumed_align=16), cute.make_layout(512))
|
| 1064 |
+
csum = (colsum[tid] + colsum[128 + tid]) + (colsum[256 + tid] + colsum[384 + tid])
|
| 1065 |
+
half_up = bits_float((127 + (e >> 1)) << 23)
|
| 1066 |
+
rskn = cute.arch.fmin(cute.math.rsqrt(csum * Float32(1.0 / 128), fastmath=True), Float32(1e12) * half_down)
|
| 1067 |
+
scales = cute.make_tensor(rawhead + 4096, cute.make_layout(256))
|
| 1068 |
+
# Round the reciprocal once, then use its inverse as the output scale.
|
| 1069 |
+
# Keeping both sides consistent preserves the quantized reconstruction.
|
| 1070 |
+
# fp16 reciprocal (11-bit mantissa keeps the quantization grid within 2^-12 of the reference's, so the codes
|
| 1071 |
+
# track the reference's rounding; rskn >= 2^-7 here, the clamp only touches columns that are zero to ~1e-14
|
| 1072 |
+
# of the head), and its inverse as the output scale
|
| 1073 |
+
recip_h = cute.arch.fmin(rskn, Float32(65504.0)).to(Float16)
|
| 1074 |
+
recip = recip_h.to(Float32)
|
| 1075 |
+
scales[tid] = cute.arch.rcp_approx(recip) * half_down
|
| 1076 |
+
nt = pi_inv(tid)
|
| 1077 |
+
packed_sk = cute.make_tensor(cute.make_ptr(Float16, base + SKP, cute.AddressSpace.smem, assumed_align=16), cute.make_layout(128))
|
| 1078 |
+
packed_sk[(((nt >> 4) * 4 + ((nt >> 1) & 3)) * 4) + ((nt >> 3) & 1) * 2 + (nt & 1)] = recip_h
|
| 1079 |
+
ev_first = tmem_load_nowait(tbase, '16x256b.x16', 64) # pass C's first block, in flight across the barrier
|
| 1080 |
+
cute.arch.sync_threads()
|
| 1081 |
+
tc_wait_ld()
|
| 1082 |
+
# ---------------- pass C: row scales and codes (16x256b, permuted columns), stmatrix into SF[0:16K] ----------------
|
| 1083 |
+
c4 = lane & 3
|
| 1084 |
+
eps_v = Float32(1e-12) * half_up
|
| 1085 |
+
rowsc = []
|
| 1086 |
+
rsk_packed = []
|
| 1087 |
+
for q in cutlass.range_constexpr(8):
|
| 1088 |
+
rsk_packed += _smem_vec(Int32, base + SKP + (q * 4 + c4) * 8, 2, 8)
|
| 1089 |
+
for lb in cutlass.range_constexpr(2):
|
| 1090 |
+
ev = ev_first if lb == 0 else tmem_load(tbase + ((16 * lb) << 16), '16x256b.x16', 64)
|
| 1091 |
+
x = [None] * 64
|
| 1092 |
+
m0, m1 = Float32(0), Float32(0)
|
| 1093 |
+
for b in cutlass.range_constexpr(16):
|
| 1094 |
+
rs = f16x2_f32(rsk_packed[b])
|
| 1095 |
+
x[4 * b], x[4 * b + 1] = cute.arch.mul_packed_f32x2((ev[4 * b], ev[4 * b + 1]), (rs[0], rs[1]), ftz=False)
|
| 1096 |
+
x[4 * b + 2], x[4 * b + 3] = cute.arch.mul_packed_f32x2((ev[4 * b + 2], ev[4 * b + 3]), (rs[0], rs[1]), ftz=False)
|
| 1097 |
+
m0 = cute.arch.fmax(m0, cute.arch.fmax(cute.math.abs(x[4 * b]), cute.math.abs(x[4 * b + 1])))
|
| 1098 |
+
m1 = cute.arch.fmax(m1, cute.arch.fmax(cute.math.abs(x[4 * b + 2]), cute.math.abs(x[4 * b + 3])))
|
| 1099 |
+
for sh in cutlass.range_constexpr(2):
|
| 1100 |
+
m0 = cute.arch.fmax(m0, cute.arch.shuffle_sync_bfly(m0, 1 << sh))
|
| 1101 |
+
m1 = cute.arch.fmax(m1, cute.arch.shuffle_sync_bfly(m1, 1 << sh))
|
| 1102 |
+
m0 = cute.arch.fmax(m0, eps_v)
|
| 1103 |
+
m1 = cute.arch.fmax(m1, eps_v)
|
| 1104 |
+
row0 = warp * 32 + 16 * lb + (lane >> 2)
|
| 1105 |
+
rowsc.append(m0 * half_down)
|
| 1106 |
+
rowsc.append(m1 * half_down)
|
| 1107 |
+
f0 = Float32(127) * cute.arch.rcp_approx(m0)
|
| 1108 |
+
f1 = Float32(127) * cute.arch.rcp_approx(m1)
|
| 1109 |
+
wds = [[None] * 8, [None] * 8]
|
| 1110 |
+
for mm in cutlass.range_constexpr(8):
|
| 1111 |
+
wds[0][mm] = quant_pack(x[8 * mm], x[8 * mm + 1], x[8 * mm + 4], x[8 * mm + 5], f0)
|
| 1112 |
+
wds[1][mm] = quant_pack(x[8 * mm + 2], x[8 * mm + 3], x[8 * mm + 6], x[8 * mm + 7], f1)
|
| 1113 |
+
jj = lane >> 3
|
| 1114 |
+
xr = jj & 1
|
| 1115 |
+
rho = lane & 7
|
| 1116 |
+
vrow = warp * 32 + 16 * lb + 8 * xr + rho
|
| 1117 |
+
for g in cutlass.range_constexpr(4):
|
| 1118 |
+
mcol = 2 * g + (jj >> 1)
|
| 1119 |
+
addr = base + SF + vrow * 128 + ((mcol ^ (vrow & 7)) << 4)
|
| 1120 |
+
stsm4(addr, wds[0][2 * g], wds[1][2 * g], wds[0][2 * g + 1], wds[1][2 * g + 1])
|
| 1121 |
+
fence_async_smem()
|
| 1122 |
+
cute.arch.sync_threads()
|
| 1123 |
+
if warp == 0:
|
| 1124 |
+
cute.copy(tma_atom_s, t_ss, t_gs[(None, head, slot)], cache_policy=l2_policy(fraction))
|
| 1125 |
+
bulk_commit()
|
| 1126 |
+
if c4 == 0: # row scales leave after the code store is issued
|
| 1127 |
+
for lb in cutlass.range_constexpr(2):
|
| 1128 |
+
row0 = warp * 32 + 16 * lb + (lane >> 2)
|
| 1129 |
+
scales[128 + row0] = rowsc[2 * lb]
|
| 1130 |
+
scales[136 + row0] = rowsc[2 * lb + 1]
|
| 1131 |
+
|
| 1132 |
+
if total > 0:
|
| 1133 |
+
if warp == 0:
|
| 1134 |
+
bulk_wait_read() # the last code store has read SF (its global writes complete with the grid)
|
| 1135 |
+
cute.arch.sync_threads()
|
| 1136 |
+
if warp == 0:
|
| 1137 |
+
cute.arch.dealloc_tmem(tp, 128)
|
| 1138 |
+
|
| 1139 |
+
|
| 1140 |
+
@cute.jit
|
| 1141 |
+
def launch(raw: cute.Pointer, kb: cute.Pointer, ub: cute.Pointer, gb: cute.Pointer, wb: cute.Pointer, pb: cute.Pointer,
|
| 1142 |
+
hc: cute.Pointer, desc: cute.Pointer, start: cute.Pointer, indices: cute.Pointer, dbgp: cute.Pointer,
|
| 1143 |
+
n: Int32, nprog_pool: Int32, stream: cuda.CUstream, blocks: cutlass.Constexpr, dbg: cutlass.Constexpr, fraction: cutlass.Constexpr = None):
|
| 1144 |
+
# the pool's codes as (row, code, head, slot) int8; one program's 128 x 128 tile lands K-major SW128 (descriptor
|
| 1145 |
+
# in the kernel parameters)
|
| 1146 |
+
codes_ptr = cute.make_ptr(Int8, raw.toint() + OFF * 4, cute.AddressSpace.gmem, assumed_align=16)
|
| 1147 |
+
codes_g = cute.make_tensor(codes_ptr, cute.make_layout((128, 128, 32, nprog_pool // 32), stride=(128, 1, 65536, 4 * SS)))
|
| 1148 |
+
codes_layout = cute.tile_to_shape(tc.make_smem_layout_atom(tc.SmemLayoutAtomKind.K_SW128, Int8), (128, 128), order=(0, 1))
|
| 1149 |
+
tma_atom_c, tma_c = cpasync.make_tiled_tma_atom(cpasync.CopyBulkTensorTileG2SOp(), codes_g, codes_layout, (128, 128))
|
| 1150 |
+
tma_atom_s, tma_s = cpasync.make_tiled_tma_atom(cpasync.CopyBulkTensorTileS2GOp(), codes_g, codes_layout, (128, 128))
|
| 1151 |
+
# each program's ubuf as (value, entry, program), landing as the MN-major SW128 window A operand
|
| 1152 |
+
ub_g = cute.make_tensor(cute.make_ptr(BFloat16, ub.toint(), cute.AddressSpace.gmem, assumed_align=16),
|
| 1153 |
+
cute.make_layout((128, 16, nprog_pool), stride=(1, 128, 2048)))
|
| 1154 |
+
ub_layout = cute.tile_to_shape(tc.make_smem_layout_atom(tc.SmemLayoutAtomKind.MN_SW128, BFloat16), (128, 16), order=(1, 0))
|
| 1155 |
+
tma_atom_u, tma_u = cpasync.make_tiled_tma_atom(cpasync.CopyBulkTensorTileG2SOp(), ub_g, ub_layout, (128, 16))
|
| 1156 |
+
flush_kernel(raw.toint(), kb.toint(), ub.toint(), gb.toint(), wb.toint(), pb.toint(),
|
| 1157 |
+
hc.toint(), desc.toint(), start.toint(), indices.toint(), dbgp.toint(), n, tma_atom_c, tma_c,
|
| 1158 |
+
tma_atom_s, tma_s, tma_atom_u, tma_u, blocks, dbg, fraction).launch(
|
| 1159 |
+
grid=(cutlass.max(Int32(1), cutlass.min(n * 32, Int32(blocks))), 1, 1),
|
| 1160 |
+
block=(128, 1, 1), min_blocks_per_mp=CTAS_PER_SM, stream=stream)
|
| 1161 |
+
|
| 1162 |
+
|
| 1163 |
+
def _ptr(t, dtype):
|
| 1164 |
+
return make_ptr(dtype, t.data_ptr(), cute.AddressSpace.gmem, assumed_align=16)
|
| 1165 |
+
|
| 1166 |
+
|
| 1167 |
+
_COMPILED = {}
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
class Pool:
|
| 1171 |
+
"""The serving engine's unchanged strided checkpoint and window layout."""
|
| 1172 |
+
def __init__(self, num_slots, device="cuda", dbg=0):
|
| 1173 |
+
self.NS = num_slots
|
| 1174 |
+
self.raw = torch.zeros(num_slots * SS + OFF, dtype=torch.float32, device=device)
|
| 1175 |
+
storage = self.raw.untyped_storage()
|
| 1176 |
+
def view(dtype, shape, strides, off):
|
| 1177 |
+
return torch.empty(0, dtype=dtype, device=device).set_(storage).as_strided(shape, strides, off)
|
| 1178 |
+
self.codes = view(torch.int8, (num_slots, 32, 128, 128), (4 * SS, 65536, 128, 1), 4 * OFF)
|
| 1179 |
+
self.codes32 = view(torch.int32, (num_slots, 32, 128, 32), (SS, 16384, 32, 1), OFF)
|
| 1180 |
+
self.codes16 = view(torch.int16, (num_slots, 32, 128, 64), (2 * SS, 32768, 64, 1), 2 * OFF)
|
| 1181 |
+
self.s_k = view(torch.float32, (num_slots, 32, 128), (SS, 16384, 1), OFF + 4096)
|
| 1182 |
+
self.s_v = view(torch.float32, (num_slots, 32, 128), (SS, 16384, 1), OFF + 4224)
|
| 1183 |
+
self.s_kv = view(torch.float32, (num_slots, 32, 256), (SS, 16384, 1), OFF + 4096)
|
| 1184 |
+
self.uq = view(torch.float16, (num_slots, 32, 4, 256), (2 * SS, 32768, 256, 1), 2 * (OFF + 4352))
|
| 1185 |
+
self.kbuf = torch.zeros(num_slots, 32, 16, 128, dtype=torch.bfloat16, device=device)
|
| 1186 |
+
self.ubuf = torch.zeros_like(self.kbuf)
|
| 1187 |
+
self.gbuf = torch.ones(num_slots, 32, 16, 128, dtype=torch.float16, device=device)
|
| 1188 |
+
self.w = torch.zeros(num_slots, 32, 16, dtype=torch.float32, device=device)
|
| 1189 |
+
self.pcum = torch.zeros(num_slots, 32, 128, dtype=torch.float32, device=device)
|
| 1190 |
+
self.hcnt = torch.zeros(num_slots, 32, dtype=torch.int32, device=device)
|
| 1191 |
+
self.dbg = dbg
|
| 1192 |
+
self.dbgbuf = torch.zeros(1 if not dbg else max(num_slots * 32 * 128 * 129, 2048 * 32 * 20), dtype=torch.float32, device=device)
|
| 1193 |
+
with torch.cuda.device(self.raw.device):
|
| 1194 |
+
self.codes_map = encode_map(self.codes.data_ptr(), (128, 128, 32, num_slots), (128, 65536, 4 * SS), (128, 128, 1, 1),
|
| 1195 |
+
cuda.CUtensorMapDataType.CU_TENSOR_MAP_DATA_TYPE_UINT8,
|
| 1196 |
+
cuda.CUtensorMapSwizzle.CU_TENSOR_MAP_SWIZZLE_128B, self.raw.device)
|
| 1197 |
+
device_index = self.raw.device.index
|
| 1198 |
+
sms = torch.cuda.get_device_properties(self.raw.device).multi_processor_count
|
| 1199 |
+
self.blocks = sms * CTAS_PER_SM
|
| 1200 |
+
self._args = (_ptr(self.raw, Float32), _ptr(self.kbuf, BFloat16), _ptr(self.ubuf, BFloat16),
|
| 1201 |
+
_ptr(self.gbuf, Float16), _ptr(self.w, Float32), _ptr(self.pcum, Float32), _ptr(self.hcnt, Int32),
|
| 1202 |
+
_ptr(self.codes_map, Int64))
|
| 1203 |
+
self.kernels = {}
|
| 1204 |
+
with torch.cuda.device(device_index):
|
| 1205 |
+
# Every variant is ready before a caller captures flush_inplace.
|
| 1206 |
+
for fraction in (None, 0.75, 1.0):
|
| 1207 |
+
key = (device_index, self.blocks, dbg, fraction)
|
| 1208 |
+
if key not in _COMPILED:
|
| 1209 |
+
compiled = cute.compile(launch, *self._args, _ptr(self.pcum, Float32), _ptr(self.hcnt, Int32), _ptr(self.dbgbuf, Float32),
|
| 1210 |
+
Int32(1), Int32(num_slots * 32), cuda.CUstream(0), self.blocks, dbg, fraction,
|
| 1211 |
+
options="--generate-line-info --ptxas-options=--maxrregcount=128")
|
| 1212 |
+
_COMPILED[key] = compiled.to(device_index)
|
| 1213 |
+
self.kernels[fraction] = _COMPILED[key]
|
| 1214 |
+
self.kernel = self.kernels[None]
|
| 1215 |
+
|
| 1216 |
+
|
| 1217 |
+
def flush_inplace(pool, idx, q0):
|
| 1218 |
+
if idx.numel() == 0:
|
| 1219 |
+
return
|
| 1220 |
+
with torch.cuda.device(pool.raw.device):
|
| 1221 |
+
count = idx.numel()
|
| 1222 |
+
kernel = pool.kernels[0.75 if count <= 20 else 1.0 if count <= 64 else None]
|
| 1223 |
+
kernel(*pool._args, _ptr(q0, Float32), _ptr(idx, Int32), _ptr(pool.dbgbuf, Float32), Int32(idx.numel()),
|
| 1224 |
+
Int32(pool.NS * 32), cuda.CUstream(torch.cuda.current_stream(pool.raw.device).cuda_stream))
|
| 1225 |
+
|
| 1226 |
+
|
| 1227 |
+
def run(codes, s_k, s_v, u, q, kbuf, ubuf, gbuf, w, pcum, q0):
|
| 1228 |
+
b = codes.shape[0]
|
| 1229 |
+
pool = Pool(b + 8, codes.device)
|
| 1230 |
+
sl = slice(1, b + 1)
|
| 1231 |
+
pool.codes[sl] = codes
|
| 1232 |
+
pool.s_k[sl] = s_k
|
| 1233 |
+
pool.s_v[sl] = s_v
|
| 1234 |
+
pool.uq[sl, :, :, :128] = u
|
| 1235 |
+
pool.uq[sl, :, :, 128:] = q
|
| 1236 |
+
pool.kbuf[sl], pool.ubuf[sl], pool.gbuf[sl] = kbuf, ubuf, gbuf
|
| 1237 |
+
pool.w[sl], pool.pcum[sl] = w, pcum
|
| 1238 |
+
pool.hcnt[sl] = 16
|
| 1239 |
+
idx = torch.arange(1, b + 1, dtype=torch.int32, device=codes.device)
|
| 1240 |
+
flush_inplace(pool, idx, q0.contiguous())
|
| 1241 |
+
return (pool.codes[sl].clone(), pool.s_k[sl].clone(), pool.s_v[sl].clone(),
|
| 1242 |
+
pool.uq[sl, :, :, :128].clone(), pool.uq[sl, :, :, 128:].clone())
|
build/torch-cuda/metadata.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "kernels",
|
| 3 |
+
"id": "_humanfia_leapquant_cuda_6215db1dd13a6d5f",
|
| 4 |
+
"version": 1,
|
| 5 |
+
"license": "Apache-2.0",
|
| 6 |
+
"python-depends": [
|
| 7 |
+
"nvidia-cutlass-dsl"
|
| 8 |
+
],
|
| 9 |
+
"kernel-depends": [],
|
| 10 |
+
"backend": {
|
| 11 |
+
"type": "cuda",
|
| 12 |
+
"archs": [
|
| 13 |
+
"10.3"
|
| 14 |
+
]
|
| 15 |
+
},
|
| 16 |
+
"digest": {
|
| 17 |
+
"algorithm": "sha256",
|
| 18 |
+
"files": {
|
| 19 |
+
"LICENSE.txt": "z8d0m5b2O9McPEK1xHG/dWgUBT6EfBDz6wA0F7xSPTA=",
|
| 20 |
+
"__init__.py": "Apnx4rqE5UnXv9sg1yYjFyffJd+jA3bmk4YTnMYAI34=",
|
| 21 |
+
"_gdn.py": "pzS1nnWoyOhw1oKAxZxP4F6ePSM0xNfmLXEBxnyc2bY=",
|
| 22 |
+
"_kda.py": "L2NYlrcNE939doItcR91yMOrtGBvDM0l3QS1g7lbfsY="
|
| 23 |
+
}
|
| 24 |
+
}
|
| 25 |
+
}
|
gdn/README.md
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LeapQuant Gated DeltaNet checkpoint flush
|
| 2 |
+
|
| 3 |
+
CuTe DSL window-boundary re-quantization of the recurrent state for Gated DeltaNet.
|
| 4 |
+
This is the flush operation, with the checkpoint format and one-round subspace
|
| 5 |
+
iteration specified in [NVlabs/kda#10](https://github.com/NVlabs/kda/pull/10).
|
| 6 |
+
It does not implement the per-token decode operation or a complete model layer.
|
| 7 |
+
|
| 8 |
+
The final accepted implementation achieved **2.551x overall**
|
| 9 |
+
and **2.813x on batches 128, 256 and 512** versus the
|
| 10 |
+
request's TileLang baseline on NVIDIA B300 SXM6 AC. All six workloads passed the
|
| 11 |
+
original accuracy criterion. These are the final paired KDA measurements from
|
| 12 |
+
2026-10-24T10:57:39Z; they are kernel timings for the deployment interface, not timings
|
| 13 |
+
of allocation, input packing or the functional `run` wrapper.
|
| 14 |
+
|
| 15 |
+
## Requirements and supported inputs
|
| 16 |
+
|
| 17 |
+
- NVIDIA B300, CUDA compute capability **10.3**. This release advertises only the
|
| 18 |
+
tested architecture; other GPU architectures are not validated.
|
| 19 |
+
- CUDA 13-compatible driver; tested with PyTorch 2.12.1+cu130,
|
| 20 |
+
`nvidia-cutlass-dsl[cu13]==4.6.0` and `cuda-bindings==13.3.1`.
|
| 21 |
+
- Python 3.12 and `kernels==0.17.2` were used for package validation.
|
| 22 |
+
- Fixed geometry: 32 heads, value/key dimension 128, window 16, rank 4.
|
| 23 |
+
Dense benchmark batches: 16, 32, 64, 128, 256 and 512.
|
| 24 |
+
- `codes`: int8 `[B,32,128,128]`; `s_k`/`s_v`: fp32 `[B,32,128]`;
|
| 25 |
+
`u`/`q`: fp16 `[B,32,4,128]`; `kbuf`/`ubuf`: bf16 `[B,32,16,128]`;
|
| 26 |
+
`w`: fp32 `[B,32,16]`; `q0`: contiguous fp32 `[128,4]` on the same CUDA device.
|
| 27 |
+
- `p`: fp32 `[B,32]`, the window gate product in `(0,1]`.
|
| 28 |
+
|
| 29 |
+
Checkpoint scales are positive and the request's deployment domain has state
|
| 30 |
+
magnitudes below 1e4. See the complete [upstream input contract](https://github.com/NVlabs/kda/tree/48f02e6ba0e98a1841ab6f0a2d99a90b2de1a326/requests/conless-leapquant-gdn-flush)
|
| 31 |
+
and [reference definition](https://huggingface.co/kernels/humanfia-lab/kernels/blob/v1/gdn/definition.json).
|
| 32 |
+
|
| 33 |
+
## Load and use
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
import torch
|
| 37 |
+
from kernels import get_kernel
|
| 38 |
+
|
| 39 |
+
op = get_kernel("humanfia-lab/kernels", version=1, trust_remote_code=True).gdn
|
| 40 |
+
B, H, V, K, L, R = 16, 32, 128, 128, 16, 4
|
| 41 |
+
codes = torch.zeros(B, H, V, K, dtype=torch.int8, device="cuda")
|
| 42 |
+
s_k = torch.full((B, H, K), 0.05, device="cuda")
|
| 43 |
+
s_v = torch.full((B, H, V), 0.3, device="cuda")
|
| 44 |
+
u = torch.zeros(B, H, R, K, dtype=torch.float16, device="cuda")
|
| 45 |
+
q = torch.zeros(B, H, R, V, dtype=torch.float16, device="cuda")
|
| 46 |
+
kbuf = (torch.randn(B, H, L, K, device="cuda") * 0.3).bfloat16()
|
| 47 |
+
ubuf = (torch.randn(B, H, L, V, device="cuda") * 0.3).bfloat16()
|
| 48 |
+
w = torch.rand(B, H, L, device="cuda")
|
| 49 |
+
p = torch.ones(B, H, device="cuda")
|
| 50 |
+
q0 = torch.linalg.qr(torch.randn(V, R, device="cuda"))[0].contiguous()
|
| 51 |
+
|
| 52 |
+
new_codes, new_s_k, new_s_v, new_u, new_q = op.run(
|
| 53 |
+
codes, s_k, s_v, u, q, kbuf, ubuf, w, p, q0
|
| 54 |
+
)
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
`run` returns five fresh checkpoint tensors and leaves the supplied inputs
|
| 58 |
+
unchanged. It includes allocation/packing overhead. Use serial calls to `run`;
|
| 59 |
+
for independent concurrent streams, use an independent caller-owned `Pool` per
|
| 60 |
+
stream and keep calls on each pool ordered.
|
| 61 |
+
|
| 62 |
+
For serving, use the original caller-owned pool interface:
|
| 63 |
+
|
| 64 |
+
```python
|
| 65 |
+
pool = op.Pool(B + 8, device="cuda") # allocates buffers and JIT-compiles kernels
|
| 66 |
+
sl = slice(1, B + 1) # slot 0 is reserved
|
| 67 |
+
pool.codes[sl], pool.s_k[sl], pool.s_v[sl] = codes, s_k, s_v
|
| 68 |
+
pool.uq[sl, :, :, :K], pool.uq[sl, :, :, K:] = u, q
|
| 69 |
+
pool.kbuf[sl], pool.ubuf[sl], pool.w[sl] = kbuf, ubuf, w
|
| 70 |
+
pool.p[sl, :, 0] = p
|
| 71 |
+
pool.hcnt[sl] = L
|
| 72 |
+
idx = torch.arange(1, B + 1, dtype=torch.int32, device="cuda")
|
| 73 |
+
op.flush_inplace(pool, idx, q0) # checkpoint stays in pool; returns None
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
`idx` is a contiguous CUDA int32 vector of valid, unique slot indices. Index 0
|
| 77 |
+
is skipped. Only selected heads whose fill counter equals 16 are flushed;
|
| 78 |
+
non-due heads and unselected slots remain unchanged. A due head resets `w = 0`, `p = 1`.
|
| 79 |
+
The fill counter remains at `L`: the decode step interprets this as "flushed,
|
| 80 |
+
empty" and advances it. Flush does not clear it, because other CTAs may still
|
| 81 |
+
be scanning the due flags.
|
| 82 |
+
`q0` is the supplied fixed start basis, not the previous window's factors.
|
| 83 |
+
|
| 84 |
+
Construct the pool and perform warmup before CUDA graph capture. Refill the
|
| 85 |
+
window buffers and counters before each new window. Calls use the current CUDA
|
| 86 |
+
stream on the pool's device. Keep the pool, index vector and `q0` buffers alive
|
| 87 |
+
while a graph using their addresses is alive. The supplied `validate.py` checks
|
| 88 |
+
mixed due heads, slot 0, reset/no-op behavior, a non-default stream and graph
|
| 89 |
+
replay with changed input contents.
|
| 90 |
+
|
| 91 |
+
## Accuracy and timing
|
| 92 |
+
|
| 93 |
+
The original benchmark compares decoded checkpoints with the exactly rebuilt
|
| 94 |
+
fp64 state for structured edge-case heads, a second window and unstructured
|
| 95 |
+
in-domain random inputs at each batch size. For every head, reconstruction
|
| 96 |
+
error may be at most 1.01x the reference's error; nearly exact reference heads
|
| 97 |
+
use the original absolute cap `1e-3 * mean(abs(S))`. Outputs must be finite and
|
| 98 |
+
int8 codes must remain in [-127,127]. The upstream benchmark and thresholds are
|
| 99 |
+
included unchanged.
|
| 100 |
+
|
| 101 |
+
Deployment timing uses `flush_inplace`, all programs due, eight disjoint slot
|
| 102 |
+
sets rotated to avoid L2 reuse, four warmups and 16 measured iterations, and
|
| 103 |
+
CUDA kernel time from the PyTorch profiler. Large means batches >=128.
|
| 104 |
+
|
| 105 |
+
| Batch | Final paired speedup | Accuracy |
|
| 106 |
+
|---:|---:|---|
|
| 107 |
+
| 16 | 2.150x | pass |
|
| 108 |
+
| 32 | 2.249x | pass |
|
| 109 |
+
| 64 | 2.557x | pass |
|
| 110 |
+
| 128 | 2.816x | pass |
|
| 111 |
+
| 256 | 2.887x | pass |
|
| 112 |
+
| 512 | 2.739x | pass |
|
| 113 |
+
| Geomean, all six | 2.551x | 6/6 pass |
|
| 114 |
+
| Geomean, batch >=128 | 2.813x | 3/3 pass |
|
| 115 |
+
|
| 116 |
+
These measurements are workload- and hardware-specific. The functional `run`
|
| 117 |
+
wrapper is not the timed deployment entrypoint.
|
| 118 |
+
|
| 119 |
+
## Reproduce
|
| 120 |
+
|
| 121 |
+
Download the combined repository, then enter this component directory:
|
| 122 |
+
|
| 123 |
+
```bash
|
| 124 |
+
hf download humanfia-lab/kernels --repo-type kernel --revision v1 --local-dir leapquant-kernels
|
| 125 |
+
cd leapquant-kernels/gdn
|
| 126 |
+
python -m pip install torch==2.12.1 --index-url https://download.pytorch.org/whl/cu130
|
| 127 |
+
python -m pip install -r ../requirements.txt
|
| 128 |
+
python benchmark.py --impl ../build/torch-cuda/_gdn.py # six original workloads
|
| 129 |
+
python benchmark.py # original TileLang baseline
|
| 130 |
+
python validate.py # package loader and deployment checks
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
TileLang and `nvcc` on `PATH` are needed only to benchmark the original baseline.
|
| 134 |
+
The CuTe implementation JIT-compiles on first use; do not include compilation in
|
| 135 |
+
steady-state timings or perform first-use compilation inside graph capture.
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
The unchanged kernel passed all six original workloads (three input families
|
| 139 |
+
each) and deployment checks on B300 before consolidation; the original reports
|
| 140 |
+
are retained in `validation_results.json`. The speedup table retains the paired
|
| 141 |
+
optimization-run measurement, not a new baseline comparison.
|
| 142 |
+
|
| 143 |
+
## Files and provenance
|
| 144 |
+
|
| 145 |
+
The combined runtime is in `../build/torch-cuda/`; this component's unchanged
|
| 146 |
+
kernel is `_gdn.py`. The files in this directory provide its original
|
| 147 |
+
benchmark, baseline, definition, workloads, results, validation and provenance.
|
| 148 |
+
Shared dependencies and licenses are at the repository root.
|
| 149 |
+
|
| 150 |
+
The runtime kernel is byte-for-byte the final accepted submission
|
| 151 |
+
`8f705942197446f4` (SHA-256 `a734b59e75a8c8e870d68280c59c4fe05e9e3d2334c4d7e62d7101c67c9cd9b6`), from a 48-hour KDA experiment
|
| 152 |
+
with GPT 6.1 and Claude Opus 5.5. Request sources are pinned to public commit
|
| 153 |
+
`48f02e6ba0e98a1841ab6f0a2d99a90b2de1a326`. The release adds a public import wrapper, metadata
|
| 154 |
+
and validation scripts; it does not change the kernel algorithm. Apache-2.0;
|
| 155 |
+
see `../LICENSE.txt` and `../NOTICE`.
|
| 156 |
+
|
| 157 |
+
## Available functions
|
| 158 |
+
|
| 159 |
+
- `run`
|
| 160 |
+
- `Pool`
|
| 161 |
+
- `flush_inplace`
|
gdn/baseline.py
ADDED
|
@@ -0,0 +1,732 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
"""Best-known LeapQuant flush kernel (window-boundary re-quantization of the recurrent state; see README.md).
|
| 3 |
+
|
| 4 |
+
Warp-specialised TileLang kernel for sm_100 (B200): one persistent CTA per SM, a TMA producer warp and three
|
| 5 |
+
128-thread consumer groups, products on tensor cores (mma.sync m16n8k16, bf16 hi/lo operands), the rebuilt state
|
| 6 |
+
resident in shared memory as fp16 with the old rank-4 part carried algebraically in fp32, CholeskyQR2 with a relative
|
| 7 |
+
pivot floor for the new Compensator Tokens, the due programs balanced across CTAs by a rank scan.
|
| 8 |
+
|
| 9 |
+
run(...) functional form with the input order / outputs of definition.json (packs the inputs into a slot
|
| 10 |
+
pool, calls the kernel, returns the new checkpoint as fresh tensors) -- used for correctness
|
| 11 |
+
Pool, flush_inplace deployment form: caller-owned strided slot pool updated in place -- what benchmark.py times
|
| 12 |
+
|
| 13 |
+
Requires: torch (CUDA), tilelang 0.1.12, CUDA toolkit 13 (nvcc), NVIDIA B200.
|
| 14 |
+
"""
|
| 15 |
+
import torch, tilelang, tilelang.language as T
|
| 16 |
+
from tilelang.layout import make_swizzled_layout
|
| 17 |
+
|
| 18 |
+
F32, BF16, I32, I8 = "float32", "bfloat16", "int32", "int8"
|
| 19 |
+
QMAX = 127.0
|
| 20 |
+
EPS = 1e-12
|
| 21 |
+
HV, K, V, L, R = 32, 128, 128, 16, 4 # heads per sequence, key dim, value dim, window length, rank
|
| 22 |
+
SS, OFF = 33 * V * K, 12288 # pool geometry in fp32 words: slot stride (one spare head per slot), base offset
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@tilelang.jit(pass_configs={"tl.disable_thread_storage_sync": True})
|
| 26 |
+
def make_flush_kernel(NS, HV, K, V, L, SS, R=4, ITERS=1, SMS=148, NCG=3, MAXIT=128, PROF=False, PAD=8, KDA=False, GB16=True, PROFIT=False, DROPLO=False, MMT="bf16", ABL="", PNMIN=1e-20, GRAM16=False, NSTAGE=0, NMAX=0, **_ignored):
|
| 27 |
+
"""TileLang generator of the flush kernel (the KDA=True branches serve a per-channel-gate variant that this request does not use).
|
| 28 |
+
|
| 29 |
+
v2 keeps S in the mma fragments (128 fp32 registers per thread), which caps the CTA at two 4-warp programs in flight;
|
| 30 |
+
every phase of the flush is a dependent chain (mma -> smem -> barrier -> reduction), so the flush ran at ~22k cycles
|
| 31 |
+
per program per warpgroup with 8 warps resident. v4 makes shared memory the home of the state: the rebuild produces
|
| 32 |
+
B = pn deq(S0) + buffer in two 64-column halves (64 accumulator registers) and stores it as fp16 with stmatrix; the
|
| 33 |
+
old rank-R part A = pn Q_old U_old^T is carried algebraically (see below); the residual E = B + A - Q U^T is written
|
| 34 |
+
back over B (ldmatrix / stmatrix), and the quantisation streams E row-wise (8 lanes per row, 16 columns per lane, one
|
| 35 |
+
16 B global store per lane -- no staging tile, no copy-out). Registers drop to ~128 per thread, which fits NCG = 3
|
| 36 |
+
programs in flight (12 consumer warps); the stage (int8 tile, buffers, old factors) is released after the residual.
|
| 37 |
+
Every per-program smem object beyond the stage lives in two per-group buffers: St_s (V x (K + 8) fp16: B / E in the
|
| 38 |
+
columns < K, the fp16 Q tile of the iteration in the 8 padding columns) and UQn_s (fp32 Q for the CholeskyQR rows,
|
| 39 |
+
the fp16 P tile, then the new -U^T for the residual mma, then the |E| column partials).
|
| 40 |
+
|
| 41 |
+
Numerics: v2's fp16 St_s folds the fp16 rounding of S (2^-11 |S|) into the residual, which for a row captured by the
|
| 42 |
+
factors (hot rows: |E| << |S|) is a large error relative to E. v4 keeps only B in fp16 and carries A exactly: the
|
| 43 |
+
iteration's products get the R x R corrections P += pn U_old (Q_old^T Q) and Q += pn Q_old (U_old^T P), with the
|
| 44 |
+
R x R matrices accumulated on the tensor cores alongside the products (every warp holds the full matrix, no
|
| 45 |
+
reduction), and the residual has both rank-R terms on the tensor cores in fp32. The fp16 rounding is then 2^-11 |B|,
|
| 46 |
+
the size of the checkpoint residual itself; E is rounded to fp16 once more before the quantisation.
|
| 47 |
+
"""
|
| 48 |
+
# Gbuf holds fp16 factors; it is declared bf16 so the TMA target (Kbl_s, later the lo key tile) matches -- the bits are reinterpreted on read
|
| 49 |
+
assert 1 <= R <= 4 and K == 128 and V == 128 and (not KDA or GB16) and PAD == 8
|
| 50 |
+
F16 = "float16"
|
| 51 |
+
N = T.symbolic("N")
|
| 52 |
+
KW = K // 4
|
| 53 |
+
NPROD = 32
|
| 54 |
+
NCONS = 128 * NCG
|
| 55 |
+
NT = NPROD + NCONS
|
| 56 |
+
NWARPS = NT // 32
|
| 57 |
+
NDUE = min(NS - 8, NMAX) if NMAX else NS - 8 # rows that can be due at once: one call's rows (NMAX = the engine's batch cap) or the whole table
|
| 58 |
+
MAXIT = max(MAXIT, (NDUE * HV + SMS - 1) // SMS + 1) # dlist capacity: a CTA's share of all programs when every such row is due
|
| 59 |
+
# (with NMAX the list is ~350 B instead of 5.5 KB on an 8155-slot engine: on sm_120 that is the difference between a 2-stage flush fitting in 99 KB or not)
|
| 60 |
+
KMAX = min((NS + NWARPS - 1) // NWARPS, 40) # n-steps per warp kept in registers by the compaction (3 x 40 registers; N <= 40 * NWARPS =
|
| 61 |
+
# 520 sequences at NCG = 3, vLLM's max_num_seqs 512); larger batches take a serial tail
|
| 62 |
+
# with the flags recomputed in the rank pass (64 steps spilled: +3 us none-due)
|
| 63 |
+
NSTAGE = NSTAGE or NCG # NSTAGE > NCG: each group double-buffers its stage (the TMA warp prefetches the group's
|
| 64 |
+
assert NSTAGE % NCG == 0 # next due program while it works) -- worth it where one group is all that fits (sm_120)
|
| 65 |
+
SPG = NSTAGE // NCG
|
| 66 |
+
KP = K + PAD # St_s row stride: conflict-free fragment stores, ldmatrix rows and 16 B row reads; the pad holds the fp16 Q tile
|
| 67 |
+
KV8 = K + V + 8 # UQn_s row stride (halfwords): 528 B -> conflict-free ldmatrix rows
|
| 68 |
+
P16OFF = 4 * KV8 # fp16 P tile (K x 8) at halfword offset 4 rows into UQn_s (after the fp32 Q plane)
|
| 69 |
+
assert 4 * KV8 * 2 >= (V + 4) * 4 * 4 and 4 * KV8 >= K * 8
|
| 70 |
+
|
| 71 |
+
@T.prim_func
|
| 72 |
+
def flush(Sq: T.StridedTensor((NS, HV, V, KW), (SS, V * K, KW, 1), I32),
|
| 73 |
+
Sk: T.StridedTensor((NS, HV, K), (SS, V * K, 1), F32),
|
| 74 |
+
Sv: T.StridedTensor((NS, HV, V), (SS, V * K, 1), F32),
|
| 75 |
+
Skv: T.StridedTensor((NS, HV, K + V), (SS, V * K, 1), F32),
|
| 76 |
+
Kbuf: T.Tensor((NS, HV, L, K), BF16), Ubuf: T.Tensor((NS, HV, L, V), BF16),
|
| 77 |
+
Wbuf: T.Tensor((NS, HV, L), F32), Pbuf: T.Tensor((NS, HV, K if KDA else 1), F32), Gbuf: T.Tensor((NS, HV, L, K) if KDA else (1, 1, 1, 1), BF16), hcnt: T.Tensor((NS, HV), I32),
|
| 78 |
+
Sq16: T.StridedTensor((NS, HV, V, K // 2), (2 * SS, 2 * V * K, K // 2, 1), "int16"), # unused (kept for the v2 call signature)
|
| 79 |
+
UQ: T.StridedTensor((NS, HV, R, K + V), (2 * SS, 2 * V * K, K + V, 1), F16), # fp16 factors U^T | Q^T after the scales
|
| 80 |
+
Q0: T.Tensor((V, R), F32), # deterministic start of the subspace iteration
|
| 81 |
+
idx: T.Tensor((N,), I32)):
|
| 82 |
+
with T.Kernel(SMS, threads=NPROD + NCONS) as bid:
|
| 83 |
+
Qs = T.alloc_shared((NSTAGE, V, KW), I32)
|
| 84 |
+
skv_s = T.alloc_shared((NSTAGE, K + V), F32)
|
| 85 |
+
Kb_s = T.alloc_shared((NSTAGE, 2, L, K // 2), BF16) # two 128 B-wide halves, 128 B swizzle (conflict-free ldmatrix)
|
| 86 |
+
Ub_s = T.alloc_shared((NSTAGE, 2, L, V // 2), BF16)
|
| 87 |
+
Wb_s = T.alloc_shared((NSTAGE, 32), F32) # 128 B per stage (TMA destination alignment)
|
| 88 |
+
UQ_s = T.alloc_shared((NSTAGE, 4, 8, 64), F16) # old factors U^T | Q^T in four 128 B-wide column blocks (swizzled: conflict-free ldmatrix rows), k-rows padded to 8 (rows R.. zero)
|
| 89 |
+
St_s = T.alloc_shared((NCG, V, KP), F16) # B (fp16) for the iteration, then the residual E in place; columns K.. = the fp16 Q tile (V x 8, columns R.. zero)
|
| 90 |
+
UQn_s = T.alloc_shared((NCG, 8, KV8), F16) # new -U^T (rows R.. zero) for the residual mma; aliases: PQ_s (fp32 Q rows), P16 (fp16 P tile), cpart (column partials)
|
| 91 |
+
PQ_s = T.view(UQn_s, (NCG, 2, KV8 // 2, 4), F32) # plane 0 = Q (V x R) fp32 for the CholeskyQR rows
|
| 92 |
+
UQn1 = T.view(UQn_s, (NCG, 8 * KV8), F16) # flat view: the fp16 P tile P16[c][r] at P16OFF + 8 c + r
|
| 93 |
+
cpart = T.view(UQn_s, (NCG, 8, KV8 // 2), F32) # per-warp column partials of |E| (rows 0..3)
|
| 94 |
+
rsk = T.view(UQn_s, (NCG, 8, KV8 // 2), F32) # reciprocal column scales: row 6 of the cpart view (free once the partials are read)
|
| 95 |
+
dlist = T.alloc_shared((MAXIT,), I32) # this CTA's due programs p (global rank == bid mod SMS), in rank order
|
| 96 |
+
ndue_s = T.alloc_shared((1,), I32)
|
| 97 |
+
wsum_s = T.alloc_shared((NWARPS,), I32) # per-warp due counts of the block-wide compaction
|
| 98 |
+
if KDA:
|
| 99 |
+
Kbl_s = T.alloc_shared((NSTAGE, 2, L, K // 2), BF16) # per-entry decay factors (TMA target, fp16 bits) -> lo part of the decayed keys
|
| 100 |
+
pb_s = T.alloc_shared((NSTAGE, K), F32)
|
| 101 |
+
pc_s = T.alloc_shared((NCG, K), F32)
|
| 102 |
+
loaded = T.alloc_barrier([32] * NSTAGE)
|
| 103 |
+
consumed = T.alloc_barrier([128] * NSTAGE)
|
| 104 |
+
if KDA:
|
| 105 |
+
T.annotate_layout({Qs: make_swizzled_layout(Qs), Kb_s: make_swizzled_layout(Kb_s), Ub_s: make_swizzled_layout(Ub_s), Kbl_s: make_swizzled_layout(Kbl_s), UQ_s: make_swizzled_layout(UQ_s)})
|
| 106 |
+
else:
|
| 107 |
+
T.annotate_layout({Qs: make_swizzled_layout(Qs), Kb_s: make_swizzled_layout(Kb_s), Ub_s: make_swizzled_layout(Ub_s), UQ_s: make_swizzled_layout(UQ_s)})
|
| 108 |
+
tx = T.get_thread_binding()
|
| 109 |
+
# ---- block-wide balanced compaction (no atomics): every CTA scans all N * HV due flags -- warp w takes the sequences
|
| 110 |
+
# n = w, w + NWARPS, ..., lane hv the head (one broadcast idx load + one coalesced 128 B hcnt load per n; an uncoalesced
|
| 111 |
+
# gather costs 32 L1 lookups per warp-load and was 8x slower) -- ranks the due programs with ballot/popc in the fixed order
|
| 112 |
+
# (warp, n-step, hv) and keeps the ranks == bid (mod SMS). The flush is latency-bound at 1/16 duty (1-3 programs per
|
| 113 |
+
# group): the static assignment's binomial imbalance (max 12 of mean 3.6 per CTA at bs 256) cost ~1.4x; this gives +-1.
|
| 114 |
+
# dlist holds q = slot * HV + hv. ----
|
| 115 |
+
tc = T.alloc_local((4,), "int64")
|
| 116 |
+
if PROF:
|
| 117 |
+
tc[0] = T.call_extern("int64", "clock64")
|
| 118 |
+
wlane = tx % 32
|
| 119 |
+
wid = tx // 32
|
| 120 |
+
kn = T.alloc_local((1,), I32)
|
| 121 |
+
kn[0] = T.ceildiv(N, NWARPS) # n-steps per warp
|
| 122 |
+
cnt = T.alloc_local((1,), I32)
|
| 123 |
+
cnt[0] = 0
|
| 124 |
+
slk = T.alloc_local((KMAX,), I32)
|
| 125 |
+
hck = T.alloc_local((KMAX,), I32)
|
| 126 |
+
mk = T.alloc_local((KMAX,), "uint32")
|
| 127 |
+
for k in T.unroll(KMAX): # all loads in flight at once (explicit clamps: no guard branches)
|
| 128 |
+
slk[k] = idx[T.max(T.min(wid + NWARPS * k, N - 1), 0)]
|
| 129 |
+
for k in T.unroll(KMAX):
|
| 130 |
+
hck[k] = hcnt[T.min(T.max(slk[k], 0), NS - 1), wlane]
|
| 131 |
+
for k in T.unroll(KMAX):
|
| 132 |
+
f = T.if_then_else((k < kn[0]) & (wid + NWARPS * k < N) & (slk[k] > 0) & (hck[k] == L), 1, 0)
|
| 133 |
+
mk[k] = T.call_extern("uint32", "__ballot_sync", T.uint32(0xFFFFFFFF), f)
|
| 134 |
+
cnt[0] += T.call_extern(I32, "__popc", mk[k])
|
| 135 |
+
sl8 = T.alloc_local((8,), I32)
|
| 136 |
+
hc8 = T.alloc_local((8,), I32)
|
| 137 |
+
for ck in T.serial(T.ceildiv(kn[0] - KMAX, 8)): # tail (N > KMAX * NWARPS only): serial chunks, flags recomputed in the rank pass
|
| 138 |
+
for j in T.unroll(8):
|
| 139 |
+
sl8[j] = idx[T.max(T.min(wid + NWARPS * (KMAX + ck * 8 + j), N - 1), 0)]
|
| 140 |
+
for j in T.unroll(8):
|
| 141 |
+
hc8[j] = hcnt[T.min(T.max(sl8[j], 0), NS - 1), wlane]
|
| 142 |
+
for j in T.unroll(8):
|
| 143 |
+
k = KMAX + ck * 8 + j
|
| 144 |
+
f = T.if_then_else((k < kn[0]) & (wid + NWARPS * k < N) & (sl8[j] > 0) & (hc8[j] == L), 1, 0)
|
| 145 |
+
cnt[0] += T.call_extern(I32, "__popc", T.call_extern("uint32", "__ballot_sync", T.uint32(0xFFFFFFFF), f))
|
| 146 |
+
if PROF:
|
| 147 |
+
tc[1] = T.call_extern("int64", "clock64")
|
| 148 |
+
if wlane == 0:
|
| 149 |
+
wsum_s[wid] = cnt[0]
|
| 150 |
+
T.sync_threads(14, NPROD + NCONS)
|
| 151 |
+
base = T.alloc_local((1,), I32)
|
| 152 |
+
base[0] = 0
|
| 153 |
+
for ww in T.serial(NWARPS):
|
| 154 |
+
base[0] += T.if_then_else(ww < wid, wsum_s[ww], 0)
|
| 155 |
+
tot = T.alloc_local((1,), I32)
|
| 156 |
+
tot[0] = 0
|
| 157 |
+
for ww in T.serial(NWARPS):
|
| 158 |
+
tot[0] += wsum_s[ww]
|
| 159 |
+
T.sync_threads(14, NPROD + NCONS) # wsum_s reads done before dlist (which may share its smem) is written
|
| 160 |
+
lmask = T.cast((T.int64(1) << T.cast(wlane, "int64")) - T.int64(1), "uint32")
|
| 161 |
+
if cnt[0] > 0: # warps without due programs skip the pass (masks past kn are zero)
|
| 162 |
+
rst = T.alloc_local((2,), I32) # next rank == bid (mod SMS) at or above base, and its dlist index (one division per thread)
|
| 163 |
+
rst[0] = base[0] + (bid - base[0] % SMS + SMS) % SMS
|
| 164 |
+
rst[1] = rst[0] // SMS
|
| 165 |
+
for k in T.unroll(KMAX): # static indexing of the mask registers; one predicate per step, no division
|
| 166 |
+
m = mk[k]
|
| 167 |
+
rank = base[0] + T.call_extern(I32, "__popc", m & lmask)
|
| 168 |
+
if (((m >> T.cast(wlane, "uint32")) & T.uint32(1)) == T.uint32(1)) & (rank == rst[0]):
|
| 169 |
+
dlist[rst[1]] = idx[wid + NWARPS * k] * HV + wlane
|
| 170 |
+
base[0] += T.call_extern(I32, "__popc", m)
|
| 171 |
+
if rst[0] < base[0]: # the warp's rank sequence passed the target (warp-uniform; at most one target per step)
|
| 172 |
+
rst[0] += SMS
|
| 173 |
+
rst[1] += 1
|
| 174 |
+
for ck in T.serial(T.ceildiv(kn[0] - KMAX, 8)):
|
| 175 |
+
for j in T.unroll(8):
|
| 176 |
+
sl8[j] = idx[T.max(T.min(wid + NWARPS * (KMAX + ck * 8 + j), N - 1), 0)]
|
| 177 |
+
for j in T.unroll(8):
|
| 178 |
+
hc8[j] = hcnt[T.min(T.max(sl8[j], 0), NS - 1), wlane]
|
| 179 |
+
for j in T.unroll(8):
|
| 180 |
+
k = KMAX + ck * 8 + j
|
| 181 |
+
f = T.if_then_else((k < kn[0]) & (wid + NWARPS * k < N) & (sl8[j] > 0) & (hc8[j] == L), 1, 0)
|
| 182 |
+
m = T.call_extern("uint32", "__ballot_sync", T.uint32(0xFFFFFFFF), f)
|
| 183 |
+
if f == 1:
|
| 184 |
+
rank = base[0] + T.call_extern(I32, "__popc", m & lmask)
|
| 185 |
+
if rank % SMS == bid:
|
| 186 |
+
dlist[rank // SMS] = sl8[j] * HV + wlane
|
| 187 |
+
base[0] += T.call_extern(I32, "__popc", m)
|
| 188 |
+
if tx == 0:
|
| 189 |
+
ndue_s[0] = T.max(T.ceildiv(tot[0] - bid, SMS), 0)
|
| 190 |
+
if PROF:
|
| 191 |
+
tc[2] = T.call_extern("int64", "clock64")
|
| 192 |
+
if tx < NPROD:
|
| 193 |
+
for i in T.serial(NSTAGE * 4 * (8 - R) * 64 // NPROD): # zero the padding k-rows of UQ_s once (only rows < R are ever written)
|
| 194 |
+
e = tx + NPROD * i
|
| 195 |
+
UQ_s[e // (4 * (8 - R) * 64), (e // ((8 - R) * 64)) % 4, R + (e % ((8 - R) * 64)) // 64, e % 64] = T.cast(0.0, F16)
|
| 196 |
+
T.sync_threads(14, NPROD + NCONS)
|
| 197 |
+
if tx < NPROD:
|
| 198 |
+
T.fence_proxy_async()
|
| 199 |
+
for k in T.serial(ndue_s[0]):
|
| 200 |
+
q = dlist[k]
|
| 201 |
+
gc = k % NCG
|
| 202 |
+
ig = k // NCG
|
| 203 |
+
s = gc * SPG + ig % SPG
|
| 204 |
+
hv = q % HV
|
| 205 |
+
slot = q // HV
|
| 206 |
+
T.mbarrier_wait_parity(consumed[s], ((ig // SPG) & 1) ^ 1)
|
| 207 |
+
T.tma_copy(Sq[slot, hv, :, :], Qs[s, :, :], barrier=loaded[s])
|
| 208 |
+
T.tma_copy(Skv[slot, hv, :], skv_s[s, :], barrier=loaded[s])
|
| 209 |
+
T.tma_copy(Kbuf[slot, hv, :, 0:K // 2], Kb_s[s, 0, :, :], barrier=loaded[s])
|
| 210 |
+
T.tma_copy(Kbuf[slot, hv, :, K // 2:K], Kb_s[s, 1, :, :], barrier=loaded[s])
|
| 211 |
+
T.tma_copy(Ubuf[slot, hv, :, 0:V // 2], Ub_s[s, 0, :, :], barrier=loaded[s])
|
| 212 |
+
T.tma_copy(Ubuf[slot, hv, :, V // 2:V], Ub_s[s, 1, :, :], barrier=loaded[s])
|
| 213 |
+
T.tma_copy(Wbuf[slot, hv, :], Wb_s[s, 0:L], barrier=loaded[s])
|
| 214 |
+
for cb in T.unroll(4):
|
| 215 |
+
T.tma_copy(UQ[slot, hv, :, cb * 64:(cb + 1) * 64], UQ_s[s, cb, 0:R, :], barrier=loaded[s])
|
| 216 |
+
if KDA:
|
| 217 |
+
T.tma_copy(Gbuf[slot, hv, :, 0:K // 2], Kbl_s[s, 0, :, :], barrier=loaded[s])
|
| 218 |
+
T.tma_copy(Gbuf[slot, hv, :, K // 2:K], Kbl_s[s, 1, :, :], barrier=loaded[s])
|
| 219 |
+
T.tma_copy(Pbuf[slot, hv, :], pb_s[s, :], barrier=loaded[s])
|
| 220 |
+
T.mbarrier_arrive(loaded[s])
|
| 221 |
+
else:
|
| 222 |
+
g = (tx - NPROD) // 128
|
| 223 |
+
t = (tx - NPROD) % 128
|
| 224 |
+
w = t // 32
|
| 225 |
+
lane = t % 32
|
| 226 |
+
q4 = lane % 4
|
| 227 |
+
r0 = lane // 4
|
| 228 |
+
bar = 8 + g
|
| 229 |
+
qw = T.alloc_local((4,), I32)
|
| 230 |
+
svr_l = T.alloc_local((4,), F32)
|
| 231 |
+
rmax = T.alloc_local((4,), F32)
|
| 232 |
+
afrag = T.alloc_local((32 if not KDA else 16,), BF16)
|
| 233 |
+
araw = T.alloc_local((8,), BF16)
|
| 234 |
+
wv = T.alloc_local((4,), F32)
|
| 235 |
+
bfrag = T.alloc_local((32 if KDA else 16,), BF16) # 2 x (ring-buffer B tile, KDA: hi + lo) -- alternating per unrolled step
|
| 236 |
+
afrag2 = T.alloc_local((8,), F16) # rank-R A fragments (m16n8k8) per m-tile: old Q^T (residual)
|
| 237 |
+
afrag3 = T.alloc_local((8,), F16) # rank-R A fragments of the new factors (residual)
|
| 238 |
+
cfrag = T.alloc_local((64,), F32) # half of B / E in fragment layout: index (ntl * 4 + (mt * 2 + r)) * 2 + c1, ntl = local n-tile 0..7
|
| 239 |
+
efrag = T.alloc_local((8,), F16) # ldmatrix.x4 result: B values of (ntl, top), (ntl, bottom), (ntl+1, top), (ntl+1, bottom)
|
| 240 |
+
colp = T.alloc_local((32,), F32) # column partials of |E| (16 n-tiles x 2 columns of this lane)
|
| 241 |
+
skl = T.alloc_local((16,), F32) # this lane's 16 column scales of the current half (dequant)
|
| 242 |
+
ah = T.alloc_local((32,), F16) # m16n8k16 A fragments (ldmatrix.x4 from the fp16 St_s): 2 k-parities x 2 m-tiles
|
| 243 |
+
bh2 = T.alloc_local((8,), F16) # B fragments (Q or P column pairs, fp16, ldmatrix.x2.trans): 2 k-parities
|
| 244 |
+
ao = T.alloc_local((16,), F16) # A fragments of the old factor (rows 0..7 of a 16-row m-tile; rows 8..15 zero): 2 k-parities
|
| 245 |
+
bfr = T.alloc_local((8,), F16) # 2 x rank-R B fragment (residual)
|
| 246 |
+
bhi = T.alloc_local((4,), I32) # |E| B fragments (sign bits cleared) of one n-tile, 2 k-steps
|
| 247 |
+
aone = T.alloc_local((8,), F16) # A fragment of ones (column sums on the tensor cores)
|
| 248 |
+
c32 = T.alloc_local((16,), F32) # 2 m-tiles x 4, two accumulator chains (even/odd k-steps)
|
| 249 |
+
mc = T.alloc_local((4,), F32) # R x R correction matrix accumulator (M = Q_old^T Q, M2 = U_old^T P), full in every warp
|
| 250 |
+
mm = T.alloc_local((8,), F32) # M[a][2 q4 + i] for a = 0..3 (shuffled from lanes 4 a + q4)
|
| 251 |
+
uo = T.alloc_local((16,), F32) # old factor entries U_old[a][c] / Q_old[a][v] of this lane's 4 rows
|
| 252 |
+
pr = T.alloc_local((4,), F32) # this thread's row of Q
|
| 253 |
+
gg = T.alloc_local((10,), F32) # Gram entries (0,0) (1,0) (1,1) (2,0) (2,1) (2,2) (3,0) (3,1) (3,2) (3,3)
|
| 254 |
+
ll = T.alloc_local((10,), F32) # Cholesky factor, same packing
|
| 255 |
+
uh = T.alloc_local((4,), F16)
|
| 256 |
+
qh = T.alloc_local((4,), F16)
|
| 257 |
+
el = T.alloc_local((L,), F32) # KDA: this column's per-entry decay factors
|
| 258 |
+
dcur = T.alloc_local((1,), F32)
|
| 259 |
+
eh = T.alloc_local((32,), F16) # quantisation: 2 x 2 x 8 halfwords of E (alternating per row pass)
|
| 260 |
+
ph = T.alloc_local((8,), F16) # fp16 pairs for stmatrix (vectorised cast -> one F2FP.PACK per pair)
|
| 261 |
+
ex = T.alloc_local((16,), F32) # quantisation: this lane's 16 scaled residual values of the row
|
| 262 |
+
rk = T.alloc_local((16,), F32) # quantisation: this lane's 16 reciprocal column scales
|
| 263 |
+
tk = T.alloc_local((10,), "int64")
|
| 264 |
+
tk2 = T.alloc_local((6,), "int64")
|
| 265 |
+
tacc = T.alloc_local((10,), F32)
|
| 266 |
+
for i in T.unroll(10):
|
| 267 |
+
tacc[i] = 0.0
|
| 268 |
+
if PROF:
|
| 269 |
+
tacc[7] = T.cast(tc[1] - tc[0], F32) # compaction: loads + ballots
|
| 270 |
+
tacc[9] = T.cast(tc[2] - tc[1], F32) # compaction: scan + rank pass
|
| 271 |
+
for i in T.unroll(8):
|
| 272 |
+
aone[i] = T.cast(1.0, F16)
|
| 273 |
+
for i in T.unroll(2): # the old-factor A fragments: register pairs 1 and 3 (m-rows 8..15) stay zero
|
| 274 |
+
ao[2 + i] = T.cast(0.0, F16)
|
| 275 |
+
ao[6 + i] = T.cast(0.0, F16)
|
| 276 |
+
ao[10 + i] = T.cast(0.0, F16)
|
| 277 |
+
ao[14 + i] = T.cast(0.0, F16)
|
| 278 |
+
for r in T.unroll(4): # the fp16 Q tile's padding columns R..7 stay zero (this thread's row)
|
| 279 |
+
St_s[g, t, K + 4 + r] = T.cast(0.0, F16)
|
| 280 |
+
for r in T.unroll(4 - R):
|
| 281 |
+
St_s[g, t, K + R + r] = T.cast(0.0, F16)
|
| 282 |
+
for it0 in T.serial(T.ceildiv(ndue_s[0] - g, NCG)):
|
| 283 |
+
k = g + it0 * NCG
|
| 284 |
+
q = dlist[k]
|
| 285 |
+
hv = q % HV
|
| 286 |
+
s = g * SPG + it0 % SPG
|
| 287 |
+
if PROF:
|
| 288 |
+
tk[0] = T.call_extern("int64", "clock64")
|
| 289 |
+
T.mbarrier_wait_parity(loaded[s], (it0 // SPG) & 1)
|
| 290 |
+
if PROF:
|
| 291 |
+
tk[1] = T.call_extern("int64", "clock64")
|
| 292 |
+
slot = q // HV
|
| 293 |
+
if KDA:
|
| 294 |
+
# pre-pass (thread per column c = t): pc = exp(G); decayed keys w_j k_j D_j as bf16 hi (in place) + lo (over the factors);
|
| 295 |
+
# U^T pre-multiplied by pc (the checkpoint's column decay)
|
| 296 |
+
pcc = T.exp(pb_s[s, t])
|
| 297 |
+
pc_s[g, t] = pcc
|
| 298 |
+
for jj in T.unroll(L):
|
| 299 |
+
el[jj] = T.cast(T.reinterpret(F16, Kbl_s[s, t // (K // 2), jj, t % (K // 2)]), F32)
|
| 300 |
+
T.sync_threads(bar, 128) # every lane holds its factors before the lo tile overwrites them
|
| 301 |
+
dcur[0] = 1.0
|
| 302 |
+
for jj in T.unroll(L): # backward: D_{L-1} = 1, D_j = D_{j+1} e_{j+1}
|
| 303 |
+
j = L - 1 - jj
|
| 304 |
+
kd = T.cast(Kb_s[s, t // (K // 2), j, t % (K // 2)], F32) * (Wb_s[s, j] * dcur[0])
|
| 305 |
+
khi = T.cast(kd, BF16)
|
| 306 |
+
Kb_s[s, t // (K // 2), j, t % (K // 2)] = khi
|
| 307 |
+
Kbl_s[s, t // (K // 2), j, t % (K // 2)] = T.cast(kd - T.cast(khi, F32), BF16)
|
| 308 |
+
dcur[0] = dcur[0] * el[j]
|
| 309 |
+
for r in T.unroll(R): # pc U^T in place (fp16: 2^-11 of the rank-R term, measured irrelevant next to the int8 residual, 10.46)
|
| 310 |
+
UQ_s[s, t // 64, r, t % 64] = T.cast(T.cast(UQ_s[s, t // 64, r, t % 64], F32) * pcc, F16)
|
| 311 |
+
T.sync_threads(bar, 128)
|
| 312 |
+
for i in T.unroll(4):
|
| 313 |
+
svr_l[i] = skv_s[s, K + w * 32 + (i // 2) * 16 + (i % 2) * 8 + lane // 4] * (1.0 / QMAX)
|
| 314 |
+
else:
|
| 315 |
+
pn = T.max(Pbuf[slot, hv, 0], PNMIN) # floor: a fully decayed head has a denormal product (2e-41 seen on 9B layer 11) and 1/pn = inf
|
| 316 |
+
rpn = 1.0 / pn # poisoned the residual (Sk = inf -> NaN outputs, 10.49); the floor changes E by <= 1e-20 |Q_old U_old^T|
|
| 317 |
+
if KDA:
|
| 318 |
+
pn = 1.0
|
| 319 |
+
if not KDA:
|
| 320 |
+
for i in T.unroll(4):
|
| 321 |
+
svr_l[i] = skv_s[s, K + w * 32 + (i // 2) * 16 + (i % 2) * 8 + lane // 4] * (pn / QMAX)
|
| 322 |
+
# (1) A fragments of the ring buffer u_j (GDN: w_j-scaled, bf16 hi + lo; KDA: exact bf16)
|
| 323 |
+
if KDA:
|
| 324 |
+
for mt in T.unroll(2):
|
| 325 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(Ub_s[s, (w * 32 + mt * 16) // (V // 2), (lane % 8) + 8 * (lane // 16), (w * 32 + mt * 16) % (V // 2) + 8 * ((lane // 8) % 2)], "r", extent=8), T.access_ptr(afrag[mt * 8], "w", extent=8))
|
| 326 |
+
else:
|
| 327 |
+
for i in T.unroll(4):
|
| 328 |
+
wv[i] = Wb_s[s, 2 * q4 + (i % 2) + 8 * (i // 2)]
|
| 329 |
+
for mt in T.unroll(2):
|
| 330 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(Ub_s[s, (w * 32 + mt * 16) // (V // 2), (lane % 8) + 8 * (lane // 16), (w * 32 + mt * 16) % (V // 2) + 8 * ((lane // 8) % 2)], "r", extent=8), T.access_ptr(araw[0], "w", extent=8))
|
| 331 |
+
for i in T.unroll(8):
|
| 332 |
+
wu = wv[(i % 2) + 2 * (i // 4)] * T.cast(araw[i], F32)
|
| 333 |
+
afrag[mt * 16 + i] = T.cast(wu, BF16)
|
| 334 |
+
afrag[mt * 16 + 8 + i] = T.cast(wu - T.cast(afrag[mt * 16 + i], F32), BF16)
|
| 335 |
+
# (2) two 64-column halves: B = ring buffer (mma) + pn * deq(S0), out to St_s (fp16, stmatrix); the old rank-R part stays algebraic
|
| 336 |
+
for h in T.unroll(2):
|
| 337 |
+
# dequantise first (independent FFMA chains, no accumulator dependency), then the ring-buffer mma accumulates on top
|
| 338 |
+
for ntl in T.unroll(8):
|
| 339 |
+
for c1 in T.vectorized(2):
|
| 340 |
+
if KDA:
|
| 341 |
+
skl[ntl * 2 + c1] = skv_s[s, (h * 8 + ntl) * 8 + q4 * 2 + c1] * pc_s[g, (h * 8 + ntl) * 8 + q4 * 2 + c1]
|
| 342 |
+
else:
|
| 343 |
+
skl[ntl * 2 + c1] = skv_s[s, (h * 8 + ntl) * 8 + q4 * 2 + c1]
|
| 344 |
+
for rr in (T.unroll(0) if "nodeq" in ABL else T.unroll(4)):
|
| 345 |
+
v0 = w * 32 + (rr // 2) * 16 + (rr % 2) * 8 + r0
|
| 346 |
+
for jcl in T.unroll(4): # 16-column chunk = n-tiles 2jc, 2jc+1; lane q4 needs word q4 // 2 of each n-tile
|
| 347 |
+
jc = h * 4 + jcl
|
| 348 |
+
for nn in T.unroll(2):
|
| 349 |
+
qw[nn] = Qs[s, v0, jc * 4 + nn * 2 + q4 // 2]
|
| 350 |
+
for nn in T.unroll(2):
|
| 351 |
+
ntl = jcl * 2 + nn
|
| 352 |
+
pkw = qw[nn] ^ T.int32(-2139062144)
|
| 353 |
+
for c1 in T.unroll(2): # the magic-number subtraction must stay a separate exact fp32 op: folding -K*skl into an FFMA
|
| 354 |
+
x = T.reinterpret(F32, T.call_extern(I32, "__byte_perm", pkw, T.int32(0x4B000000), T.int32(0x7650) + (q4 % 2) * 2 + c1)) - 8388736.0 # costs ulp(2^23 skl) = half a code
|
| 355 |
+
cfrag[(ntl * 4 + rr) * 2 + c1] = x * svr_l[rr] * skl[ntl * 2 + c1]
|
| 356 |
+
# stmatrix.x4: matrices (ntl, rows 0-7), (ntl, rows 8-15), (ntl+1, rows 0-7), (ntl+1, rows 8-15) of m-tile mt
|
| 357 |
+
for npl in T.unroll(4):
|
| 358 |
+
n0 = (h * 4 + npl) * 16
|
| 359 |
+
bo = (npl % 2) * (16 if KDA else 8)
|
| 360 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(Kb_s[s, n0 // (K // 2), (lane % 8) + 8 * ((lane // 8) % 2), n0 % (K // 2) + 8 * (lane // 16)], "r", extent=8), T.access_ptr(bfrag[bo], "w", extent=8))
|
| 361 |
+
if KDA:
|
| 362 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(Kbl_s[s, n0 // (K // 2), (lane % 8) + 8 * ((lane // 8) % 2), n0 % (K // 2) + 8 * (lane // 16)], "r", extent=8), T.access_ptr(bfrag[bo + 8], "w", extent=8))
|
| 363 |
+
for mt in T.unroll(2):
|
| 364 |
+
for nn in T.unroll(2):
|
| 365 |
+
if KDA:
|
| 366 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "bf16", "bf16", "fp32", afrag.data, mt * 8, bfrag.data, bo + nn * 4, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 367 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "bf16", "bf16", "fp32", afrag.data, mt * 8, bfrag.data, bo + 8 + nn * 4, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 368 |
+
else:
|
| 369 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", MMT, MMT, "fp32", afrag.data, mt * 16, bfrag.data, bo + nn * 4, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 370 |
+
if not DROPLO:
|
| 371 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", MMT, MMT, "fp32", afrag.data, mt * 16 + 8, bfrag.data, bo + nn * 4, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 372 |
+
for mt in (T.unroll(0) if "nostb" in ABL else T.unroll(2)):
|
| 373 |
+
for npl in T.unroll(4):
|
| 374 |
+
for jj in T.unroll(4): # 4 fp16 pairs: (ntl, rows 0-7), (ntl, rows 8-15), (ntl+1, ...) -- one F2FP.PACK each
|
| 375 |
+
for c1 in T.vectorized(2):
|
| 376 |
+
ph[jj * 2 + c1] = T.cast(cfrag[((npl * 2 + jj // 2) * 4 + mt * 2 + jj % 2) * 2 + c1], F16)
|
| 377 |
+
T.call_extern("handle", "tl::ptx_stmatrix_m8n8_x4",
|
| 378 |
+
T.access_ptr(St_s[g, w * 32 + mt * 16 + 8 * ((lane // 8) % 2) + lane % 8, (h * 8 + npl * 2 + lane // 16) * 8], "w", extent=8),
|
| 379 |
+
T.reinterpret(I32, ph[0:2]), T.reinterpret(I32, ph[2:4]), T.reinterpret(I32, ph[4:6]), T.reinterpret(I32, ph[6:8]))
|
| 380 |
+
# the iteration's start Q0 (fp16 tile in the St_s pad columns; this thread's row) -- before the barrier that publishes B
|
| 381 |
+
for r in T.unroll(R):
|
| 382 |
+
St_s[g, t, K + r] = T.cast(Q0[t, r], F16)
|
| 383 |
+
T.sync_threads(bar, 128)
|
| 384 |
+
if PROF:
|
| 385 |
+
tk[2] = T.call_extern("int64", "clock64")
|
| 386 |
+
# ================= subspace iteration on B (fp16 mma) with the algebraic rank-R corrections =================
|
| 387 |
+
for itr in T.serial(ITERS + 1):
|
| 388 |
+
if PROFIT:
|
| 389 |
+
tk2[0] = T.call_extern("int64", "clock64")
|
| 390 |
+
# ---- P = B^T Q (K x R): A[m=c][k=v] = St_s[v][c] via ldmatrix.x4.trans; B[k=v][n=r] = Q16[v][r] via ldmatrix.x2.trans;
|
| 391 |
+
# alongside M = Q_old^T Q (R x R): A[m=r][k=v] = Q_old^T (rows 8..15 zero), same B fragments ----
|
| 392 |
+
for i in T.unroll(16):
|
| 393 |
+
c32[i] = 0.0
|
| 394 |
+
for i in T.unroll(4):
|
| 395 |
+
mc[i] = 0.0
|
| 396 |
+
for k0 in T.unroll(V // 16):
|
| 397 |
+
kp = k0 % 2 # alternating fragment registers: the next step's ldmatrix can overlap this step's mma
|
| 398 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(St_s[g, k0 * 16 + 8 * ((lane // 8) % 2) + lane % 8, K], "r", extent=4), T.access_ptr(bh2[kp * 4], "w", extent=4))
|
| 399 |
+
for mt in T.unroll(2):
|
| 400 |
+
m0 = w * 32 + mt * 16
|
| 401 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(St_s[g, k0 * 16 + 8 * (lane // 16) + lane % 8, m0 + 8 * ((lane // 8) % 2)], "r", extent=8), T.access_ptr(ah[(kp * 2 + mt) * 8], "w", extent=8))
|
| 402 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", ah.data, (kp * 2 + mt) * 8, bh2.data, kp * 4, c32.data, (k0 % 2) * 8 + mt * 4, T.bool(False))
|
| 403 |
+
T.ptx_ldmatrix(T.bool(False), 1, T.access_ptr(UQ_s[s, (K + k0 * 16) // 64, lane % 8, (K + k0 * 16) % 64], "r", extent=2), T.access_ptr(ao[kp * 8], "w", extent=2))
|
| 404 |
+
T.ptx_ldmatrix(T.bool(False), 1, T.access_ptr(UQ_s[s, (K + k0 * 16 + 8) // 64, lane % 8, (K + k0 * 16 + 8) % 64], "r", extent=2), T.access_ptr(ao[kp * 8 + 4], "w", extent=2))
|
| 405 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", ao.data, kp * 8, bh2.data, kp * 4, mc.data, 0, T.bool(False))
|
| 406 |
+
for i in T.unroll(8):
|
| 407 |
+
c32[i] += c32[8 + i]
|
| 408 |
+
if PROFIT:
|
| 409 |
+
tk2[1] = T.call_extern("int64", "clock64")
|
| 410 |
+
# ---- P += pn U_old M in the fragments: rows c = m0 + r0 (+8), columns n = 2 q4 + i; M[a][n] sits in lane 4 a + q4 ----
|
| 411 |
+
for a in T.unroll(4):
|
| 412 |
+
mm[a * 2] = T.shfl_sync(mc[0], a * 4 + q4)
|
| 413 |
+
mm[a * 2 + 1] = T.shfl_sync(mc[1], a * 4 + q4)
|
| 414 |
+
for mt in T.unroll(2):
|
| 415 |
+
for hh in T.unroll(2):
|
| 416 |
+
cc = w * 32 + mt * 16 + hh * 8 + r0
|
| 417 |
+
for a in T.unroll(4):
|
| 418 |
+
uo[(mt * 2 + hh) * 4 + a] = T.if_then_else(a < R, T.cast(UQ_s[s, cc // 64, a, cc % 64], F32), 0.0)
|
| 419 |
+
for i in T.unroll(2):
|
| 420 |
+
c32[mt * 4 + hh * 2 + i] += pn * (uo[(mt * 2 + hh) * 4] * mm[i] + uo[(mt * 2 + hh) * 4 + 1] * mm[2 + i] + uo[(mt * 2 + hh) * 4 + 2] * mm[4 + i] + uo[(mt * 2 + hh) * 4 + 3] * mm[6 + i])
|
| 421 |
+
# ---- the fp16 P tile P16[c][r] (columns >= R zero: lanes q4 >= R/2 write zeros) via stmatrix.x2 (rows 0-7, rows 8-15 of each m-tile) ----
|
| 422 |
+
for mt in T.unroll(2):
|
| 423 |
+
for c1 in T.vectorized(2):
|
| 424 |
+
ph[c1] = T.cast(T.if_then_else(2 * q4 + c1 < R, c32[mt * 4 + c1], 0.0), F16)
|
| 425 |
+
ph[2 + c1] = T.cast(T.if_then_else(2 * q4 + c1 < R, c32[mt * 4 + 2 + c1], 0.0), F16)
|
| 426 |
+
T.call_extern("handle", "tl::ptx_stmatrix_m8n8_x2",
|
| 427 |
+
T.access_ptr(UQn1[g, P16OFF + (w * 32 + mt * 16 + 8 * ((lane // 8) % 2) + lane % 8) * 8], "w", extent=8),
|
| 428 |
+
T.reinterpret(I32, ph[0:2]), T.reinterpret(I32, ph[2:4]))
|
| 429 |
+
T.sync_threads(bar, 128)
|
| 430 |
+
if PROFIT:
|
| 431 |
+
tk2[2] = T.call_extern("int64", "clock64")
|
| 432 |
+
tacc[0] += T.cast(tk2[1] - tk2[0], F32)
|
| 433 |
+
tacc[1] += T.cast(tk2[2] - tk2[1], F32)
|
| 434 |
+
if itr < ITERS:
|
| 435 |
+
# ---- Q = B P (V x R): A[m=v][k=c] = St_s[v][c] via ldmatrix.x4; B[k=c][n=r] = P16[c][r] via ldmatrix.x2.trans; alongside M2 = U_old^T P ----
|
| 436 |
+
for i in T.unroll(16):
|
| 437 |
+
c32[i] = 0.0
|
| 438 |
+
for i in T.unroll(4):
|
| 439 |
+
mc[i] = 0.0
|
| 440 |
+
for k0 in T.unroll(K // 16):
|
| 441 |
+
kp = k0 % 2
|
| 442 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(UQn1[g, P16OFF + (k0 * 16 + 8 * ((lane // 8) % 2) + lane % 8) * 8], "r", extent=4), T.access_ptr(bh2[kp * 4], "w", extent=4))
|
| 443 |
+
for mt in T.unroll(2):
|
| 444 |
+
m0 = w * 32 + mt * 16
|
| 445 |
+
T.ptx_ldmatrix(T.bool(False), 4, T.access_ptr(St_s[g, m0 + 8 * ((lane // 8) % 2) + lane % 8, k0 * 16 + 8 * (lane // 16)], "r", extent=8), T.access_ptr(ah[(kp * 2 + mt) * 8], "w", extent=8))
|
| 446 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", ah.data, (kp * 2 + mt) * 8, bh2.data, kp * 4, c32.data, (k0 % 2) * 8 + mt * 4, T.bool(False))
|
| 447 |
+
T.ptx_ldmatrix(T.bool(False), 1, T.access_ptr(UQ_s[s, (k0 * 16) // 64, lane % 8, (k0 * 16) % 64], "r", extent=2), T.access_ptr(ao[kp * 8], "w", extent=2))
|
| 448 |
+
T.ptx_ldmatrix(T.bool(False), 1, T.access_ptr(UQ_s[s, (k0 * 16 + 8) // 64, lane % 8, (k0 * 16 + 8) % 64], "r", extent=2), T.access_ptr(ao[kp * 8 + 4], "w", extent=2))
|
| 449 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", ao.data, kp * 8, bh2.data, kp * 4, mc.data, 0, T.bool(False))
|
| 450 |
+
for i in T.unroll(8):
|
| 451 |
+
c32[i] += c32[8 + i]
|
| 452 |
+
# ---- Q += pn Q_old M2 in the fragments, then the fp32 rows to PQ_s plane 0 for the CholeskyQR ----
|
| 453 |
+
for a in T.unroll(4):
|
| 454 |
+
mm[a * 2] = T.shfl_sync(mc[0], a * 4 + q4)
|
| 455 |
+
mm[a * 2 + 1] = T.shfl_sync(mc[1], a * 4 + q4)
|
| 456 |
+
for mt in T.unroll(2):
|
| 457 |
+
for hh in T.unroll(2):
|
| 458 |
+
vv = w * 32 + mt * 16 + hh * 8 + r0
|
| 459 |
+
for a in T.unroll(4):
|
| 460 |
+
uo[(mt * 2 + hh) * 4 + a] = T.if_then_else(a < R, T.cast(UQ_s[s, (K + vv) // 64, a, (K + vv) % 64], F32), 0.0)
|
| 461 |
+
for i in T.unroll(2):
|
| 462 |
+
c32[mt * 4 + hh * 2 + i] += pn * (uo[(mt * 2 + hh) * 4] * mm[i] + uo[(mt * 2 + hh) * 4 + 1] * mm[2 + i] + uo[(mt * 2 + hh) * 4 + 2] * mm[4 + i] + uo[(mt * 2 + hh) * 4 + 3] * mm[6 + i])
|
| 463 |
+
if q4 * 2 < R:
|
| 464 |
+
for mt in T.unroll(2):
|
| 465 |
+
PQ_s[g, 0, w * 32 + mt * 16 + r0, 2 * q4] = c32[mt * 4]
|
| 466 |
+
PQ_s[g, 0, w * 32 + mt * 16 + r0, 2 * q4 + 1] = c32[mt * 4 + 1]
|
| 467 |
+
PQ_s[g, 0, w * 32 + mt * 16 + r0 + 8, 2 * q4] = c32[mt * 4 + 2]
|
| 468 |
+
PQ_s[g, 0, w * 32 + mt * 16 + r0 + 8, 2 * q4 + 1] = c32[mt * 4 + 3]
|
| 469 |
+
T.sync_threads(bar, 128)
|
| 470 |
+
if PROFIT:
|
| 471 |
+
tk2[3] = T.call_extern("int64", "clock64")
|
| 472 |
+
tacc[2] += T.cast(tk2[3] - tk2[2], F32)
|
| 473 |
+
# ---- CholeskyQR2 of Q (V rows = 128 threads), relative pivot floor for rank-deficient heads. Pass 1 in fp32 (shuffle tree);
|
| 474 |
+
# pass 2's Gram on the tensor cores in fp16 (8 mma; the factors are stored in fp16 anyway and the residual uses the same
|
| 475 |
+
# fp16 factors, so a 2^-11 non-orthonormality costs nothing). A 3xTF32 Gram for pass 1 was slower (48 dependent mma). ----
|
| 476 |
+
for r in T.unroll(4):
|
| 477 |
+
pr[r] = T.if_then_else(r < R, PQ_s[g, 0, t, r], 0.0)
|
| 478 |
+
for cq in range(2):
|
| 479 |
+
if cq == 0 or not GRAM16: # pass 1 (kappa up to 1e3): fp32 Gram by the warp-shuffle tree + smem partials. GRAM16=False: pass 2 too --
|
| 480 |
+
# after a floored pass-1 pivot (rank-deficient head, e.g. svals 4.8 / 0.2 / 8e-3 / 1e-3) the 4th column has norm 1e-3..1e-5,
|
| 481 |
+
# its fp16 Gram entry is subnormal/zero, rsqrt blows the column up by 1e3..1e15 and U_4 = B^T q_4 with it (10.49)
|
| 482 |
+
for r in T.unroll(4):
|
| 483 |
+
for c in T.unroll(r + 1):
|
| 484 |
+
gg[r * (r + 1) // 2 + c] = pr[r] * pr[c]
|
| 485 |
+
for off in (T.unroll(0) if "nogram" in ABL else T.unroll(5)):
|
| 486 |
+
for i in T.unroll(10):
|
| 487 |
+
gg[i] += T.shfl_xor(gg[i], 16 >> off)
|
| 488 |
+
if lane == 0:
|
| 489 |
+
for i in T.unroll(10):
|
| 490 |
+
cpart[g, 4, w * 16 + i] = gg[i] # per-warp Gram partials (cpart row 4: free during the iteration)
|
| 491 |
+
T.sync_threads(bar, 128)
|
| 492 |
+
for i in T.unroll(10):
|
| 493 |
+
gg[i] = cpart[g, 4, i] + cpart[g, 4, 16 + i] + cpart[g, 4, 32 + i] + cpart[g, 4, 48 + i]
|
| 494 |
+
else: # pass 2 (Q nearly orthonormal): Gram on the tensor cores from the fp16 Q tile,
|
| 495 |
+
for i in T.unroll(4): # A = Q^T (rows R.. zero) and B = Q are the same ldmatrix.x2.trans fragment
|
| 496 |
+
mc[i] = 0.0
|
| 497 |
+
for k0 in T.unroll(V // 16):
|
| 498 |
+
kp = k0 % 2
|
| 499 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(St_s[g, k0 * 16 + 8 * ((lane // 8) % 2) + lane % 8, K], "r", extent=4), T.access_ptr(bh2[kp * 4], "w", extent=4))
|
| 500 |
+
for i in T.unroll(2):
|
| 501 |
+
ao[kp * 8 + i] = bh2[kp * 4 + i]
|
| 502 |
+
ao[kp * 8 + 4 + i] = bh2[kp * 4 + 2 + i]
|
| 503 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", ao.data, kp * 8, bh2.data, kp * 4, mc.data, 0, T.bool(False))
|
| 504 |
+
gg[0] = T.shfl_sync(mc[0], 0) # G[a][c] sits in lane 4 a + c // 2, register c % 2
|
| 505 |
+
gg[1] = T.shfl_sync(mc[0], 4)
|
| 506 |
+
gg[2] = T.shfl_sync(mc[1], 4)
|
| 507 |
+
gg[3] = T.shfl_sync(mc[0], 8)
|
| 508 |
+
gg[4] = T.shfl_sync(mc[1], 8)
|
| 509 |
+
gg[5] = T.shfl_sync(mc[0], 9)
|
| 510 |
+
gg[6] = T.shfl_sync(mc[0], 12)
|
| 511 |
+
gg[7] = T.shfl_sync(mc[1], 12)
|
| 512 |
+
gg[8] = T.shfl_sync(mc[0], 13)
|
| 513 |
+
gg[9] = T.shfl_sync(mc[1], 13)
|
| 514 |
+
ll[0] = T.rsqrt(T.max(gg[0], 1e-30)) # reciprocals of the diagonal (1/L_jj)
|
| 515 |
+
ll[1] = gg[1] * ll[0]
|
| 516 |
+
ll[2] = T.rsqrt(T.max(T.max(gg[2] - ll[1] * ll[1], 1e-6 * gg[2]), 1e-30))
|
| 517 |
+
ll[3] = gg[3] * ll[0]
|
| 518 |
+
ll[4] = (gg[4] - ll[3] * ll[1]) * ll[2]
|
| 519 |
+
ll[5] = T.rsqrt(T.max(T.max(gg[5] - ll[3] * ll[3] - ll[4] * ll[4], 1e-6 * gg[5]), 1e-30))
|
| 520 |
+
ll[6] = gg[6] * ll[0]
|
| 521 |
+
ll[7] = (gg[7] - ll[6] * ll[1]) * ll[2]
|
| 522 |
+
ll[8] = (gg[8] - ll[6] * ll[3] - ll[7] * ll[4]) * ll[5]
|
| 523 |
+
ll[9] = T.rsqrt(T.max(T.max(gg[9] - ll[6] * ll[6] - ll[7] * ll[7] - ll[8] * ll[8], 1e-6 * gg[9]), 1e-30))
|
| 524 |
+
pr[0] = pr[0] * ll[0]
|
| 525 |
+
pr[1] = (pr[1] - pr[0] * ll[1]) * ll[2]
|
| 526 |
+
pr[2] = (pr[2] - pr[0] * ll[3] - pr[1] * ll[4]) * ll[5]
|
| 527 |
+
pr[3] = (pr[3] - pr[0] * ll[6] - pr[1] * ll[7] - pr[2] * ll[8]) * ll[9]
|
| 528 |
+
for r in T.unroll(R):
|
| 529 |
+
St_s[g, t, K + r] = T.cast(pr[r], F16) # the fp16 Q tile (pass 2's Gram operand, then the next product)
|
| 530 |
+
T.sync_threads(bar, 128)
|
| 531 |
+
if PROFIT:
|
| 532 |
+
tk2[4] = T.call_extern("int64", "clock64")
|
| 533 |
+
tacc[3] += T.cast(tk2[4] - tk2[3], F32)
|
| 534 |
+
if PROF:
|
| 535 |
+
tk[3] = T.call_extern("int64", "clock64")
|
| 536 |
+
# ---- the fp16 factors (U^T[r][c] = P16[c][r], Q^T[r][v] = Q16[v][r]) to global and, after a barrier, -U^T over the P/Q planes for the residual mma ----
|
| 537 |
+
for r in T.unroll(R):
|
| 538 |
+
uh[r] = UQn1[g, P16OFF + t * 8 + r]
|
| 539 |
+
qh[r] = St_s[g, t, K + r]
|
| 540 |
+
UQ[slot, hv, r, t] = uh[r]
|
| 541 |
+
UQ[slot, hv, r, K + t] = qh[r]
|
| 542 |
+
T.sync_threads(bar, 128)
|
| 543 |
+
for r in T.unroll(R):
|
| 544 |
+
UQn_s[g, r, t] = -uh[r] # -U^T: the residual mma accumulates the subtraction
|
| 545 |
+
for r in T.unroll(8 - R):
|
| 546 |
+
UQn_s[g, R + r, t] = T.cast(0.0, F16)
|
| 547 |
+
T.sync_threads(bar, 128)
|
| 548 |
+
# ---- residual E = fp16(B) + pn Q_old U_old^T - Q U^T in two halves (fp16 mma, fp32 accumulate), |E| column partials, E over B in St_s ----
|
| 549 |
+
for mt in T.unroll(2): # A[m=v][k=r] = Q_old^T[r][v]: x2.trans -> (m 0-7), (m 8-15) of k-rows 0-7
|
| 550 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(UQ_s[s, (K + w * 32 + mt * 16 + 8 * ((lane // 8) % 2)) // 64, lane % 8, (K + w * 32 + mt * 16 + 8 * ((lane // 8) % 2)) % 64], "r", extent=4), T.access_ptr(afrag2[mt * 4], "w", extent=4))
|
| 551 |
+
# A[m=v][k=r] = Q16[v][r] (row-major [m][k], k 0-7): x2 (non-trans) -> rows 0-7, rows 8-15
|
| 552 |
+
T.ptx_ldmatrix(T.bool(False), 2, T.access_ptr(St_s[g, w * 32 + mt * 16 + 8 * ((lane // 8) % 2) + lane % 8, K], "r", extent=4), T.access_ptr(afrag3[mt * 4], "w", extent=4))
|
| 553 |
+
for h in T.unroll(2):
|
| 554 |
+
# E = pn (B / pn + Q_old U_old^T) - Q U^T: the accumulator starts from B (scaled by 1 / pn on GDN, loaded with ldmatrix.x4 in the
|
| 555 |
+
# fragment layout), so both rank-R mma chains accumulate straight into it and there is no elementwise add afterwards
|
| 556 |
+
for mt in T.unroll(2):
|
| 557 |
+
for npl in T.unroll(4):
|
| 558 |
+
T.ptx_ldmatrix(T.bool(False), 4, T.access_ptr(St_s[g, w * 32 + mt * 16 + 8 * ((lane // 8) % 2) + lane % 8, (h * 8 + npl * 2 + lane // 16) * 8], "r", extent=8), T.access_ptr(efrag[0], "w", extent=8))
|
| 559 |
+
for jj in T.unroll(4):
|
| 560 |
+
for c1 in T.unroll(2):
|
| 561 |
+
if KDA:
|
| 562 |
+
cfrag[((npl * 2 + jj // 2) * 4 + mt * 2 + jj % 2) * 2 + c1] = T.cast(efrag[jj * 2 + c1], F32)
|
| 563 |
+
else:
|
| 564 |
+
cfrag[((npl * 2 + jj // 2) * 4 + mt * 2 + jj % 2) * 2 + c1] = T.cast(efrag[jj * 2 + c1], F32) * rpn
|
| 565 |
+
for npl in T.unroll(4):
|
| 566 |
+
n0 = (h * 4 + npl) * 16
|
| 567 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(UQ_s[s, n0 // 64, lane % 8, n0 % 64 + 8 * ((lane // 8) % 2)], "r", extent=4), T.access_ptr(bfr[(npl % 2) * 4], "w", extent=4))
|
| 568 |
+
for mt in T.unroll(2):
|
| 569 |
+
for nn in T.unroll(2):
|
| 570 |
+
T.ptx_mma("float32", "m16n8k8", "row", "col", "fp16", "fp16", "fp32", afrag2.data, mt * 4, bfr.data, (npl % 2) * 4 + nn * 2, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 571 |
+
if not KDA:
|
| 572 |
+
for i in T.unroll(64):
|
| 573 |
+
cfrag[i] = cfrag[i] * pn
|
| 574 |
+
for npl in T.unroll(4):
|
| 575 |
+
n0 = (h * 4 + npl) * 16
|
| 576 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(UQn_s[g, lane % 8, n0 + 8 * ((lane // 8) % 2)], "r", extent=4), T.access_ptr(bfr[(npl % 2) * 4], "w", extent=4))
|
| 577 |
+
for mt in T.unroll(2):
|
| 578 |
+
for nn in T.unroll(2):
|
| 579 |
+
T.ptx_mma("float32", "m16n8k8", "row", "col", "fp16", "fp16", "fp32", afrag3.data, mt * 4, bfr.data, (npl % 2) * 4 + nn * 2, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 580 |
+
for mt in T.unroll(2):
|
| 581 |
+
for npl in T.unroll(4):
|
| 582 |
+
if "noste" not in ABL:
|
| 583 |
+
for jj in T.unroll(4):
|
| 584 |
+
for c1 in T.vectorized(2):
|
| 585 |
+
ph[jj * 2 + c1] = T.cast(cfrag[((npl * 2 + jj // 2) * 4 + mt * 2 + jj % 2) * 2 + c1], F16)
|
| 586 |
+
T.call_extern("handle", "tl::ptx_stmatrix_m8n8_x4",
|
| 587 |
+
T.access_ptr(St_s[g, w * 32 + mt * 16 + 8 * ((lane // 8) % 2) + lane % 8, (h * 8 + npl * 2 + lane // 16) * 8], "w", extent=8),
|
| 588 |
+
T.reinterpret(I32, ph[0:2]), T.reinterpret(I32, ph[2:4]), T.reinterpret(I32, ph[4:6]), T.reinterpret(I32, ph[6:8]))
|
| 589 |
+
# ---- |E| column partials of this warp's 32 rows on the tensor cores (this half's 8 n-tiles): C[m][c] = sum_v 1 * |E[v][c]| with
|
| 590 |
+
# A = ones and B = |E| read back from the fp16 E tile (ldmatrix.x2.trans + sign-bit clear), accumulated into the dead cfrag;
|
| 591 |
+
# every m-row of C holds the sums -- lane rows r0 == 0 are used. No shuffle reduction. ----
|
| 592 |
+
T.sync_warp()
|
| 593 |
+
for i in T.unroll(32):
|
| 594 |
+
cfrag[i] = 0.0
|
| 595 |
+
for ntl in T.unroll(8):
|
| 596 |
+
for ks in T.unroll(2):
|
| 597 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(St_s[g, w * 32 + ks * 16 + 8 * ((lane // 8) % 2) + lane % 8, (h * 8 + ntl) * 8], "r", extent=4), T.access_ptr(bh2[ks * 4], "w", extent=4))
|
| 598 |
+
for i in T.unroll(4):
|
| 599 |
+
bhi[i] = T.reinterpret(I32, bh2[i * 2:i * 2 + 2]) & T.int32(0x7FFF7FFF)
|
| 600 |
+
for ks in T.unroll(2):
|
| 601 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", aone.data, 0, bhi.data, ks * 2, cfrag.data, ntl * 4, T.bool(False))
|
| 602 |
+
for ntl in T.unroll(8):
|
| 603 |
+
for c1 in T.unroll(2):
|
| 604 |
+
colp[(h * 8 + ntl) * 2 + c1] = cfrag[ntl * 4 + c1]
|
| 605 |
+
T.sync_threads(bar, 128) # the residual mma operands (UQn_s, UQ_s) are consumed: the partials may take the buffer, the stage is free
|
| 606 |
+
T.fence_proxy_async()
|
| 607 |
+
T.mbarrier_arrive(consumed[s])
|
| 608 |
+
if r0 == 0:
|
| 609 |
+
for nt in T.unroll(16):
|
| 610 |
+
for c1 in T.vectorized(2):
|
| 611 |
+
cpart[g, w, nt * 8 + q4 * 2 + c1] = colp[nt * 2 + c1]
|
| 612 |
+
T.sync_threads(bar, 128)
|
| 613 |
+
if PROF:
|
| 614 |
+
tk[4] = T.call_extern("int64", "clock64")
|
| 615 |
+
# (4) column scale s_k (thread per column) from the 4 warp partials, reciprocal to smem
|
| 616 |
+
msum = (cpart[g, 0, t] + cpart[g, 1, t] + cpart[g, 2, t] + cpart[g, 3, t]) * (1.0 / V)
|
| 617 |
+
rskn = T.min(T.rsqrt(msum), 1.0 / EPS) # 1/max(sqrt(m), EPS) without the IEEE division slow path
|
| 618 |
+
Sk[slot, hv, t] = T.max(T.sqrt(msum), EPS)
|
| 619 |
+
rsk[g, 6, t] = rskn
|
| 620 |
+
T.sync_threads(bar, 128)
|
| 621 |
+
if PROF:
|
| 622 |
+
tk[5] = T.call_extern("int64", "clock64")
|
| 623 |
+
# (5) row-wise quantisation: warp w rows 32w.., 8 lanes per row (16 columns each), 4 rows per pass;
|
| 624 |
+
# row max over the 8 lanes, int8 codes packed in registers, one coalesced 16 B store per lane and row
|
| 625 |
+
for i in T.unroll(4):
|
| 626 |
+
for c1 in T.vectorized(4):
|
| 627 |
+
rk[i * 4 + c1] = rsk[g, 6, (lane % 8) * 16 + i * 4 + c1]
|
| 628 |
+
for i in T.unroll(8):
|
| 629 |
+
v0 = w * 32 + i * 4 + lane // 8
|
| 630 |
+
rmax[0] = 0.0
|
| 631 |
+
for hh in T.unroll(2):
|
| 632 |
+
for c1 in T.vectorized(8):
|
| 633 |
+
eh[((i % 2) * 2 + hh) * 8 + c1] = St_s[g, v0, (lane % 8) * 16 + hh * 8 + c1]
|
| 634 |
+
for hh in T.unroll(2):
|
| 635 |
+
for c1 in T.unroll(8):
|
| 636 |
+
ex[hh * 8 + c1] = T.cast(eh[((i % 2) * 2 + hh) * 8 + c1], F32) * rk[hh * 8 + c1]
|
| 637 |
+
rmax[0] = T.max(rmax[0], T.abs(ex[hh * 8 + c1]))
|
| 638 |
+
rmax[0] = T.max(rmax[0], T.shfl_xor(rmax[0], 1))
|
| 639 |
+
rmax[0] = T.max(rmax[0], T.shfl_xor(rmax[0], 2))
|
| 640 |
+
rmax[0] = T.max(rmax[0], T.shfl_xor(rmax[0], 4))
|
| 641 |
+
rmax[0] = T.max(rmax[0], EPS)
|
| 642 |
+
rmax[1] = QMAX * T.call_extern(F32, "__frcp_rn", rmax[0])
|
| 643 |
+
if lane % 8 == 0:
|
| 644 |
+
Sv[slot, hv, v0] = rmax[0]
|
| 645 |
+
if "nocode" not in ABL:
|
| 646 |
+
for c1 in T.unroll(4):
|
| 647 |
+
qw[c1] = T.call_extern(I32, "__byte_perm",
|
| 648 |
+
T.call_extern(I32, "__byte_perm", T.reinterpret(I32, ex[c1 * 4] * rmax[1] + 12582912.0), T.reinterpret(I32, ex[c1 * 4 + 1] * rmax[1] + 12582912.0), T.int32(0x0040)),
|
| 649 |
+
T.call_extern(I32, "__byte_perm", T.reinterpret(I32, ex[c1 * 4 + 2] * rmax[1] + 12582912.0), T.reinterpret(I32, ex[c1 * 4 + 3] * rmax[1] + 12582912.0), T.int32(0x0040)),
|
| 650 |
+
T.int32(0x5410))
|
| 651 |
+
for c1 in T.vectorized(4):
|
| 652 |
+
Sq[slot, hv, v0, (lane % 8) * 4 + c1] = qw[c1]
|
| 653 |
+
if PROF:
|
| 654 |
+
tk[6] = T.call_extern("int64", "clock64")
|
| 655 |
+
if t < L:
|
| 656 |
+
Wbuf[slot, hv, t] = 0.0
|
| 657 |
+
if KDA:
|
| 658 |
+
Pbuf[slot, hv, t] = 0.0
|
| 659 |
+
for jj in T.unroll(L):
|
| 660 |
+
Gbuf[slot, hv, jj, t] = T.reinterpret(BF16, T.cast(1.0, F16)) # entry factors -> fp16 1.0
|
| 661 |
+
else:
|
| 662 |
+
if t == 0:
|
| 663 |
+
Pbuf[slot, hv, 0] = 1.0
|
| 664 |
+
# hcnt stays at L: 'flushed, ring empty' for the step kernels (a reset here would change the due flags other CTAs are still scanning)
|
| 665 |
+
T.sync_threads(bar, 128) # St_s / UQn_s reuse by the next program of this group
|
| 666 |
+
if PROF:
|
| 667 |
+
tk[7] = T.call_extern("int64", "clock64")
|
| 668 |
+
if not PROFIT:
|
| 669 |
+
for i in T.unroll(7):
|
| 670 |
+
tacc[i] += T.cast(tk[i + 1] - tk[i], F32)
|
| 671 |
+
tacc[8] += 1.0
|
| 672 |
+
if PROF and g == 0 and t == 0 and bid < HV:
|
| 673 |
+
for i in T.unroll(10):
|
| 674 |
+
Wbuf[0, bid, i] = tacc[i]
|
| 675 |
+
return flush
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
class Pool:
|
| 680 |
+
"""Caller-owned state pool, the layout the serving engine uses. Every (slot, head) owns a V x K fp32-sized region
|
| 681 |
+
(64 KB) of one flat buffer; the checkpoint lives in its first 19 KB:
|
| 682 |
+
bytes [0, 16384) int8 codes, row-major [V, K]
|
| 683 |
+
bytes [16384, 16896) fp32 column scales s_k [K]
|
| 684 |
+
bytes [16896, 17408) fp32 row scales s_v [V]
|
| 685 |
+
bytes [17408, 19456) fp16 Compensator Tokens [R, K + V]: row r = (u[r, :K] | q[r, :V])
|
| 686 |
+
Slots are SS fp32 words apart; slot 0 is reserved (idx 0 = "no sequence"). The update buffer (kbuf, ubuf, w, p) and the
|
| 687 |
+
per-(slot, head) fill counter hcnt are separate dense tensors. A program (slot, head) is due when hcnt == L."""
|
| 688 |
+
|
| 689 |
+
def __init__(self, num_slots, device="cuda"):
|
| 690 |
+
NS = self.NS = num_slots
|
| 691 |
+
self.raw = torch.zeros(NS * SS + OFF, dtype=torch.float32, device=device); st = self.raw.untyped_storage()
|
| 692 |
+
def view(dtype, shape, strides, off):
|
| 693 |
+
return torch.empty(0, dtype=dtype, device=device).set_(st).as_strided(shape, strides, off)
|
| 694 |
+
self.codes = view(torch.int8, (NS, HV, V, K), (4 * SS, 4 * V * K, K, 1), 4 * OFF)
|
| 695 |
+
self.codes32 = view(torch.int32, (NS, HV, V, K // 4), (SS, V * K, K // 4, 1), OFF)
|
| 696 |
+
self.codes16 = view(torch.int16, (NS, HV, V, K // 2), (2 * SS, 2 * V * K, K // 2, 1), 2 * OFF)
|
| 697 |
+
self.s_k = view(torch.float32, (NS, HV, K), (SS, V * K, 1), OFF + V * K // 4)
|
| 698 |
+
self.s_v = view(torch.float32, (NS, HV, V), (SS, V * K, 1), OFF + V * K // 4 + K)
|
| 699 |
+
self.s_kv = view(torch.float32, (NS, HV, K + V), (SS, V * K, 1), OFF + V * K // 4)
|
| 700 |
+
self.uq = view(torch.float16, (NS, HV, R, K + V), (2 * SS, 2 * V * K, K + V, 1), 2 * (OFF + V * K // 4 + K + V))
|
| 701 |
+
self.kbuf = torch.zeros(NS, HV, L, K, dtype=torch.bfloat16, device=device)
|
| 702 |
+
self.ubuf = torch.zeros(NS, HV, L, V, dtype=torch.bfloat16, device=device)
|
| 703 |
+
self.w = torch.zeros(NS, HV, L, device=device)
|
| 704 |
+
self.p = torch.ones(NS, HV, 1, device=device)
|
| 705 |
+
self.hcnt = torch.zeros(NS, HV, dtype=torch.int32, device=device)
|
| 706 |
+
self._gate = torch.zeros(1, 1, 1, 1, dtype=torch.bfloat16, device=device) # placeholder argument (KDA variant only)
|
| 707 |
+
self.kernel = make_flush_kernel(NS, HV, K, V, L, SS, R=R, ITERS=1, NCG=3,
|
| 708 |
+
SMS=torch.cuda.get_device_properties(self.raw.device).multi_processor_count)
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
def flush_inplace(pool, idx, q0):
|
| 712 |
+
"""Deployment form. idx: int32 [N] slot per sequence (0 = skip). For every (idx[n], head) with hcnt == L: rebuild the
|
| 713 |
+
state from the checkpoint and the update buffer, write the new checkpoint over the old one, reset w = 0, p = 1, hcnt = 0."""
|
| 714 |
+
pool.kernel(pool.codes32, pool.s_k, pool.s_v, pool.s_kv, pool.kbuf, pool.ubuf, pool.w, pool.p, pool._gate, pool.hcnt,
|
| 715 |
+
pool.codes16, pool.uq, q0, idx)
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
_POOLS = {}
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
def run(codes, s_k, s_v, u, q, kbuf, ubuf, w, p, q0):
|
| 722 |
+
B = codes.shape[0]
|
| 723 |
+
pool = _POOLS.get((B, codes.device))
|
| 724 |
+
if pool is None:
|
| 725 |
+
pool = _POOLS[(B, codes.device)] = Pool(B + 8, codes.device)
|
| 726 |
+
sl = slice(1, B + 1)
|
| 727 |
+
pool.codes[sl] = codes; pool.s_k[sl] = s_k; pool.s_v[sl] = s_v; pool.uq[sl, :, :, :K] = u; pool.uq[sl, :, :, K:] = q
|
| 728 |
+
pool.kbuf[sl] = kbuf; pool.ubuf[sl] = ubuf; pool.w[sl] = w; pool.p[sl, :, 0] = p
|
| 729 |
+
pool.hcnt.zero_(); pool.hcnt[sl] = L
|
| 730 |
+
flush_inplace(pool, torch.arange(1, B + 1, dtype=torch.int32, device=codes.device), q0.contiguous())
|
| 731 |
+
return (pool.codes[sl].clone(), pool.s_k[sl].clone(), pool.s_v[sl].clone(),
|
| 732 |
+
pool.uq[sl, :, :, :K].clone(), pool.uq[sl, :, :, K:].clone())
|
gdn/benchmark.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
"""Correctness and timing of a flush implementation against definition.json (see README.md for the criterion).
|
| 3 |
+
|
| 4 |
+
python benchmark.py # the baseline in this directory
|
| 5 |
+
python benchmark.py --impl my_flush.py # a candidate exposing run(...) and, for timing, Pool / flush_inplace
|
| 6 |
+
|
| 7 |
+
Correctness (functional form `run`, every batch size in workloads.jsonl, three inputs each: a synthetic checkpoint with
|
| 8 |
+
edge-case heads, the checkpoint the reference produced from it, and unstructured in-domain random tensors):
|
| 9 |
+
the new checkpoint is decoded back to a V x K state and compared with the exactly rebuilt fp64 state, head by head:
|
| 10 |
+
err = mean |decode(checkpoint) - S| over the head's V x K elements, for the candidate and for the reference.
|
| 11 |
+
PASS <=> all outputs finite, codes in [-127, 127], and for every head
|
| 12 |
+
err_candidate <= (1 + REL_TOL) * err_reference if err_reference >= FLOOR * mean |S|
|
| 13 |
+
err_candidate <= CAP * mean |S| otherwise (a head the format captures almost exactly)
|
| 14 |
+
The order of operations and the precision of intermediates are free; what is bounded is the accuracy of the
|
| 15 |
+
checkpoint. Timing (deployment form `flush_inplace` on a caller-owned pool, every program due): CUDA kernel time
|
| 16 |
+
from the torch profiler, L2-cold -- NSETS disjoint slot sets are flushed in rotation so no call finds its data in L2.
|
| 17 |
+
"""
|
| 18 |
+
import argparse, importlib.util, json, sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
import torch
|
| 21 |
+
from torch.profiler import profile, ProfilerActivity
|
| 22 |
+
|
| 23 |
+
HERE = Path(__file__).resolve().parent
|
| 24 |
+
HV, K, V, L, R, QMAX = 32, 128, 128, 16, 4, 127.0
|
| 25 |
+
REL_TOL, FLOOR, CAP = 0.01, 1e-4, 1e-3 # 1 % more error than the reference; heads whose reference error is below 1e-4 |S| are held to 1e-3 |S|
|
| 26 |
+
NSETS, WARMUP, ITERS = 8, 4, 16
|
| 27 |
+
KB_PER_PROGRAM = 19 + 8 + 19 + 0.1 # checkpoint read + update buffer read + checkpoint write + resets
|
| 28 |
+
REF_TBPS = 6.3 # read + write bandwidth of the stock vLLM fp32 decode kernel on B200 at batch 256 (the memory-bound yardstick)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def load(path, name):
|
| 32 |
+
spec = importlib.util.spec_from_file_location(name, path); mod = importlib.util.module_from_spec(spec)
|
| 33 |
+
sys.modules[name] = mod; spec.loader.exec_module(mod); return mod
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def decode(codes, s_k, s_v, u, q):
|
| 37 |
+
return (torch.einsum("bhrv,bhrk->bhvk", q.double(), u.double())
|
| 38 |
+
+ codes.double() * (s_k.double()[..., None, :] / QMAX) * s_v.double()[..., :, None])
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def update_buffer(bs, dev, g):
|
| 42 |
+
rn = lambda *s: torch.randn(*s, device=dev, generator=g)
|
| 43 |
+
kbuf = (rn(bs, HV, L, K) * 0.3).to(torch.bfloat16); ubuf = (rn(bs, HV, L, V) * 0.3).to(torch.bfloat16)
|
| 44 |
+
w = torch.rand(bs, HV, L, device=dev, generator=g); p = torch.rand(bs, HV, device=dev, generator=g) * 0.5 + 0.5
|
| 45 |
+
return kbuf, ubuf, w, p
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def structured_inputs(bs, dev, seed=0):
|
| 49 |
+
"""A synthetic checkpoint (full-rank codes with positive scales, a low-rank part, one hot row) and a random update
|
| 50 |
+
buffer. Heads 1..6 are edge cases: rank 1, all zero, rank 2, tiny (1e-4), huge (3e2), rank 1 plus a noise floor."""
|
| 51 |
+
g = torch.Generator(device=dev).manual_seed(seed)
|
| 52 |
+
rn = lambda *s: torch.randn(*s, device=dev, generator=g)
|
| 53 |
+
codes = (rn(bs, HV, V, K) * 40).round().clamp(-127, 127).to(torch.int8)
|
| 54 |
+
s_k = torch.rand(bs, HV, K, device=dev, generator=g) * 0.2 + 0.05; s_v = torch.rand(bs, HV, V, device=dev, generator=g) * 0.5 + 0.1
|
| 55 |
+
s_v[..., 5] *= 30
|
| 56 |
+
u = (rn(bs, HV, R, K) * 0.5).to(torch.float16); q = (rn(bs, HV, R, V) * 0.5).to(torch.float16)
|
| 57 |
+
kbuf, ubuf, w, p = update_buffer(bs, dev, g)
|
| 58 |
+
for h in (1, 2, 3, 6): codes[:, h] = 0; u[:, h] = 0; q[:, h] = 0
|
| 59 |
+
w[:, 1, 1:] = 0; w[:, 2] = 0; w[:, 3, 2:] = 0; w[:, 6, 1:] = 0
|
| 60 |
+
codes[:, 6] = (rn(bs, V, K) * 40).round().clamp(-127, 127).to(torch.int8); s_k[:, 6] *= 1e-6
|
| 61 |
+
s_k[:, 4] *= 1e-4; u[:, 4] *= 1e-2; ubuf[:, 4] *= 1e-4
|
| 62 |
+
s_k[:, 5] *= 3e2; u[:, 5] *= 17; ubuf[:, 5] *= 3e2
|
| 63 |
+
q0 = torch.randn(V, R, generator=torch.Generator().manual_seed(0)).to(dev)
|
| 64 |
+
return codes, s_k, s_v, u, q, kbuf, ubuf, w, p, q0
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def random_inputs(bs, dev, seed=1):
|
| 68 |
+
"""Unstructured tensors inside the deployment domain: positive scales, 0 < p <= 1, 0 <= w <= 1."""
|
| 69 |
+
g = torch.Generator(device=dev).manual_seed(seed)
|
| 70 |
+
rn = lambda *s, dt=torch.float32: torch.randn(*s, device=dev, generator=g).to(dt)
|
| 71 |
+
lu = lambda *s: torch.exp(rn(*s) * 0.7) # positive scales spread over about two decades; |S| stays in the deployment range (below 1e4)
|
| 72 |
+
return (torch.randint(-127, 128, (bs, HV, V, K), device=dev, generator=g, dtype=torch.int8), lu(bs, HV, K) * 0.05, lu(bs, HV, V) * 0.3,
|
| 73 |
+
rn(bs, HV, R, K, dt=torch.float16), rn(bs, HV, R, V, dt=torch.float16), rn(bs, HV, L, K, dt=torch.bfloat16),
|
| 74 |
+
rn(bs, HV, L, V, dt=torch.bfloat16), torch.rand(bs, HV, L, device=dev, generator=g), torch.rand(bs, HV, device=dev, generator=g) * 0.999 + 0.001, rn(V, R))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def exact_state(inp):
|
| 78 |
+
codes, s_k, s_v, u, q, kbuf, ubuf, w, p, q0 = inp
|
| 79 |
+
return p.double()[..., None, None] * decode(codes, s_k, s_v, u, q) + torch.einsum("bhj,bhjv,bhjk->bhvk", w.double(), ubuf.double(), kbuf.double())
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def judge(out, ref, S):
|
| 83 |
+
finite = all(bool(torch.isfinite(t.float()).all()) for t in out[1:]); inrange = bool((out[0].int().abs() <= 127).all())
|
| 84 |
+
e_out = (decode(*out) - S).abs().mean((0, 2, 3)); e_ref = (decode(*ref) - S).abs().mean((0, 2, 3)); mag = S.abs().mean((0, 2, 3))
|
| 85 |
+
tight = (e_ref >= FLOOR * mag) & (e_ref > 0) # an all-zero head has e_ref = 0 and falls under the cap (which is then 0)
|
| 86 |
+
ok = finite and inrange and bool((e_out[tight] <= (1 + REL_TOL) * e_ref[tight]).all()) and bool((e_out[~tight] <= CAP * mag[~tight]).all())
|
| 87 |
+
ratio = (e_out[tight] / e_ref[tight]).max().item() # worst head among those compared relatively
|
| 88 |
+
return ok, ratio
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def check(bs, impl, ref_run, dev):
|
| 92 |
+
first = structured_inputs(bs, dev, seed=bs)
|
| 93 |
+
ref1 = ref_run(*[t.clone() for t in first])
|
| 94 |
+
second = (*ref1, *update_buffer(bs, dev, torch.Generator(device=dev).manual_seed(bs + 1)), first[9]) # the next window, from the reference's checkpoint
|
| 95 |
+
res = []
|
| 96 |
+
for inp, ref in ((first, ref1), (second, None), (random_inputs(bs, dev, seed=bs + 2), None)):
|
| 97 |
+
ref = ref_run(*[t.clone() for t in inp]) if ref is None else ref
|
| 98 |
+
out = impl.run(*[t.clone() for t in inp]); torch.cuda.synchronize()
|
| 99 |
+
res.append(judge(out, ref, exact_state(inp)))
|
| 100 |
+
return res
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def ktime(fn):
|
| 104 |
+
for i in range(WARMUP): fn(i % NSETS)
|
| 105 |
+
torch.cuda.synchronize()
|
| 106 |
+
with profile(activities=[ProfilerActivity.CUDA]) as prof:
|
| 107 |
+
for i in range(ITERS): fn(i % NSETS)
|
| 108 |
+
torch.cuda.synchronize()
|
| 109 |
+
ev = [e for e in prof.events() if e.device_type.name == "CUDA" and "fill" not in e.name.lower() and "mem" not in e.name.lower()]
|
| 110 |
+
return sum(e.device_time for e in ev) / ITERS / 1000
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def timing(bs, impl, dev):
|
| 114 |
+
pool = impl.Pool(NSETS * bs + 8, dev)
|
| 115 |
+
pool.raw.normal_(0, 0.1); pool.uq.normal_(0, 0.1) # arbitrary checkpoint contents: timing only
|
| 116 |
+
pool.kbuf.copy_(torch.randn(pool.kbuf.shape, device=dev)); pool.ubuf.copy_(torch.randn(pool.ubuf.shape, device=dev)); pool.w.uniform_(0, 1)
|
| 117 |
+
q0 = torch.randn(V, R, generator=torch.Generator().manual_seed(0)).to(dev)
|
| 118 |
+
idxs = [torch.arange(1 + j * bs, 1 + (j + 1) * bs, dtype=torch.int32, device=dev) for j in range(NSETS)]
|
| 119 |
+
def call(j):
|
| 120 |
+
pool.hcnt.index_fill_(0, idxs[j].long(), L) # every program of the set is due (the kernel resets the counter)
|
| 121 |
+
impl.flush_inplace(pool, idxs[j], q0)
|
| 122 |
+
return ktime(call)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def main():
|
| 126 |
+
ap = argparse.ArgumentParser(); ap.add_argument("--impl", default=str(HERE / "baseline.py")); ap.add_argument("--skip-timing", action="store_true")
|
| 127 |
+
a = ap.parse_args(); dev = torch.device("cuda")
|
| 128 |
+
name = torch.cuda.get_device_name(0); assert any(m in name.split() for m in ("B200", "B300")), name
|
| 129 |
+
d = json.loads((HERE / "definition.json").read_text()); ns = {}; exec(d["reference"], ns); ref_run = ns["run"]
|
| 130 |
+
sizes = [json.loads(l)["workload"]["axes"]["batch_size"] for l in (HERE / "workloads.jsonl").read_text().splitlines() if line_ok(l)]
|
| 131 |
+
impl = load(a.impl, "flush_impl")
|
| 132 |
+
print(f"{name}, torch {torch.__version__}, impl {Path(a.impl).name}\n")
|
| 133 |
+
print("| batch_size | programs | worst-head error ratio vs reference (structured / second window / random) | correctness | all-due latency (ms) | memory bound (ms) |")
|
| 134 |
+
print("| --- | --- | --- | --- | --- | --- |")
|
| 135 |
+
allok = True
|
| 136 |
+
for bs in sizes:
|
| 137 |
+
res = check(bs, impl, ref_run, dev); ok = all(r[0] for r in res); allok &= ok
|
| 138 |
+
t_ms = float("nan") if a.skip_timing or not hasattr(impl, "flush_inplace") else timing(bs, impl, dev)
|
| 139 |
+
bound = KB_PER_PROGRAM * 1024 * bs * HV / REF_TBPS / 1e12 * 1e3
|
| 140 |
+
print(f"| {bs} | {bs * HV} | {res[0][1]:.4f} / {res[1][1]:.4f} / {res[2][1]:.4f} | {'PASS' if ok else 'FAIL'} | {t_ms:.4f} | {bound:.3f} |", flush=True)
|
| 141 |
+
assert allok, f"correctness failed (limit: {1 + REL_TOL:.2f}x the reference's error per head, or {CAP:g} |S| where the reference error is below {FLOOR:g} |S|)"
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def line_ok(l):
|
| 145 |
+
return bool(l.strip())
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
main()
|
gdn/benchmark_results.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"measurement": "Final authoritative KDA paired evaluation of the unmodified PR #10 benchmark.",
|
| 3 |
+
"timestamp_utc": "2026-10-24T10:57:39Z",
|
| 4 |
+
"gpu": "NVIDIA B300 SXM6 AC",
|
| 5 |
+
"toolchain": {
|
| 6 |
+
"torch": "2.12.1+cu130",
|
| 7 |
+
"tilelang_baseline": "0.1.12",
|
| 8 |
+
"cutlass_dsl": "4.6.0",
|
| 9 |
+
"claude_cli": "2.1.308",
|
| 10 |
+
"codex_cli": "0.163.0"
|
| 11 |
+
},
|
| 12 |
+
"kernel_sha256": "a734b59e75a8c8e870d68280c59c4fe05e9e3d2334c4d7e62d7101c67c9cd9b6",
|
| 13 |
+
"submission_id": "8f705942197446f4",
|
| 14 |
+
"all_geomean": 2.5505261735195206,
|
| 15 |
+
"large_geomean": 2.813364086682488,
|
| 16 |
+
"workloads": [
|
| 17 |
+
{
|
| 18 |
+
"batch_size": 16,
|
| 19 |
+
"speedup": 2.15,
|
| 20 |
+
"correctness_passed": true
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"batch_size": 32,
|
| 24 |
+
"speedup": 2.2486187845303864,
|
| 25 |
+
"correctness_passed": true
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"batch_size": 64,
|
| 29 |
+
"speedup": 2.557093425605536,
|
| 30 |
+
"correctness_passed": true
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"batch_size": 128,
|
| 34 |
+
"speedup": 2.8156312625250504,
|
| 35 |
+
"correctness_passed": true
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"batch_size": 256,
|
| 39 |
+
"speedup": 2.8874172185430464,
|
| 40 |
+
"correctness_passed": true
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"batch_size": 512,
|
| 44 |
+
"speedup": 2.7390029325513194,
|
| 45 |
+
"correctness_passed": true
|
| 46 |
+
}
|
| 47 |
+
]
|
| 48 |
+
}
|
gdn/definition.json
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "leapquant_gdn_flush_r4_int8_h32_v128_k128",
|
| 3 |
+
"op_type": "leapquant_gdn_flush",
|
| 4 |
+
"description": "LeapQuant window flush (arXiv:2609.38166) for gated-delta-rule linear attention decode: at the end of a 16-token window, rebuild each head's V x K fp32 recurrent state from its quantized checkpoint (4 fp16 Compensator Tokens + smoothed int8 residual) and the window's 16 buffered rank-1 updates, then re-quantize it (one round of subspace iteration for the new Compensator Tokens, smoothing scales and int8 codes for the residual). Correctness is judged on the decoded state (see the request README), not elementwise.",
|
| 5 |
+
"axes": {
|
| 6 |
+
"batch_size": {
|
| 7 |
+
"type": "var"
|
| 8 |
+
},
|
| 9 |
+
"num_heads": {
|
| 10 |
+
"type": "const",
|
| 11 |
+
"value": 32
|
| 12 |
+
},
|
| 13 |
+
"value_dim": {
|
| 14 |
+
"type": "const",
|
| 15 |
+
"value": 128
|
| 16 |
+
},
|
| 17 |
+
"key_dim": {
|
| 18 |
+
"type": "const",
|
| 19 |
+
"value": 128
|
| 20 |
+
},
|
| 21 |
+
"window": {
|
| 22 |
+
"type": "const",
|
| 23 |
+
"value": 16
|
| 24 |
+
},
|
| 25 |
+
"rank": {
|
| 26 |
+
"type": "const",
|
| 27 |
+
"value": 4
|
| 28 |
+
}
|
| 29 |
+
},
|
| 30 |
+
"inputs": {
|
| 31 |
+
"codes": {
|
| 32 |
+
"shape": [
|
| 33 |
+
"batch_size",
|
| 34 |
+
"num_heads",
|
| 35 |
+
"value_dim",
|
| 36 |
+
"key_dim"
|
| 37 |
+
],
|
| 38 |
+
"dtype": "int8"
|
| 39 |
+
},
|
| 40 |
+
"s_k": {
|
| 41 |
+
"shape": [
|
| 42 |
+
"batch_size",
|
| 43 |
+
"num_heads",
|
| 44 |
+
"key_dim"
|
| 45 |
+
],
|
| 46 |
+
"dtype": "float32"
|
| 47 |
+
},
|
| 48 |
+
"s_v": {
|
| 49 |
+
"shape": [
|
| 50 |
+
"batch_size",
|
| 51 |
+
"num_heads",
|
| 52 |
+
"value_dim"
|
| 53 |
+
],
|
| 54 |
+
"dtype": "float32"
|
| 55 |
+
},
|
| 56 |
+
"u": {
|
| 57 |
+
"shape": [
|
| 58 |
+
"batch_size",
|
| 59 |
+
"num_heads",
|
| 60 |
+
"rank",
|
| 61 |
+
"key_dim"
|
| 62 |
+
],
|
| 63 |
+
"dtype": "float16"
|
| 64 |
+
},
|
| 65 |
+
"q": {
|
| 66 |
+
"shape": [
|
| 67 |
+
"batch_size",
|
| 68 |
+
"num_heads",
|
| 69 |
+
"rank",
|
| 70 |
+
"value_dim"
|
| 71 |
+
],
|
| 72 |
+
"dtype": "float16"
|
| 73 |
+
},
|
| 74 |
+
"kbuf": {
|
| 75 |
+
"shape": [
|
| 76 |
+
"batch_size",
|
| 77 |
+
"num_heads",
|
| 78 |
+
"window",
|
| 79 |
+
"key_dim"
|
| 80 |
+
],
|
| 81 |
+
"dtype": "bfloat16"
|
| 82 |
+
},
|
| 83 |
+
"ubuf": {
|
| 84 |
+
"shape": [
|
| 85 |
+
"batch_size",
|
| 86 |
+
"num_heads",
|
| 87 |
+
"window",
|
| 88 |
+
"value_dim"
|
| 89 |
+
],
|
| 90 |
+
"dtype": "bfloat16"
|
| 91 |
+
},
|
| 92 |
+
"w": {
|
| 93 |
+
"shape": [
|
| 94 |
+
"batch_size",
|
| 95 |
+
"num_heads",
|
| 96 |
+
"window"
|
| 97 |
+
],
|
| 98 |
+
"dtype": "float32"
|
| 99 |
+
},
|
| 100 |
+
"p": {
|
| 101 |
+
"shape": [
|
| 102 |
+
"batch_size",
|
| 103 |
+
"num_heads"
|
| 104 |
+
],
|
| 105 |
+
"dtype": "float32"
|
| 106 |
+
},
|
| 107 |
+
"q0": {
|
| 108 |
+
"shape": [
|
| 109 |
+
"value_dim",
|
| 110 |
+
"rank"
|
| 111 |
+
],
|
| 112 |
+
"dtype": "float32"
|
| 113 |
+
}
|
| 114 |
+
},
|
| 115 |
+
"outputs": {
|
| 116 |
+
"codes_new": {
|
| 117 |
+
"shape": [
|
| 118 |
+
"batch_size",
|
| 119 |
+
"num_heads",
|
| 120 |
+
"value_dim",
|
| 121 |
+
"key_dim"
|
| 122 |
+
],
|
| 123 |
+
"dtype": "int8"
|
| 124 |
+
},
|
| 125 |
+
"s_k_new": {
|
| 126 |
+
"shape": [
|
| 127 |
+
"batch_size",
|
| 128 |
+
"num_heads",
|
| 129 |
+
"key_dim"
|
| 130 |
+
],
|
| 131 |
+
"dtype": "float32"
|
| 132 |
+
},
|
| 133 |
+
"s_v_new": {
|
| 134 |
+
"shape": [
|
| 135 |
+
"batch_size",
|
| 136 |
+
"num_heads",
|
| 137 |
+
"value_dim"
|
| 138 |
+
],
|
| 139 |
+
"dtype": "float32"
|
| 140 |
+
},
|
| 141 |
+
"u_new": {
|
| 142 |
+
"shape": [
|
| 143 |
+
"batch_size",
|
| 144 |
+
"num_heads",
|
| 145 |
+
"rank",
|
| 146 |
+
"key_dim"
|
| 147 |
+
],
|
| 148 |
+
"dtype": "float16"
|
| 149 |
+
},
|
| 150 |
+
"q_new": {
|
| 151 |
+
"shape": [
|
| 152 |
+
"batch_size",
|
| 153 |
+
"num_heads",
|
| 154 |
+
"rank",
|
| 155 |
+
"value_dim"
|
| 156 |
+
],
|
| 157 |
+
"dtype": "float16"
|
| 158 |
+
}
|
| 159 |
+
},
|
| 160 |
+
"constraints": [
|
| 161 |
+
"batch_size >= 1"
|
| 162 |
+
],
|
| 163 |
+
"reference": "# SPDX-License-Identifier: Apache-2.0\nimport torch\n\nQMAX = 127.0\nEPS = 1e-12\n\n\ndef _mgs(m):\n \"\"\"Modified Gram-Schmidt on the columns of m, projections applied twice (\"twice is enough\"): a column that is\n numerically dependent on the previous ones (a rank-deficient head) still comes out orthogonal to them.\"\"\"\n cols = []\n for j in range(m.shape[-1]):\n v = m[..., j]\n for _ in range(2):\n for c in cols:\n v = v - c * (c * v).sum(-1, keepdim=True)\n cols.append(v / v.norm(dim=-1, keepdim=True).clamp_min(1e-30))\n return torch.stack(cols, -1)\n\n\ndef run(codes, s_k, s_v, u, q, kbuf, ubuf, w, p, q0):\n \"\"\"LeapQuant window flush: fold the buffered updates of one window into a new quantized checkpoint.\n\n codes int8 [B, H, V, K], s_k f32 [B, H, K], s_v f32 [B, H, V]: smoothed int8 residual of the old checkpoint\n u f16 [B, H, R, K], q f16 [B, H, R, V]: the R Compensator Tokens of the old checkpoint (rank-R part = q^T u)\n kbuf bf16 [B, H, L, K], ubuf bf16 [B, H, L, V], w f32 [B, H, L], p f32 [B, H]: the window's buffered updates\n q0 f32 [V, R]: fixed start of the subspace iteration\n Returns the new (codes, s_k, s_v, u, q). fp32 arithmetic; the order of operations is not part of the contract.\n \"\"\"\n # 1. rebuild the fp32 state: S = p * (q^T u + dequant(codes)) + sum_j w_j ubuf_j kbuf_j^T [V, K]\n s_old = torch.einsum(\"bhrv,bhrk->bhvk\", q.float(), u.float())\n s_old = s_old + codes.float() * (s_k[..., None, :] / QMAX) * s_v[..., :, None]\n s = p[..., None, None] * s_old + torch.einsum(\"bhj,bhjv,bhjk->bhvk\", w, ubuf.float(), kbuf.float())\n # 2. Compensator Tokens: ONE round of subspace iteration from q0, stored as fp16\n x = s.transpose(-1, -2) # [K, V]\n qk = _mgs(x @ q0) # [K, R]\n qv = _mgs(x.transpose(-1, -2) @ qk) # [V, R], orthonormal columns\n uk = x @ qv # [K, R]\n u_new = uk.transpose(-1, -2).to(torch.float16)\n q_new = qv.transpose(-1, -2).to(torch.float16)\n # 3. residual, smoothing scales (column scale = sqrt of the mean |E| over rows, row scale = max of the smoothed row), int8\n e = s - torch.einsum(\"bhrv,bhrk->bhvk\", q_new.float(), u_new.float())\n sk = e.abs().mean(-2).sqrt().clamp_min(EPS)\n sv = (e.abs() / sk[..., None, :]).amax(-1).clamp_min(EPS)\n c = torch.round(e / (sk[..., None, :] * sv[..., :, None]) * QMAX).clamp(-QMAX, QMAX).to(torch.int8)\n return c, sk, sv, u_new, q_new\n"
|
| 164 |
+
}
|
gdn/provenance.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"repo_id": "humanfia-lab/kernels",
|
| 3 |
+
"version": 1,
|
| 4 |
+
"source_url": "https://github.com/NVlabs/kda/pull/10",
|
| 5 |
+
"source_commit": "48f02e6ba0e98a1841ab6f0a2d99a90b2de1a326",
|
| 6 |
+
"upstream_sha256": {
|
| 7 |
+
"baseline.py": "b53f30426a9647e523fc6463a5a8d1ba1a9c0f9a09d83599b10abf631346712f",
|
| 8 |
+
"benchmark.py": "58c5404386dd121ef7e2dca73c3488c7e23b1e0d16f69e23dc1d33b563d3d62f",
|
| 9 |
+
"definition.json": "313e8b7d2d7305fb09aaa6771eb6482ee2182567339a4d7c33388e9db68296d7",
|
| 10 |
+
"workloads.jsonl": "4fb72f317e2eabd9752907e6bd0d4cebc4e9a23c6c48c5a4a95750e13e805145"
|
| 11 |
+
},
|
| 12 |
+
"kernel_sha256": "a734b59e75a8c8e870d68280c59c4fe05e9e3d2334c4d7e62d7101c67c9cd9b6",
|
| 13 |
+
"kernel_git_commit": "06975ceabe46d5122fe76b742f71d1eeb841a9bd",
|
| 14 |
+
"official_submission_id": "8f705942197446f4",
|
| 15 |
+
"official_artifact_digest": "8d7d94ad883d3c95960eea61a2b63cb85b9633f900ed26394cb1bd82ccc2ef11",
|
| 16 |
+
"official_benchmarks_sha": "3ac105d12ef108513555f8eac2a39203c0a18c5af3a8b6f77cb12751274ede75",
|
| 17 |
+
"official_evaluation_utc": "2026-10-24T10:57:39Z",
|
| 18 |
+
"experiment_hours": 48,
|
| 19 |
+
"models": [
|
| 20 |
+
"codex/gpt-6.1-sol:max",
|
| 21 |
+
"claude/claude-opus-5-5:max"
|
| 22 |
+
],
|
| 23 |
+
"packaging": "Unmodified accepted kernel; exposed as a module of the combined HF package.",
|
| 24 |
+
"component": "gdn",
|
| 25 |
+
"kernel_path": "build/torch-cuda/_gdn.py"
|
| 26 |
+
}
|
gdn/validate.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
"""Validate the local HF package and caller-owned deployment contract on CUDA."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import base64
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from kernels import get_local_kernel
|
| 12 |
+
|
| 13 |
+
import benchmark as bench
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def main() -> None:
|
| 17 |
+
here = Path(__file__).resolve().parent
|
| 18 |
+
runtime = here.parent / "build/torch-cuda"
|
| 19 |
+
metadata = json.loads((runtime / "metadata.json").read_text())
|
| 20 |
+
for filename, expected in metadata["digest"]["files"].items():
|
| 21 |
+
actual = base64.b64encode(hashlib.sha256((runtime / filename).read_bytes()).digest()).decode()
|
| 22 |
+
assert actual == expected, f"digest mismatch: {filename}"
|
| 23 |
+
op = get_local_kernel(here.parent, trust_remote_code=True).gdn
|
| 24 |
+
assert all(hasattr(op, name) for name in ("Pool", "flush_inplace", "run"))
|
| 25 |
+
namespace = {}
|
| 26 |
+
exec(json.loads((here / "definition.json").read_text())["reference"], namespace)
|
| 27 |
+
reference = namespace["run"]
|
| 28 |
+
device = torch.device("cuda")
|
| 29 |
+
ns = 8
|
| 30 |
+
pool = op.Pool(ns, device=device)
|
| 31 |
+
is_kda = hasattr(pool, "gbuf")
|
| 32 |
+
idx = torch.tensor([0, 7, 2, 5, 1, 3], dtype=torch.int32, device=device)
|
| 33 |
+
counters = torch.where(torch.arange(ns * 32, device=device).reshape(ns, 32) % 3 == 0, 16, 7).int()
|
| 34 |
+
selected = torch.zeros(ns, dtype=torch.bool, device=device)
|
| 35 |
+
selected[idx.long()] = True
|
| 36 |
+
selected[0] = False
|
| 37 |
+
due = selected[:, None] & (counters == 16)
|
| 38 |
+
fields = ["codes", "s_k", "s_v", "uq", "kbuf", "ubuf", "w", "hcnt"] + (["gbuf", "pcum"] if is_kda else ["p"])
|
| 39 |
+
q0 = torch.empty(128, 4, device=device)
|
| 40 |
+
|
| 41 |
+
def restore(inputs):
|
| 42 |
+
pool.codes.copy_(inputs[0]); pool.s_k.copy_(inputs[1]); pool.s_v.copy_(inputs[2])
|
| 43 |
+
pool.uq[..., :128].copy_(inputs[3]); pool.uq[..., 128:].copy_(inputs[4])
|
| 44 |
+
pool.kbuf.copy_(inputs[5]); pool.ubuf.copy_(inputs[6])
|
| 45 |
+
if is_kda:
|
| 46 |
+
pool.gbuf.copy_(inputs[7]); pool.w.copy_(inputs[8]); pool.pcum.copy_(inputs[9])
|
| 47 |
+
else:
|
| 48 |
+
pool.w.copy_(inputs[7]); pool.p[..., 0].copy_(inputs[8])
|
| 49 |
+
pool.hcnt.copy_(counters)
|
| 50 |
+
q0.copy_(inputs[-1])
|
| 51 |
+
|
| 52 |
+
def snapshot():
|
| 53 |
+
return {name: getattr(pool, name).clone() for name in fields}
|
| 54 |
+
|
| 55 |
+
def verify(inputs, before):
|
| 56 |
+
ref = reference(*[tensor.clone() for tensor in inputs])
|
| 57 |
+
actual = (pool.codes, pool.s_k, pool.s_v, pool.uq[..., :128], pool.uq[..., 128:])
|
| 58 |
+
# Each selected (slot, head) is a separate checked head, never averaged across slots.
|
| 59 |
+
out = tuple(tensor[due].unsqueeze(0) for tensor in actual)
|
| 60 |
+
ref = tuple(tensor[due].unsqueeze(0) for tensor in ref)
|
| 61 |
+
exact = bench.exact_state(inputs)[due].unsqueeze(0)
|
| 62 |
+
passed, ratio = bench.judge(out, ref, exact)
|
| 63 |
+
assert passed, f"deployment accuracy failed: {ratio}"
|
| 64 |
+
for name in fields:
|
| 65 |
+
assert torch.equal(getattr(pool, name)[~due], before[name][~due]), f"non-due/slot-0 write: {name}"
|
| 66 |
+
for name in ("kbuf", "ubuf"):
|
| 67 |
+
assert torch.equal(getattr(pool, name), before[name]), f"update buffer changed: {name}"
|
| 68 |
+
# The serving contract leaves hcnt at L ("flushed, empty"); the decode
|
| 69 |
+
# step consumes that sentinel. Clearing it in flush would race scanners.
|
| 70 |
+
assert torch.equal(pool.hcnt, before["hcnt"]), "flush changed fill counters"
|
| 71 |
+
assert bool((pool.w[due] == 0).all())
|
| 72 |
+
if is_kda:
|
| 73 |
+
assert bool((pool.gbuf[due] == 1).all())
|
| 74 |
+
assert bool((pool.pcum[due] == 0).all())
|
| 75 |
+
else:
|
| 76 |
+
assert bool((pool.p[due] == 1).all())
|
| 77 |
+
return float(ratio)
|
| 78 |
+
|
| 79 |
+
stream = torch.cuda.Stream()
|
| 80 |
+
inputs = bench.structured_inputs(ns, device, seed=91)
|
| 81 |
+
restore(inputs)
|
| 82 |
+
torch.cuda.synchronize()
|
| 83 |
+
before = snapshot()
|
| 84 |
+
torch.cuda.synchronize()
|
| 85 |
+
with torch.cuda.stream(stream):
|
| 86 |
+
op.flush_inplace(pool, idx, q0)
|
| 87 |
+
stream.synchronize()
|
| 88 |
+
ratios = [verify(inputs, before)]
|
| 89 |
+
before = snapshot()
|
| 90 |
+
op.flush_inplace(pool, torch.empty(0, dtype=torch.int32, device=device), q0)
|
| 91 |
+
torch.cuda.synchronize()
|
| 92 |
+
assert all(torch.equal(getattr(pool, name), before[name]) for name in fields), "empty idx is not a no-op"
|
| 93 |
+
|
| 94 |
+
restore(inputs)
|
| 95 |
+
torch.cuda.synchronize()
|
| 96 |
+
graph = torch.cuda.CUDAGraph()
|
| 97 |
+
with torch.cuda.graph(graph, stream=stream):
|
| 98 |
+
op.flush_inplace(pool, idx, q0)
|
| 99 |
+
for seed in (92, 93):
|
| 100 |
+
inputs = bench.structured_inputs(ns, device, seed=seed)
|
| 101 |
+
# structured_inputs always uses the same q0; vary it explicitly here.
|
| 102 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 103 |
+
inputs = (*inputs[:-1], torch.randn(128, 4, device=device, generator=generator))
|
| 104 |
+
restore(inputs)
|
| 105 |
+
before = snapshot()
|
| 106 |
+
torch.cuda.synchronize()
|
| 107 |
+
graph.replay()
|
| 108 |
+
torch.cuda.synchronize()
|
| 109 |
+
ratios.append(verify(inputs, before))
|
| 110 |
+
# Simulate the caller advancing the counters so no head is due.
|
| 111 |
+
pool.hcnt[due] = 0
|
| 112 |
+
after = snapshot()
|
| 113 |
+
torch.cuda.synchronize()
|
| 114 |
+
graph.replay()
|
| 115 |
+
torch.cuda.synchronize()
|
| 116 |
+
assert all(torch.equal(getattr(pool, name), after[name]) for name in fields), "replay with no due heads is not a no-op"
|
| 117 |
+
print(json.dumps({
|
| 118 |
+
"status": "pass", "gpu": torch.cuda.get_device_name(),
|
| 119 |
+
"compute_capability": list(torch.cuda.get_device_capability()),
|
| 120 |
+
"checks": ["runtime digests", "HF get_local_kernel", "mixed due heads", "unselected slots", "reserved slot 0", "window resets", "fill counters unchanged", "empty idx", "non-default stream", "graph capture", "graph replay with changed inputs and q0", "no-op replay with no due heads"],
|
| 121 |
+
"deployment_worst_head_error_ratios": ratios,
|
| 122 |
+
}, indent=2))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
main()
|
gdn/validation_results.json
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"validated_at_utc": "2026-10-25T20:03:16.823824+00:00",
|
| 3 |
+
"kernel_sha256": "a734b59e75a8c8e870d68280c59c4fe05e9e3d2334c4d7e62d7101c67c9cd9b6",
|
| 4 |
+
"deployment": {
|
| 5 |
+
"status": "pass",
|
| 6 |
+
"gpu": "NVIDIA B300 SXM6 AC",
|
| 7 |
+
"compute_capability": [
|
| 8 |
+
10,
|
| 9 |
+
3
|
| 10 |
+
],
|
| 11 |
+
"checks": [
|
| 12 |
+
"runtime digests",
|
| 13 |
+
"HF get_local_kernel",
|
| 14 |
+
"mixed due heads",
|
| 15 |
+
"unselected slots",
|
| 16 |
+
"reserved slot 0",
|
| 17 |
+
"window resets",
|
| 18 |
+
"fill counters unchanged",
|
| 19 |
+
"empty idx",
|
| 20 |
+
"non-default stream",
|
| 21 |
+
"graph capture",
|
| 22 |
+
"graph replay with changed inputs and q0",
|
| 23 |
+
"no-op replay with no due heads"
|
| 24 |
+
],
|
| 25 |
+
"deployment_worst_head_error_ratios": [
|
| 26 |
+
1.0022517222625789,
|
| 27 |
+
1.0016240993273937,
|
| 28 |
+
1.0018801265800452
|
| 29 |
+
]
|
| 30 |
+
},
|
| 31 |
+
"original_benchmark": {
|
| 32 |
+
"workloads_passed": 6,
|
| 33 |
+
"input_families_per_workload": 3,
|
| 34 |
+
"thresholds_modified": false,
|
| 35 |
+
"workloads": [
|
| 36 |
+
{
|
| 37 |
+
"batch_size": 16,
|
| 38 |
+
"programs": 512,
|
| 39 |
+
"error_ratios": [
|
| 40 |
+
1.0004,
|
| 41 |
+
1.0003,
|
| 42 |
+
1.0004
|
| 43 |
+
],
|
| 44 |
+
"latency_ms": 0.0121,
|
| 45 |
+
"correctness_passed": true
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"batch_size": 32,
|
| 49 |
+
"programs": 1024,
|
| 50 |
+
"error_ratios": [
|
| 51 |
+
1.0004,
|
| 52 |
+
1.0002,
|
| 53 |
+
1.0002
|
| 54 |
+
],
|
| 55 |
+
"latency_ms": 0.0183,
|
| 56 |
+
"correctness_passed": true
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"batch_size": 64,
|
| 60 |
+
"programs": 2048,
|
| 61 |
+
"error_ratios": [
|
| 62 |
+
1.0002,
|
| 63 |
+
1.0002,
|
| 64 |
+
1.0002
|
| 65 |
+
],
|
| 66 |
+
"latency_ms": 0.029,
|
| 67 |
+
"correctness_passed": true
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"batch_size": 128,
|
| 71 |
+
"programs": 4096,
|
| 72 |
+
"error_ratios": [
|
| 73 |
+
1.0002,
|
| 74 |
+
1.0004,
|
| 75 |
+
1.0001
|
| 76 |
+
],
|
| 77 |
+
"latency_ms": 0.0499,
|
| 78 |
+
"correctness_passed": true
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"batch_size": 256,
|
| 82 |
+
"programs": 8192,
|
| 83 |
+
"error_ratios": [
|
| 84 |
+
1.0001,
|
| 85 |
+
1.0004,
|
| 86 |
+
1.0001
|
| 87 |
+
],
|
| 88 |
+
"latency_ms": 0.091,
|
| 89 |
+
"correctness_passed": true
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"batch_size": 512,
|
| 93 |
+
"programs": 16384,
|
| 94 |
+
"error_ratios": [
|
| 95 |
+
1.0001,
|
| 96 |
+
1.0003,
|
| 97 |
+
1.0001
|
| 98 |
+
],
|
| 99 |
+
"latency_ms": 0.1706,
|
| 100 |
+
"correctness_passed": true
|
| 101 |
+
}
|
| 102 |
+
]
|
| 103 |
+
},
|
| 104 |
+
"environment": {
|
| 105 |
+
"python": "3.12.13",
|
| 106 |
+
"torch": "2.12.1+cu130",
|
| 107 |
+
"cutlass_dsl": "4.6.0",
|
| 108 |
+
"cuda_bindings": "13.3.1",
|
| 109 |
+
"kernels": "0.17.2",
|
| 110 |
+
"huggingface_hub": "2.2.0"
|
| 111 |
+
}
|
| 112 |
+
}
|
gdn/workloads.jsonl
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"definition": "leapquant_gdn_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "37b74c8b-2ae8-4b82-91c4-472d69507bc1", "axes": {"batch_size": 16}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "w": {"type": "random"}, "p": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
| 2 |
+
{"definition": "leapquant_gdn_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "f34d2357-d8c6-4002-850a-6fca954ff598", "axes": {"batch_size": 32}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "w": {"type": "random"}, "p": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
| 3 |
+
{"definition": "leapquant_gdn_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "3d65a1d3-81cb-47b2-ba5c-91a892d2a479", "axes": {"batch_size": 64}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "w": {"type": "random"}, "p": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
| 4 |
+
{"definition": "leapquant_gdn_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "491dbee1-9c39-4140-8668-2db1198ce937", "axes": {"batch_size": 128}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "w": {"type": "random"}, "p": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
| 5 |
+
{"definition": "leapquant_gdn_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "b016fecf-c600-44a4-a469-84d3ccb05b95", "axes": {"batch_size": 256}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "w": {"type": "random"}, "p": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
| 6 |
+
{"definition": "leapquant_gdn_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "927f32c0-7206-48fd-bd39-3c9682be7ee7", "axes": {"batch_size": 512}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "w": {"type": "random"}, "p": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
kda/README.md
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LeapQuant Kimi Delta Attention checkpoint flush
|
| 2 |
+
|
| 3 |
+
CuTe DSL window-boundary re-quantization of the recurrent state for Kimi Delta Attention.
|
| 4 |
+
This is the flush operation, with the checkpoint format and one-round subspace
|
| 5 |
+
iteration specified in [NVlabs/kda#10](https://github.com/NVlabs/kda/pull/10).
|
| 6 |
+
It does not implement the per-token decode operation or a complete model layer.
|
| 7 |
+
|
| 8 |
+
The final accepted implementation achieved **2.999x overall**
|
| 9 |
+
and **3.128x on batches 128, 256 and 512** versus the
|
| 10 |
+
request's TileLang baseline on NVIDIA B300 SXM6 AC. All six workloads passed the
|
| 11 |
+
original accuracy criterion. These are the final paired KDA measurements from
|
| 12 |
+
2026-10-24T12:38:34Z; they are kernel timings for the deployment interface, not timings
|
| 13 |
+
of allocation, input packing or the functional `run` wrapper.
|
| 14 |
+
|
| 15 |
+
## Requirements and supported inputs
|
| 16 |
+
|
| 17 |
+
- NVIDIA B300, CUDA compute capability **10.3**. This release advertises only the
|
| 18 |
+
tested architecture; other GPU architectures are not validated.
|
| 19 |
+
- CUDA 13-compatible driver; tested with PyTorch 2.12.1+cu130,
|
| 20 |
+
`nvidia-cutlass-dsl[cu13]==4.6.0` and `cuda-bindings==13.3.1`.
|
| 21 |
+
- Python 3.12 and `kernels==0.17.2` were used for package validation.
|
| 22 |
+
- Fixed geometry: 32 heads, value/key dimension 128, window 16, rank 4.
|
| 23 |
+
Dense benchmark batches: 16, 32, 64, 128, 256 and 512.
|
| 24 |
+
- `codes`: int8 `[B,32,128,128]`; `s_k`/`s_v`: fp32 `[B,32,128]`;
|
| 25 |
+
`u`/`q`: fp16 `[B,32,4,128]`; `kbuf`/`ubuf`: bf16 `[B,32,16,128]`;
|
| 26 |
+
`w`: fp32 `[B,32,16]`; `q0`: contiguous fp32 `[128,4]` on the same CUDA device.
|
| 27 |
+
- `gbuf`: fp16 `[B,32,16,128]` in `(0,1]`; `pcum`: fp32 `[B,32,128]`, cumulative non-positive log-gates.
|
| 28 |
+
|
| 29 |
+
Checkpoint scales are positive and the request's deployment domain has state
|
| 30 |
+
magnitudes below 1e4. See the complete [upstream input contract](https://github.com/NVlabs/kda/tree/48f02e6ba0e98a1841ab6f0a2d99a90b2de1a326/requests/conless-leapquant-kda-flush)
|
| 31 |
+
and [reference definition](https://huggingface.co/kernels/humanfia-lab/kernels/blob/v1/kda/definition.json).
|
| 32 |
+
|
| 33 |
+
## Load and use
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
import torch
|
| 37 |
+
from kernels import get_kernel
|
| 38 |
+
|
| 39 |
+
op = get_kernel("humanfia-lab/kernels", version=1, trust_remote_code=True).kda
|
| 40 |
+
B, H, V, K, L, R = 16, 32, 128, 128, 16, 4
|
| 41 |
+
codes = torch.zeros(B, H, V, K, dtype=torch.int8, device="cuda")
|
| 42 |
+
s_k = torch.full((B, H, K), 0.05, device="cuda")
|
| 43 |
+
s_v = torch.full((B, H, V), 0.3, device="cuda")
|
| 44 |
+
u = torch.zeros(B, H, R, K, dtype=torch.float16, device="cuda")
|
| 45 |
+
q = torch.zeros(B, H, R, V, dtype=torch.float16, device="cuda")
|
| 46 |
+
kbuf = (torch.randn(B, H, L, K, device="cuda") * 0.3).bfloat16()
|
| 47 |
+
ubuf = (torch.randn(B, H, L, V, device="cuda") * 0.3).bfloat16()
|
| 48 |
+
w = torch.rand(B, H, L, device="cuda")
|
| 49 |
+
gbuf = torch.ones_like(kbuf, dtype=torch.float16)
|
| 50 |
+
pcum = torch.zeros(B, H, K, device="cuda")
|
| 51 |
+
q0 = torch.linalg.qr(torch.randn(V, R, device="cuda"))[0].contiguous()
|
| 52 |
+
|
| 53 |
+
new_codes, new_s_k, new_s_v, new_u, new_q = op.run(
|
| 54 |
+
codes, s_k, s_v, u, q, kbuf, ubuf, gbuf, w, pcum, q0
|
| 55 |
+
)
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
`run` returns five fresh checkpoint tensors and leaves the supplied inputs
|
| 59 |
+
unchanged. It includes allocation/packing overhead. Use serial calls to `run`;
|
| 60 |
+
for independent concurrent streams, use an independent caller-owned `Pool` per
|
| 61 |
+
stream and keep calls on each pool ordered.
|
| 62 |
+
|
| 63 |
+
For serving, use the original caller-owned pool interface:
|
| 64 |
+
|
| 65 |
+
```python
|
| 66 |
+
pool = op.Pool(B + 8, device="cuda") # allocates buffers and JIT-compiles kernels
|
| 67 |
+
sl = slice(1, B + 1) # slot 0 is reserved
|
| 68 |
+
pool.codes[sl], pool.s_k[sl], pool.s_v[sl] = codes, s_k, s_v
|
| 69 |
+
pool.uq[sl, :, :, :K], pool.uq[sl, :, :, K:] = u, q
|
| 70 |
+
pool.kbuf[sl], pool.ubuf[sl], pool.w[sl] = kbuf, ubuf, w
|
| 71 |
+
pool.gbuf[sl] = gbuf
|
| 72 |
+
pool.pcum[sl] = pcum
|
| 73 |
+
pool.hcnt[sl] = L
|
| 74 |
+
idx = torch.arange(1, B + 1, dtype=torch.int32, device="cuda")
|
| 75 |
+
op.flush_inplace(pool, idx, q0) # checkpoint stays in pool; returns None
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
`idx` is a contiguous CUDA int32 vector of valid, unique slot indices. Index 0
|
| 79 |
+
is skipped. Only selected heads whose fill counter equals 16 are flushed;
|
| 80 |
+
non-due heads and unselected slots remain unchanged. A due head resets `w = 0`, `gbuf = 1`, `pcum = 0`.
|
| 81 |
+
The fill counter remains at `L`: the decode step interprets this as "flushed,
|
| 82 |
+
empty" and advances it. Flush does not clear it, because other CTAs may still
|
| 83 |
+
be scanning the due flags.
|
| 84 |
+
`q0` is the supplied fixed start basis, not the previous window's factors.
|
| 85 |
+
|
| 86 |
+
Construct the pool and perform warmup before CUDA graph capture. Refill the
|
| 87 |
+
window buffers and counters before each new window. Calls use the current CUDA
|
| 88 |
+
stream on the pool's device. Keep the pool, index vector and `q0` buffers alive
|
| 89 |
+
while a graph using their addresses is alive. The supplied `validate.py` checks
|
| 90 |
+
mixed due heads, slot 0, reset/no-op behavior, a non-default stream and graph
|
| 91 |
+
replay with changed input contents.
|
| 92 |
+
|
| 93 |
+
## Accuracy and timing
|
| 94 |
+
|
| 95 |
+
The original benchmark compares decoded checkpoints with the exactly rebuilt
|
| 96 |
+
fp64 state for structured edge-case heads, a second window and unstructured
|
| 97 |
+
in-domain random inputs at each batch size. For every head, reconstruction
|
| 98 |
+
error may be at most 1.01x the reference's error; nearly exact reference heads
|
| 99 |
+
use the original absolute cap `1e-3 * mean(abs(S))`. Outputs must be finite and
|
| 100 |
+
int8 codes must remain in [-127,127]. The upstream benchmark and thresholds are
|
| 101 |
+
included unchanged.
|
| 102 |
+
|
| 103 |
+
Deployment timing uses `flush_inplace`, all programs due, eight disjoint slot
|
| 104 |
+
sets rotated to avoid L2 reuse, four warmups and 16 measured iterations, and
|
| 105 |
+
CUDA kernel time from the PyTorch profiler. Large means batches >=128.
|
| 106 |
+
|
| 107 |
+
| Batch | Final paired speedup | Accuracy |
|
| 108 |
+
|---:|---:|---|
|
| 109 |
+
| 16 | 2.669x | pass |
|
| 110 |
+
| 32 | 2.811x | pass |
|
| 111 |
+
| 64 | 3.170x | pass |
|
| 112 |
+
| 128 | 3.219x | pass |
|
| 113 |
+
| 256 | 3.094x | pass |
|
| 114 |
+
| 512 | 3.073x | pass |
|
| 115 |
+
| Geomean, all six | 2.999x | 6/6 pass |
|
| 116 |
+
| Geomean, batch >=128 | 3.128x | 3/3 pass |
|
| 117 |
+
|
| 118 |
+
These measurements are workload- and hardware-specific. The functional `run`
|
| 119 |
+
wrapper is not the timed deployment entrypoint.
|
| 120 |
+
|
| 121 |
+
## Reproduce
|
| 122 |
+
|
| 123 |
+
Download the combined repository, then enter this component directory:
|
| 124 |
+
|
| 125 |
+
```bash
|
| 126 |
+
hf download humanfia-lab/kernels --repo-type kernel --revision v1 --local-dir leapquant-kernels
|
| 127 |
+
cd leapquant-kernels/kda
|
| 128 |
+
python -m pip install torch==2.12.1 --index-url https://download.pytorch.org/whl/cu130
|
| 129 |
+
python -m pip install -r ../requirements.txt
|
| 130 |
+
python benchmark.py --impl ../build/torch-cuda/_kda.py # six original workloads
|
| 131 |
+
python benchmark.py # original TileLang baseline
|
| 132 |
+
python validate.py # package loader and deployment checks
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
TileLang and `nvcc` on `PATH` are needed only to benchmark the original baseline.
|
| 136 |
+
The CuTe implementation JIT-compiles on first use; do not include compilation in
|
| 137 |
+
steady-state timings or perform first-use compilation inside graph capture.
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
The unchanged kernel passed all six original workloads (three input families
|
| 141 |
+
each) and deployment checks on B300 before consolidation; the original reports
|
| 142 |
+
are retained in `validation_results.json`. The speedup table retains the paired
|
| 143 |
+
optimization-run measurement, not a new baseline comparison.
|
| 144 |
+
|
| 145 |
+
## Files and provenance
|
| 146 |
+
|
| 147 |
+
The combined runtime is in `../build/torch-cuda/`; this component's unchanged
|
| 148 |
+
kernel is `_kda.py`. The files in this directory provide its original
|
| 149 |
+
benchmark, baseline, definition, workloads, results, validation and provenance.
|
| 150 |
+
Shared dependencies and licenses are at the repository root.
|
| 151 |
+
|
| 152 |
+
The runtime kernel is byte-for-byte the final accepted submission
|
| 153 |
+
`e797d585430d45e1` (SHA-256 `2f635896b70d13ddfd76822d711f75c8c3abb4606f0ccd25dd04b583b95b7ec6`), from a 48-hour KDA experiment
|
| 154 |
+
with GPT 6.1 and Claude Opus 5.5. Request sources are pinned to public commit
|
| 155 |
+
`48f02e6ba0e98a1841ab6f0a2d99a90b2de1a326`. The release adds a public import wrapper, metadata
|
| 156 |
+
and validation scripts; it does not change the kernel algorithm. Apache-2.0;
|
| 157 |
+
see `../LICENSE.txt` and `../NOTICE`.
|
| 158 |
+
|
| 159 |
+
## Available functions
|
| 160 |
+
|
| 161 |
+
- `run`
|
| 162 |
+
- `Pool`
|
| 163 |
+
- `flush_inplace`
|
kda/baseline.py
ADDED
|
@@ -0,0 +1,789 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
"""Best-known LeapQuant flush kernel for Kimi Delta Attention (per-key-channel gate; see README.md).
|
| 3 |
+
|
| 4 |
+
Warp-specialised TileLang kernel for sm_100 (B200): one persistent CTA per SM, a TMA producer warp and three
|
| 5 |
+
128-thread consumer groups, products on tensor cores (mma.sync m16n8k16, bf16 hi/lo operands), the subspace iteration
|
| 6 |
+
on an fp16 copy of the rebuilt state in shared memory with the old rank-4 part carried algebraically, CholeskyQR2 with
|
| 7 |
+
a relative pivot floor for the new Compensator Tokens, the residual accumulated in fp32 from the checkpoint, the
|
| 8 |
+
buffered updates and both rank-4 parts, the due programs balanced across CTAs by a rank scan.
|
| 9 |
+
|
| 10 |
+
run(...) functional form with the input order / outputs of definition.json (packs the inputs into a slot
|
| 11 |
+
pool, calls the kernel, returns the new checkpoint as fresh tensors) -- used for correctness
|
| 12 |
+
Pool, flush_inplace deployment form: caller-owned strided slot pool updated in place -- what benchmark.py times
|
| 13 |
+
|
| 14 |
+
Requires: torch (CUDA), tilelang 0.1.12, CUDA toolkit 13 (nvcc), NVIDIA B200.
|
| 15 |
+
"""
|
| 16 |
+
import torch, tilelang, tilelang.language as T
|
| 17 |
+
from tilelang.layout import make_swizzled_layout
|
| 18 |
+
|
| 19 |
+
F32, BF16, I32, I8 = "float32", "bfloat16", "int32", "int8"
|
| 20 |
+
QMAX = 127.0
|
| 21 |
+
EPS = 1e-12
|
| 22 |
+
HV, K, V, L, R = 32, 128, 128, 16, 4 # heads per sequence, key dim, value dim, window length, rank
|
| 23 |
+
SS, OFF = 33 * V * K, 12288 # pool geometry in fp32 words: slot stride (one spare head per slot), base offset
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@tilelang.jit(pass_configs={"tl.disable_thread_storage_sync": True})
|
| 27 |
+
def make_flush_kernel(NS, HV, K, V, L, SS, R=4, ITERS=1, SMS=148, NCG=3, MAXIT=128, PROF=False, PAD=8, KDA=False, GB16=True, PROFIT=False, DROPLO=False, MMT="bf16", ABL="", PNMIN=1e-20, GRAM16=False, NSTAGE=0, NMAX=0, KEXACT=True, **_ignored):
|
| 28 |
+
"""TileLang generator of the flush kernel (KDA=True: the per-channel gate of this request; KDA=False is the scalar-gate
|
| 29 |
+
variant of requests/conless-leapquant-gdn-flush). The rebuilt state B (state minus the old rank-4 part) lives in shared
|
| 30 |
+
memory as fp16 for the subspace iteration; the old rank-4 part is carried algebraically; the residual is accumulated
|
| 31 |
+
in fp32 from the stage (see KEXACT below) and quantised row-wise. Keyword switches other than the shapes are
|
| 32 |
+
ablations (defaults are the deployed configuration)."""
|
| 33 |
+
# KEXACT (KDA): the residual E is accumulated from fp32 terms only -- the stage (codes, scales, decayed keys, values) is still resident,
|
| 34 |
+
# so B is rebuilt in registers instead of read back from the fp16 St_s, and the old Compensator Tokens stay unscaled in UQ_s rows
|
| 35 |
+
# 0..R-1: E = (deq(S0) + Q_old U_old^T) pc + ring buffer - Q U^T with pc = exp(Pbuf) in fp32. The subspace iteration still runs on
|
| 36 |
+
# the fp16 St_s and an fp16 pc U_old^T copy in the zero padding rows R..2R-1 (only the new factors' quality depends on those).
|
| 37 |
+
# E then goes to St_s as fp16 scaled by a power of two per (warp, half), so tiny heads do not fall into fp16 subnormals.
|
| 38 |
+
# Without KEXACT (pc U_old^T rounded in place, E from the fp16 B, unscaled) the reconstruction error is 1-8 % above the fp32
|
| 39 |
+
# reference's; with it 0.1-0.3 % (+20 % flush time: the second dequantisation).
|
| 40 |
+
KEX = bool(KDA and KEXACT)
|
| 41 |
+
assert not KEX or 2 * R <= 8
|
| 42 |
+
# Gbuf holds fp16 factors; it is declared bf16 so the TMA target (Kbl_s, later the lo key tile) matches -- the bits are reinterpreted on read
|
| 43 |
+
assert 1 <= R <= 4 and K == 128 and V == 128 and (not KDA or GB16) and PAD == 8
|
| 44 |
+
F16 = "float16"
|
| 45 |
+
N = T.symbolic("N")
|
| 46 |
+
KW = K // 4
|
| 47 |
+
NPROD = 32
|
| 48 |
+
NCONS = 128 * NCG
|
| 49 |
+
NT = NPROD + NCONS
|
| 50 |
+
NWARPS = NT // 32
|
| 51 |
+
NDUE = min(NS - 8, NMAX) if NMAX else NS - 8 # rows that can be due at once: one call's rows (NMAX = the engine's batch cap) or the whole table
|
| 52 |
+
MAXIT = max(MAXIT, (NDUE * HV + SMS - 1) // SMS + 1) # dlist capacity: a CTA's share of all programs when every such row is due
|
| 53 |
+
# (with NMAX the list is ~350 B instead of 5.5 KB on an 8155-slot engine: on sm_120 that is the difference between a 2-stage flush fitting in 99 KB or not)
|
| 54 |
+
KMAX = min((NS + NWARPS - 1) // NWARPS, 40) # n-steps per warp kept in registers by the compaction (3 x 40 registers; N <= 40 * NWARPS =
|
| 55 |
+
# 520 sequences at NCG = 3, vLLM's max_num_seqs 512); larger batches take a serial tail
|
| 56 |
+
# with the flags recomputed in the rank pass (64 steps spilled: +3 us none-due)
|
| 57 |
+
NSTAGE = NSTAGE or NCG # NSTAGE > NCG: each group double-buffers its stage (the TMA warp prefetches the group's
|
| 58 |
+
assert NSTAGE % NCG == 0 # next due program while it works) -- worth it where one group is all that fits (sm_120)
|
| 59 |
+
SPG = NSTAGE // NCG
|
| 60 |
+
KP = K + PAD # St_s row stride: conflict-free fragment stores, ldmatrix rows and 16 B row reads; the pad holds the fp16 Q tile
|
| 61 |
+
KV8 = K + V + 8 # UQn_s row stride (halfwords): 528 B -> conflict-free ldmatrix rows
|
| 62 |
+
P16OFF = 4 * KV8 # fp16 P tile (K x 8) at halfword offset 4 rows into UQn_s (after the fp32 Q plane)
|
| 63 |
+
assert 4 * KV8 * 2 >= (V + 4) * 4 * 4 and 4 * KV8 >= K * 8
|
| 64 |
+
|
| 65 |
+
@T.prim_func
|
| 66 |
+
def flush(Sq: T.StridedTensor((NS, HV, V, KW), (SS, V * K, KW, 1), I32),
|
| 67 |
+
Sk: T.StridedTensor((NS, HV, K), (SS, V * K, 1), F32),
|
| 68 |
+
Sv: T.StridedTensor((NS, HV, V), (SS, V * K, 1), F32),
|
| 69 |
+
Skv: T.StridedTensor((NS, HV, K + V), (SS, V * K, 1), F32),
|
| 70 |
+
Kbuf: T.Tensor((NS, HV, L, K), BF16), Ubuf: T.Tensor((NS, HV, L, V), BF16),
|
| 71 |
+
Wbuf: T.Tensor((NS, HV, L), F32), Pbuf: T.Tensor((NS, HV, K if KDA else 1), F32), Gbuf: T.Tensor((NS, HV, L, K) if KDA else (1, 1, 1, 1), BF16), hcnt: T.Tensor((NS, HV), I32),
|
| 72 |
+
Sq16: T.StridedTensor((NS, HV, V, K // 2), (2 * SS, 2 * V * K, K // 2, 1), "int16"), # unused (kept for the v2 call signature)
|
| 73 |
+
UQ: T.StridedTensor((NS, HV, R, K + V), (2 * SS, 2 * V * K, K + V, 1), F16), # fp16 factors U^T | Q^T after the scales
|
| 74 |
+
Q0: T.Tensor((V, R), F32), # deterministic start of the subspace iteration
|
| 75 |
+
idx: T.Tensor((N,), I32)):
|
| 76 |
+
with T.Kernel(SMS, threads=NPROD + NCONS) as bid:
|
| 77 |
+
Qs = T.alloc_shared((NSTAGE, V, KW), I32)
|
| 78 |
+
skv_s = T.alloc_shared((NSTAGE, K + V), F32)
|
| 79 |
+
Kb_s = T.alloc_shared((NSTAGE, 2, L, K // 2), BF16) # two 128 B-wide halves, 128 B swizzle (conflict-free ldmatrix)
|
| 80 |
+
Ub_s = T.alloc_shared((NSTAGE, 2, L, V // 2), BF16)
|
| 81 |
+
Wb_s = T.alloc_shared((NSTAGE, 32), F32) # 128 B per stage (TMA destination alignment)
|
| 82 |
+
UQ_s = T.alloc_shared((NSTAGE, 4, 8, 64), F16) # old factors U^T | Q^T in four 128 B-wide column blocks (swizzled: conflict-free ldmatrix rows), k-rows padded to 8 (rows R.. zero)
|
| 83 |
+
St_s = T.alloc_shared((NCG, V, KP), F16) # B (fp16) for the iteration, then the residual E in place; columns K.. = the fp16 Q tile (V x 8, columns R.. zero)
|
| 84 |
+
UQn_s = T.alloc_shared((NCG, 8, KV8), F16) # new -U^T (rows R.. zero) for the residual mma; aliases: PQ_s (fp32 Q rows), P16 (fp16 P tile), cpart (column partials)
|
| 85 |
+
PQ_s = T.view(UQn_s, (NCG, 2, KV8 // 2, 4), F32) # plane 0 = Q (V x R) fp32 for the CholeskyQR rows
|
| 86 |
+
UQn1 = T.view(UQn_s, (NCG, 8 * KV8), F16) # flat view: the fp16 P tile P16[c][r] at P16OFF + 8 c + r
|
| 87 |
+
cpart = T.view(UQn_s, (NCG, 8, KV8 // 2), F32) # per-warp column partials of |E| (rows 0..3)
|
| 88 |
+
rsk = T.view(UQn_s, (NCG, 8, KV8 // 2), F32) # reciprocal column scales: row 6 of the cpart view (free once the partials are read)
|
| 89 |
+
dlist = T.alloc_shared((MAXIT,), I32) # this CTA's due programs p (global rank == bid mod SMS), in rank order
|
| 90 |
+
ndue_s = T.alloc_shared((1,), I32)
|
| 91 |
+
wsum_s = T.alloc_shared((NWARPS,), I32) # per-warp due counts of the block-wide compaction
|
| 92 |
+
if KDA:
|
| 93 |
+
Kbl_s = T.alloc_shared((NSTAGE, 2, L, K // 2), BF16) # per-entry decay factors (TMA target, fp16 bits) -> lo part of the decayed keys
|
| 94 |
+
pb_s = T.alloc_shared((NSTAGE, K), F32)
|
| 95 |
+
pc_s = T.alloc_shared((NCG, K), F32)
|
| 96 |
+
loaded = T.alloc_barrier([32] * NSTAGE)
|
| 97 |
+
consumed = T.alloc_barrier([128] * NSTAGE)
|
| 98 |
+
if KDA:
|
| 99 |
+
T.annotate_layout({Qs: make_swizzled_layout(Qs), Kb_s: make_swizzled_layout(Kb_s), Ub_s: make_swizzled_layout(Ub_s), Kbl_s: make_swizzled_layout(Kbl_s), UQ_s: make_swizzled_layout(UQ_s)})
|
| 100 |
+
else:
|
| 101 |
+
T.annotate_layout({Qs: make_swizzled_layout(Qs), Kb_s: make_swizzled_layout(Kb_s), Ub_s: make_swizzled_layout(Ub_s), UQ_s: make_swizzled_layout(UQ_s)})
|
| 102 |
+
tx = T.get_thread_binding()
|
| 103 |
+
# ---- block-wide balanced compaction (no atomics): every CTA scans all N * HV due flags -- warp w takes the sequences
|
| 104 |
+
# n = w, w + NWARPS, ..., lane hv the head (one broadcast idx load + one coalesced 128 B hcnt load per n; an uncoalesced
|
| 105 |
+
# gather costs 32 L1 lookups per warp-load and was 8x slower) -- ranks the due programs with ballot/popc in the fixed order
|
| 106 |
+
# (warp, n-step, hv) and keeps the ranks == bid (mod SMS). The flush is latency-bound at 1/16 duty (1-3 programs per
|
| 107 |
+
# group): the static assignment's binomial imbalance (max 12 of mean 3.6 per CTA at bs 256) cost ~1.4x; this gives +-1.
|
| 108 |
+
# dlist holds q = slot * HV + hv. ----
|
| 109 |
+
tc = T.alloc_local((4,), "int64")
|
| 110 |
+
if PROF:
|
| 111 |
+
tc[0] = T.call_extern("int64", "clock64")
|
| 112 |
+
wlane = tx % 32
|
| 113 |
+
wid = tx // 32
|
| 114 |
+
kn = T.alloc_local((1,), I32)
|
| 115 |
+
kn[0] = T.ceildiv(N, NWARPS) # n-steps per warp
|
| 116 |
+
cnt = T.alloc_local((1,), I32)
|
| 117 |
+
cnt[0] = 0
|
| 118 |
+
slk = T.alloc_local((KMAX,), I32)
|
| 119 |
+
hck = T.alloc_local((KMAX,), I32)
|
| 120 |
+
mk = T.alloc_local((KMAX,), "uint32")
|
| 121 |
+
for k in T.unroll(KMAX): # all loads in flight at once (explicit clamps: no guard branches)
|
| 122 |
+
slk[k] = idx[T.max(T.min(wid + NWARPS * k, N - 1), 0)]
|
| 123 |
+
for k in T.unroll(KMAX):
|
| 124 |
+
hck[k] = hcnt[T.min(T.max(slk[k], 0), NS - 1), wlane]
|
| 125 |
+
for k in T.unroll(KMAX):
|
| 126 |
+
f = T.if_then_else((k < kn[0]) & (wid + NWARPS * k < N) & (slk[k] > 0) & (hck[k] == L), 1, 0)
|
| 127 |
+
mk[k] = T.call_extern("uint32", "__ballot_sync", T.uint32(0xFFFFFFFF), f)
|
| 128 |
+
cnt[0] += T.call_extern(I32, "__popc", mk[k])
|
| 129 |
+
sl8 = T.alloc_local((8,), I32)
|
| 130 |
+
hc8 = T.alloc_local((8,), I32)
|
| 131 |
+
for ck in T.serial(T.ceildiv(kn[0] - KMAX, 8)): # tail (N > KMAX * NWARPS only): serial chunks, flags recomputed in the rank pass
|
| 132 |
+
for j in T.unroll(8):
|
| 133 |
+
sl8[j] = idx[T.max(T.min(wid + NWARPS * (KMAX + ck * 8 + j), N - 1), 0)]
|
| 134 |
+
for j in T.unroll(8):
|
| 135 |
+
hc8[j] = hcnt[T.min(T.max(sl8[j], 0), NS - 1), wlane]
|
| 136 |
+
for j in T.unroll(8):
|
| 137 |
+
k = KMAX + ck * 8 + j
|
| 138 |
+
f = T.if_then_else((k < kn[0]) & (wid + NWARPS * k < N) & (sl8[j] > 0) & (hc8[j] == L), 1, 0)
|
| 139 |
+
cnt[0] += T.call_extern(I32, "__popc", T.call_extern("uint32", "__ballot_sync", T.uint32(0xFFFFFFFF), f))
|
| 140 |
+
if PROF:
|
| 141 |
+
tc[1] = T.call_extern("int64", "clock64")
|
| 142 |
+
if wlane == 0:
|
| 143 |
+
wsum_s[wid] = cnt[0]
|
| 144 |
+
T.sync_threads(14, NPROD + NCONS)
|
| 145 |
+
base = T.alloc_local((1,), I32)
|
| 146 |
+
base[0] = 0
|
| 147 |
+
for ww in T.serial(NWARPS):
|
| 148 |
+
base[0] += T.if_then_else(ww < wid, wsum_s[ww], 0)
|
| 149 |
+
tot = T.alloc_local((1,), I32)
|
| 150 |
+
tot[0] = 0
|
| 151 |
+
for ww in T.serial(NWARPS):
|
| 152 |
+
tot[0] += wsum_s[ww]
|
| 153 |
+
T.sync_threads(14, NPROD + NCONS) # wsum_s reads done before dlist (which may share its smem) is written
|
| 154 |
+
lmask = T.cast((T.int64(1) << T.cast(wlane, "int64")) - T.int64(1), "uint32")
|
| 155 |
+
if cnt[0] > 0: # warps without due programs skip the pass (masks past kn are zero)
|
| 156 |
+
rst = T.alloc_local((2,), I32) # next rank == bid (mod SMS) at or above base, and its dlist index (one division per thread)
|
| 157 |
+
rst[0] = base[0] + (bid - base[0] % SMS + SMS) % SMS
|
| 158 |
+
rst[1] = rst[0] // SMS
|
| 159 |
+
for k in T.unroll(KMAX): # static indexing of the mask registers; one predicate per step, no division
|
| 160 |
+
m = mk[k]
|
| 161 |
+
rank = base[0] + T.call_extern(I32, "__popc", m & lmask)
|
| 162 |
+
if (((m >> T.cast(wlane, "uint32")) & T.uint32(1)) == T.uint32(1)) & (rank == rst[0]):
|
| 163 |
+
dlist[rst[1]] = idx[wid + NWARPS * k] * HV + wlane
|
| 164 |
+
base[0] += T.call_extern(I32, "__popc", m)
|
| 165 |
+
if rst[0] < base[0]: # the warp's rank sequence passed the target (warp-uniform; at most one target per step)
|
| 166 |
+
rst[0] += SMS
|
| 167 |
+
rst[1] += 1
|
| 168 |
+
for ck in T.serial(T.ceildiv(kn[0] - KMAX, 8)):
|
| 169 |
+
for j in T.unroll(8):
|
| 170 |
+
sl8[j] = idx[T.max(T.min(wid + NWARPS * (KMAX + ck * 8 + j), N - 1), 0)]
|
| 171 |
+
for j in T.unroll(8):
|
| 172 |
+
hc8[j] = hcnt[T.min(T.max(sl8[j], 0), NS - 1), wlane]
|
| 173 |
+
for j in T.unroll(8):
|
| 174 |
+
k = KMAX + ck * 8 + j
|
| 175 |
+
f = T.if_then_else((k < kn[0]) & (wid + NWARPS * k < N) & (sl8[j] > 0) & (hc8[j] == L), 1, 0)
|
| 176 |
+
m = T.call_extern("uint32", "__ballot_sync", T.uint32(0xFFFFFFFF), f)
|
| 177 |
+
if f == 1:
|
| 178 |
+
rank = base[0] + T.call_extern(I32, "__popc", m & lmask)
|
| 179 |
+
if rank % SMS == bid:
|
| 180 |
+
dlist[rank // SMS] = sl8[j] * HV + wlane
|
| 181 |
+
base[0] += T.call_extern(I32, "__popc", m)
|
| 182 |
+
if tx == 0:
|
| 183 |
+
ndue_s[0] = T.max(T.ceildiv(tot[0] - bid, SMS), 0)
|
| 184 |
+
if PROF:
|
| 185 |
+
tc[2] = T.call_extern("int64", "clock64")
|
| 186 |
+
if tx < NPROD:
|
| 187 |
+
for i in T.serial(NSTAGE * 4 * (8 - R) * 64 // NPROD): # zero the padding k-rows of UQ_s once (only rows < R are ever written)
|
| 188 |
+
e = tx + NPROD * i
|
| 189 |
+
UQ_s[e // (4 * (8 - R) * 64), (e // ((8 - R) * 64)) % 4, R + (e % ((8 - R) * 64)) // 64, e % 64] = T.cast(0.0, F16)
|
| 190 |
+
T.sync_threads(14, NPROD + NCONS)
|
| 191 |
+
if tx < NPROD:
|
| 192 |
+
T.fence_proxy_async()
|
| 193 |
+
for k in T.serial(ndue_s[0]):
|
| 194 |
+
q = dlist[k]
|
| 195 |
+
gc = k % NCG
|
| 196 |
+
ig = k // NCG
|
| 197 |
+
s = gc * SPG + ig % SPG
|
| 198 |
+
hv = q % HV
|
| 199 |
+
slot = q // HV
|
| 200 |
+
T.mbarrier_wait_parity(consumed[s], ((ig // SPG) & 1) ^ 1)
|
| 201 |
+
T.tma_copy(Sq[slot, hv, :, :], Qs[s, :, :], barrier=loaded[s])
|
| 202 |
+
T.tma_copy(Skv[slot, hv, :], skv_s[s, :], barrier=loaded[s])
|
| 203 |
+
T.tma_copy(Kbuf[slot, hv, :, 0:K // 2], Kb_s[s, 0, :, :], barrier=loaded[s])
|
| 204 |
+
T.tma_copy(Kbuf[slot, hv, :, K // 2:K], Kb_s[s, 1, :, :], barrier=loaded[s])
|
| 205 |
+
T.tma_copy(Ubuf[slot, hv, :, 0:V // 2], Ub_s[s, 0, :, :], barrier=loaded[s])
|
| 206 |
+
T.tma_copy(Ubuf[slot, hv, :, V // 2:V], Ub_s[s, 1, :, :], barrier=loaded[s])
|
| 207 |
+
T.tma_copy(Wbuf[slot, hv, :], Wb_s[s, 0:L], barrier=loaded[s])
|
| 208 |
+
for cb in T.unroll(4):
|
| 209 |
+
T.tma_copy(UQ[slot, hv, :, cb * 64:(cb + 1) * 64], UQ_s[s, cb, 0:R, :], barrier=loaded[s])
|
| 210 |
+
if KDA:
|
| 211 |
+
T.tma_copy(Gbuf[slot, hv, :, 0:K // 2], Kbl_s[s, 0, :, :], barrier=loaded[s])
|
| 212 |
+
T.tma_copy(Gbuf[slot, hv, :, K // 2:K], Kbl_s[s, 1, :, :], barrier=loaded[s])
|
| 213 |
+
T.tma_copy(Pbuf[slot, hv, :], pb_s[s, :], barrier=loaded[s])
|
| 214 |
+
T.mbarrier_arrive(loaded[s])
|
| 215 |
+
else:
|
| 216 |
+
g = (tx - NPROD) // 128
|
| 217 |
+
t = (tx - NPROD) % 128
|
| 218 |
+
w = t // 32
|
| 219 |
+
lane = t % 32
|
| 220 |
+
q4 = lane % 4
|
| 221 |
+
r0 = lane // 4
|
| 222 |
+
bar = 8 + g
|
| 223 |
+
qw = T.alloc_local((4,), I32)
|
| 224 |
+
svr_l = T.alloc_local((4,), F32)
|
| 225 |
+
rmax = T.alloc_local((4,), F32)
|
| 226 |
+
afrag = T.alloc_local((32 if not KDA else 16,), BF16)
|
| 227 |
+
araw = T.alloc_local((8,), BF16)
|
| 228 |
+
wv = T.alloc_local((4,), F32)
|
| 229 |
+
bfrag = T.alloc_local((32 if KDA else 16,), BF16) # 2 x (ring-buffer B tile, KDA: hi + lo) -- alternating per unrolled step
|
| 230 |
+
afrag2 = T.alloc_local((8,), F16) # rank-R A fragments (m16n8k8) per m-tile: old Q^T (residual)
|
| 231 |
+
afrag3 = T.alloc_local((8,), F16) # rank-R A fragments of the new factors (residual)
|
| 232 |
+
cfrag = T.alloc_local((64,), F32) # half of B / E in fragment layout: index (ntl * 4 + (mt * 2 + r)) * 2 + c1, ntl = local n-tile 0..7
|
| 233 |
+
efrag = T.alloc_local((8,), F16) # ldmatrix.x4 result: B values of (ntl, top), (ntl, bottom), (ntl+1, top), (ntl+1, bottom)
|
| 234 |
+
colp = T.alloc_local((32,), F32) # column partials of |E| (16 n-tiles x 2 columns of this lane)
|
| 235 |
+
skl = T.alloc_local((16,), F32) # this lane's 16 column scales of the current half (dequant)
|
| 236 |
+
ah = T.alloc_local((32,), F16) # m16n8k16 A fragments (ldmatrix.x4 from the fp16 St_s): 2 k-parities x 2 m-tiles
|
| 237 |
+
bh2 = T.alloc_local((8,), F16) # B fragments (Q or P column pairs, fp16, ldmatrix.x2.trans): 2 k-parities
|
| 238 |
+
ao = T.alloc_local((16,), F16) # A fragments of the old factor (rows 0..7 of a 16-row m-tile; rows 8..15 zero): 2 k-parities
|
| 239 |
+
bfr = T.alloc_local((8,), F16) # 2 x rank-R B fragment (residual)
|
| 240 |
+
bhi = T.alloc_local((4,), I32) # |E| B fragments (sign bits cleared) of one n-tile, 2 k-steps
|
| 241 |
+
aone = T.alloc_local((8,), F16) # A fragment of ones (column sums on the tensor cores)
|
| 242 |
+
c32 = T.alloc_local((16,), F32) # 2 m-tiles x 4, two accumulator chains (even/odd k-steps)
|
| 243 |
+
mc = T.alloc_local((4,), F32) # R x R correction matrix accumulator (M = Q_old^T Q, M2 = U_old^T P), full in every warp
|
| 244 |
+
mm = T.alloc_local((8,), F32) # M[a][2 q4 + i] for a = 0..3 (shuffled from lanes 4 a + q4)
|
| 245 |
+
uo = T.alloc_local((16,), F32) # old factor entries U_old[a][c] / Q_old[a][v] of this lane's 4 rows
|
| 246 |
+
pr = T.alloc_local((4,), F32) # this thread's row of Q
|
| 247 |
+
gg = T.alloc_local((10,), F32) # Gram entries (0,0) (1,0) (1,1) (2,0) (2,1) (2,2) (3,0) (3,1) (3,2) (3,3)
|
| 248 |
+
ll = T.alloc_local((10,), F32) # Cholesky factor, same packing
|
| 249 |
+
uh = T.alloc_local((4,), F16)
|
| 250 |
+
qh = T.alloc_local((4,), F16)
|
| 251 |
+
el = T.alloc_local((L,), F32) # KDA: this column's per-entry decay factors
|
| 252 |
+
pcl = T.alloc_local((16 if KEX else 1,), F32) # KEX: pc of this lane's residual columns
|
| 253 |
+
emx = T.alloc_local((1,), F32) # KEX: block max of |E|, then the power-of-two scale
|
| 254 |
+
esc = T.alloc_local((2,), F32) # KEX: per-half inverse E scale of this warp's rows
|
| 255 |
+
dcur = T.alloc_local((1,), F32)
|
| 256 |
+
eh = T.alloc_local((32,), F16) # quantisation: 2 x 2 x 8 halfwords of E (alternating per row pass)
|
| 257 |
+
ph = T.alloc_local((8,), F16) # fp16 pairs for stmatrix (vectorised cast -> one F2FP.PACK per pair)
|
| 258 |
+
ex = T.alloc_local((16,), F32) # quantisation: this lane's 16 scaled residual values of the row
|
| 259 |
+
rk = T.alloc_local((16,), F32) # quantisation: this lane's 16 reciprocal column scales
|
| 260 |
+
tk = T.alloc_local((10,), "int64")
|
| 261 |
+
tk2 = T.alloc_local((6,), "int64")
|
| 262 |
+
tacc = T.alloc_local((10,), F32)
|
| 263 |
+
for i in T.unroll(10):
|
| 264 |
+
tacc[i] = 0.0
|
| 265 |
+
if PROF:
|
| 266 |
+
tacc[7] = T.cast(tc[1] - tc[0], F32) # compaction: loads + ballots
|
| 267 |
+
tacc[9] = T.cast(tc[2] - tc[1], F32) # compaction: scan + rank pass
|
| 268 |
+
for i in T.unroll(8):
|
| 269 |
+
aone[i] = T.cast(1.0, F16)
|
| 270 |
+
for i in T.unroll(2): # the old-factor A fragments: register pairs 1 and 3 (m-rows 8..15) stay zero
|
| 271 |
+
ao[2 + i] = T.cast(0.0, F16)
|
| 272 |
+
ao[6 + i] = T.cast(0.0, F16)
|
| 273 |
+
ao[10 + i] = T.cast(0.0, F16)
|
| 274 |
+
ao[14 + i] = T.cast(0.0, F16)
|
| 275 |
+
for r in T.unroll(4): # the fp16 Q tile's padding columns R..7 stay zero (this thread's row)
|
| 276 |
+
St_s[g, t, K + 4 + r] = T.cast(0.0, F16)
|
| 277 |
+
for r in T.unroll(4 - R):
|
| 278 |
+
St_s[g, t, K + R + r] = T.cast(0.0, F16)
|
| 279 |
+
for it0 in T.serial(T.ceildiv(ndue_s[0] - g, NCG)):
|
| 280 |
+
k = g + it0 * NCG
|
| 281 |
+
q = dlist[k]
|
| 282 |
+
hv = q % HV
|
| 283 |
+
s = g * SPG + it0 % SPG
|
| 284 |
+
if PROF:
|
| 285 |
+
tk[0] = T.call_extern("int64", "clock64")
|
| 286 |
+
T.mbarrier_wait_parity(loaded[s], (it0 // SPG) & 1)
|
| 287 |
+
if PROF:
|
| 288 |
+
tk[1] = T.call_extern("int64", "clock64")
|
| 289 |
+
slot = q // HV
|
| 290 |
+
if KDA:
|
| 291 |
+
# pre-pass (thread per column c = t): pc = exp(G); decayed keys w_j k_j D_j as bf16 hi (in place) + lo (over the factors);
|
| 292 |
+
# U^T pre-multiplied by pc (the checkpoint's column decay)
|
| 293 |
+
pcc = T.exp(pb_s[s, t])
|
| 294 |
+
pc_s[g, t] = pcc
|
| 295 |
+
for jj in T.unroll(L):
|
| 296 |
+
el[jj] = T.cast(T.reinterpret(F16, Kbl_s[s, t // (K // 2), jj, t % (K // 2)]), F32)
|
| 297 |
+
T.sync_threads(bar, 128) # every lane holds its factors before the lo tile overwrites them
|
| 298 |
+
dcur[0] = 1.0
|
| 299 |
+
for jj in T.unroll(L): # backward: D_{L-1} = 1, D_j = D_{j+1} e_{j+1}
|
| 300 |
+
j = L - 1 - jj
|
| 301 |
+
kd = T.cast(Kb_s[s, t // (K // 2), j, t % (K // 2)], F32) * (Wb_s[s, j] * dcur[0])
|
| 302 |
+
khi = T.cast(kd, BF16)
|
| 303 |
+
Kb_s[s, t // (K // 2), j, t % (K // 2)] = khi
|
| 304 |
+
Kbl_s[s, t // (K // 2), j, t % (K // 2)] = T.cast(kd - T.cast(khi, F32), BF16)
|
| 305 |
+
dcur[0] = dcur[0] * el[j]
|
| 306 |
+
for r in T.unroll(R): # pc U^T in place (fp16: 2^-11 of the rank-R term, measured irrelevant next to the int8 residual)
|
| 307 |
+
if KEX:
|
| 308 |
+
UQ_s[s, t // 64, R + r, t % 64] = T.cast(T.cast(UQ_s[s, t // 64, r, t % 64], F32) * pcc, F16)
|
| 309 |
+
else:
|
| 310 |
+
UQ_s[s, t // 64, r, t % 64] = T.cast(T.cast(UQ_s[s, t // 64, r, t % 64], F32) * pcc, F16)
|
| 311 |
+
T.sync_threads(bar, 128)
|
| 312 |
+
for i in T.unroll(4):
|
| 313 |
+
svr_l[i] = skv_s[s, K + w * 32 + (i // 2) * 16 + (i % 2) * 8 + lane // 4] * (1.0 / QMAX)
|
| 314 |
+
else:
|
| 315 |
+
pn = T.max(Pbuf[slot, hv, 0], PNMIN) # floor: a fully decayed head has a denormal product (2e-41 seen on 9B layer 11) and 1/pn = inf
|
| 316 |
+
rpn = 1.0 / pn # poisoned the residual (Sk = inf -> NaN outputs); the floor changes E by <= 1e-20 |Q_old U_old^T|
|
| 317 |
+
if KDA:
|
| 318 |
+
pn = 1.0
|
| 319 |
+
if not KDA:
|
| 320 |
+
for i in T.unroll(4):
|
| 321 |
+
svr_l[i] = skv_s[s, K + w * 32 + (i // 2) * 16 + (i % 2) * 8 + lane // 4] * (pn / QMAX)
|
| 322 |
+
# (1) A fragments of the ring buffer u_j (GDN: w_j-scaled, bf16 hi + lo; KDA: exact bf16)
|
| 323 |
+
if KDA:
|
| 324 |
+
for mt in T.unroll(2):
|
| 325 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(Ub_s[s, (w * 32 + mt * 16) // (V // 2), (lane % 8) + 8 * (lane // 16), (w * 32 + mt * 16) % (V // 2) + 8 * ((lane // 8) % 2)], "r", extent=8), T.access_ptr(afrag[mt * 8], "w", extent=8))
|
| 326 |
+
else:
|
| 327 |
+
for i in T.unroll(4):
|
| 328 |
+
wv[i] = Wb_s[s, 2 * q4 + (i % 2) + 8 * (i // 2)]
|
| 329 |
+
for mt in T.unroll(2):
|
| 330 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(Ub_s[s, (w * 32 + mt * 16) // (V // 2), (lane % 8) + 8 * (lane // 16), (w * 32 + mt * 16) % (V // 2) + 8 * ((lane // 8) % 2)], "r", extent=8), T.access_ptr(araw[0], "w", extent=8))
|
| 331 |
+
for i in T.unroll(8):
|
| 332 |
+
wu = wv[(i % 2) + 2 * (i // 4)] * T.cast(araw[i], F32)
|
| 333 |
+
afrag[mt * 16 + i] = T.cast(wu, BF16)
|
| 334 |
+
afrag[mt * 16 + 8 + i] = T.cast(wu - T.cast(afrag[mt * 16 + i], F32), BF16)
|
| 335 |
+
# (2) two 64-column halves: B = ring buffer (mma) + pn * deq(S0), out to St_s (fp16, stmatrix); the old rank-R part stays algebraic
|
| 336 |
+
for h in T.unroll(2):
|
| 337 |
+
# dequantise first (independent FFMA chains, no accumulator dependency), then the ring-buffer mma accumulates on top
|
| 338 |
+
for ntl in T.unroll(8):
|
| 339 |
+
for c1 in T.vectorized(2):
|
| 340 |
+
if KDA:
|
| 341 |
+
skl[ntl * 2 + c1] = skv_s[s, (h * 8 + ntl) * 8 + q4 * 2 + c1] * pc_s[g, (h * 8 + ntl) * 8 + q4 * 2 + c1]
|
| 342 |
+
else:
|
| 343 |
+
skl[ntl * 2 + c1] = skv_s[s, (h * 8 + ntl) * 8 + q4 * 2 + c1]
|
| 344 |
+
for rr in (T.unroll(0) if "nodeq" in ABL else T.unroll(4)):
|
| 345 |
+
v0 = w * 32 + (rr // 2) * 16 + (rr % 2) * 8 + r0
|
| 346 |
+
for jcl in T.unroll(4): # 16-column chunk = n-tiles 2jc, 2jc+1; lane q4 needs word q4 // 2 of each n-tile
|
| 347 |
+
jc = h * 4 + jcl
|
| 348 |
+
for nn in T.unroll(2):
|
| 349 |
+
qw[nn] = Qs[s, v0, jc * 4 + nn * 2 + q4 // 2]
|
| 350 |
+
for nn in T.unroll(2):
|
| 351 |
+
ntl = jcl * 2 + nn
|
| 352 |
+
pkw = qw[nn] ^ T.int32(-2139062144)
|
| 353 |
+
for c1 in T.unroll(2): # the magic-number subtraction must stay a separate exact fp32 op: folding -K*skl into an FFMA
|
| 354 |
+
x = T.reinterpret(F32, T.call_extern(I32, "__byte_perm", pkw, T.int32(0x4B000000), T.int32(0x7650) + (q4 % 2) * 2 + c1)) - 8388736.0 # costs ulp(2^23 skl) = half a code
|
| 355 |
+
cfrag[(ntl * 4 + rr) * 2 + c1] = x * svr_l[rr] * skl[ntl * 2 + c1]
|
| 356 |
+
# stmatrix.x4: matrices (ntl, rows 0-7), (ntl, rows 8-15), (ntl+1, rows 0-7), (ntl+1, rows 8-15) of m-tile mt
|
| 357 |
+
for npl in T.unroll(4):
|
| 358 |
+
n0 = (h * 4 + npl) * 16
|
| 359 |
+
bo = (npl % 2) * (16 if KDA else 8)
|
| 360 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(Kb_s[s, n0 // (K // 2), (lane % 8) + 8 * ((lane // 8) % 2), n0 % (K // 2) + 8 * (lane // 16)], "r", extent=8), T.access_ptr(bfrag[bo], "w", extent=8))
|
| 361 |
+
if KDA:
|
| 362 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(Kbl_s[s, n0 // (K // 2), (lane % 8) + 8 * ((lane // 8) % 2), n0 % (K // 2) + 8 * (lane // 16)], "r", extent=8), T.access_ptr(bfrag[bo + 8], "w", extent=8))
|
| 363 |
+
for mt in T.unroll(2):
|
| 364 |
+
for nn in T.unroll(2):
|
| 365 |
+
if KDA:
|
| 366 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "bf16", "bf16", "fp32", afrag.data, mt * 8, bfrag.data, bo + nn * 4, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 367 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "bf16", "bf16", "fp32", afrag.data, mt * 8, bfrag.data, bo + 8 + nn * 4, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 368 |
+
else:
|
| 369 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", MMT, MMT, "fp32", afrag.data, mt * 16, bfrag.data, bo + nn * 4, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 370 |
+
if not DROPLO:
|
| 371 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", MMT, MMT, "fp32", afrag.data, mt * 16 + 8, bfrag.data, bo + nn * 4, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 372 |
+
for mt in (T.unroll(0) if "nostb" in ABL else T.unroll(2)):
|
| 373 |
+
for npl in T.unroll(4):
|
| 374 |
+
for jj in T.unroll(4): # 4 fp16 pairs: (ntl, rows 0-7), (ntl, rows 8-15), (ntl+1, ...) -- one F2FP.PACK each
|
| 375 |
+
for c1 in T.vectorized(2):
|
| 376 |
+
ph[jj * 2 + c1] = T.cast(cfrag[((npl * 2 + jj // 2) * 4 + mt * 2 + jj % 2) * 2 + c1], F16)
|
| 377 |
+
T.call_extern("handle", "tl::ptx_stmatrix_m8n8_x4",
|
| 378 |
+
T.access_ptr(St_s[g, w * 32 + mt * 16 + 8 * ((lane // 8) % 2) + lane % 8, (h * 8 + npl * 2 + lane // 16) * 8], "w", extent=8),
|
| 379 |
+
T.reinterpret(I32, ph[0:2]), T.reinterpret(I32, ph[2:4]), T.reinterpret(I32, ph[4:6]), T.reinterpret(I32, ph[6:8]))
|
| 380 |
+
# the iteration's start Q0 (fp16 tile in the St_s pad columns; this thread's row) -- before the barrier that publishes B
|
| 381 |
+
for r in T.unroll(R):
|
| 382 |
+
St_s[g, t, K + r] = T.cast(Q0[t, r], F16)
|
| 383 |
+
T.sync_threads(bar, 128)
|
| 384 |
+
if PROF:
|
| 385 |
+
tk[2] = T.call_extern("int64", "clock64")
|
| 386 |
+
# ================= subspace iteration on B (fp16 mma) with the algebraic rank-R corrections =================
|
| 387 |
+
for itr in T.serial(ITERS + 1):
|
| 388 |
+
if PROFIT:
|
| 389 |
+
tk2[0] = T.call_extern("int64", "clock64")
|
| 390 |
+
# ---- P = B^T Q (K x R): A[m=c][k=v] = St_s[v][c] via ldmatrix.x4.trans; B[k=v][n=r] = Q16[v][r] via ldmatrix.x2.trans;
|
| 391 |
+
# alongside M = Q_old^T Q (R x R): A[m=r][k=v] = Q_old^T (rows 8..15 zero), same B fragments ----
|
| 392 |
+
for i in T.unroll(16):
|
| 393 |
+
c32[i] = 0.0
|
| 394 |
+
for i in T.unroll(4):
|
| 395 |
+
mc[i] = 0.0
|
| 396 |
+
for k0 in T.unroll(V // 16):
|
| 397 |
+
kp = k0 % 2 # alternating fragment registers: the next step's ldmatrix can overlap this step's mma
|
| 398 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(St_s[g, k0 * 16 + 8 * ((lane // 8) % 2) + lane % 8, K], "r", extent=4), T.access_ptr(bh2[kp * 4], "w", extent=4))
|
| 399 |
+
for mt in T.unroll(2):
|
| 400 |
+
m0 = w * 32 + mt * 16
|
| 401 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(St_s[g, k0 * 16 + 8 * (lane // 16) + lane % 8, m0 + 8 * ((lane // 8) % 2)], "r", extent=8), T.access_ptr(ah[(kp * 2 + mt) * 8], "w", extent=8))
|
| 402 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", ah.data, (kp * 2 + mt) * 8, bh2.data, kp * 4, c32.data, (k0 % 2) * 8 + mt * 4, T.bool(False))
|
| 403 |
+
T.ptx_ldmatrix(T.bool(False), 1, T.access_ptr(UQ_s[s, (K + k0 * 16) // 64, lane % 8, (K + k0 * 16) % 64], "r", extent=2), T.access_ptr(ao[kp * 8], "w", extent=2))
|
| 404 |
+
T.ptx_ldmatrix(T.bool(False), 1, T.access_ptr(UQ_s[s, (K + k0 * 16 + 8) // 64, lane % 8, (K + k0 * 16 + 8) % 64], "r", extent=2), T.access_ptr(ao[kp * 8 + 4], "w", extent=2))
|
| 405 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", ao.data, kp * 8, bh2.data, kp * 4, mc.data, 0, T.bool(False))
|
| 406 |
+
for i in T.unroll(8):
|
| 407 |
+
c32[i] += c32[8 + i]
|
| 408 |
+
if PROFIT:
|
| 409 |
+
tk2[1] = T.call_extern("int64", "clock64")
|
| 410 |
+
# ---- P += pn U_old M in the fragments: rows c = m0 + r0 (+8), columns n = 2 q4 + i; M[a][n] sits in lane 4 a + q4 ----
|
| 411 |
+
for a in T.unroll(4):
|
| 412 |
+
mm[a * 2] = T.shfl_sync(mc[0], a * 4 + q4)
|
| 413 |
+
mm[a * 2 + 1] = T.shfl_sync(mc[1], a * 4 + q4)
|
| 414 |
+
for mt in T.unroll(2):
|
| 415 |
+
for hh in T.unroll(2):
|
| 416 |
+
cc = w * 32 + mt * 16 + hh * 8 + r0
|
| 417 |
+
for a in T.unroll(4):
|
| 418 |
+
uo[(mt * 2 + hh) * 4 + a] = T.if_then_else(a < R, T.cast(UQ_s[s, cc // 64, (R + a) if KEX else a, cc % 64], F32), 0.0)
|
| 419 |
+
for i in T.unroll(2):
|
| 420 |
+
c32[mt * 4 + hh * 2 + i] += pn * (uo[(mt * 2 + hh) * 4] * mm[i] + uo[(mt * 2 + hh) * 4 + 1] * mm[2 + i] + uo[(mt * 2 + hh) * 4 + 2] * mm[4 + i] + uo[(mt * 2 + hh) * 4 + 3] * mm[6 + i])
|
| 421 |
+
# ---- the fp16 P tile P16[c][r] (columns >= R zero: lanes q4 >= R/2 write zeros) via stmatrix.x2 (rows 0-7, rows 8-15 of each m-tile) ----
|
| 422 |
+
for mt in T.unroll(2):
|
| 423 |
+
for c1 in T.vectorized(2):
|
| 424 |
+
ph[c1] = T.cast(T.if_then_else(2 * q4 + c1 < R, c32[mt * 4 + c1], 0.0), F16)
|
| 425 |
+
ph[2 + c1] = T.cast(T.if_then_else(2 * q4 + c1 < R, c32[mt * 4 + 2 + c1], 0.0), F16)
|
| 426 |
+
T.call_extern("handle", "tl::ptx_stmatrix_m8n8_x2",
|
| 427 |
+
T.access_ptr(UQn1[g, P16OFF + (w * 32 + mt * 16 + 8 * ((lane // 8) % 2) + lane % 8) * 8], "w", extent=8),
|
| 428 |
+
T.reinterpret(I32, ph[0:2]), T.reinterpret(I32, ph[2:4]))
|
| 429 |
+
T.sync_threads(bar, 128)
|
| 430 |
+
if PROFIT:
|
| 431 |
+
tk2[2] = T.call_extern("int64", "clock64")
|
| 432 |
+
tacc[0] += T.cast(tk2[1] - tk2[0], F32)
|
| 433 |
+
tacc[1] += T.cast(tk2[2] - tk2[1], F32)
|
| 434 |
+
if itr < ITERS:
|
| 435 |
+
# ---- Q = B P (V x R): A[m=v][k=c] = St_s[v][c] via ldmatrix.x4; B[k=c][n=r] = P16[c][r] via ldmatrix.x2.trans; alongside M2 = U_old^T P ----
|
| 436 |
+
for i in T.unroll(16):
|
| 437 |
+
c32[i] = 0.0
|
| 438 |
+
for i in T.unroll(4):
|
| 439 |
+
mc[i] = 0.0
|
| 440 |
+
for k0 in T.unroll(K // 16):
|
| 441 |
+
kp = k0 % 2
|
| 442 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(UQn1[g, P16OFF + (k0 * 16 + 8 * ((lane // 8) % 2) + lane % 8) * 8], "r", extent=4), T.access_ptr(bh2[kp * 4], "w", extent=4))
|
| 443 |
+
for mt in T.unroll(2):
|
| 444 |
+
m0 = w * 32 + mt * 16
|
| 445 |
+
T.ptx_ldmatrix(T.bool(False), 4, T.access_ptr(St_s[g, m0 + 8 * ((lane // 8) % 2) + lane % 8, k0 * 16 + 8 * (lane // 16)], "r", extent=8), T.access_ptr(ah[(kp * 2 + mt) * 8], "w", extent=8))
|
| 446 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", ah.data, (kp * 2 + mt) * 8, bh2.data, kp * 4, c32.data, (k0 % 2) * 8 + mt * 4, T.bool(False))
|
| 447 |
+
T.ptx_ldmatrix(T.bool(False), 1, T.access_ptr(UQ_s[s, (k0 * 16) // 64, lane % 8, (k0 * 16) % 64], "r", extent=2), T.access_ptr(ao[kp * 8], "w", extent=2))
|
| 448 |
+
T.ptx_ldmatrix(T.bool(False), 1, T.access_ptr(UQ_s[s, (k0 * 16 + 8) // 64, lane % 8, (k0 * 16 + 8) % 64], "r", extent=2), T.access_ptr(ao[kp * 8 + 4], "w", extent=2))
|
| 449 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", ao.data, kp * 8, bh2.data, kp * 4, mc.data, 0, T.bool(False))
|
| 450 |
+
for i in T.unroll(8):
|
| 451 |
+
c32[i] += c32[8 + i]
|
| 452 |
+
# ---- Q += pn Q_old M2 in the fragments, then the fp32 rows to PQ_s plane 0 for the CholeskyQR ----
|
| 453 |
+
for a in T.unroll(4):
|
| 454 |
+
mm[a * 2] = T.shfl_sync(mc[0], ((R + a) if KEX else a) * 4 + q4)
|
| 455 |
+
mm[a * 2 + 1] = T.shfl_sync(mc[1], ((R + a) if KEX else a) * 4 + q4)
|
| 456 |
+
for mt in T.unroll(2):
|
| 457 |
+
for hh in T.unroll(2):
|
| 458 |
+
vv = w * 32 + mt * 16 + hh * 8 + r0
|
| 459 |
+
for a in T.unroll(4):
|
| 460 |
+
uo[(mt * 2 + hh) * 4 + a] = T.if_then_else(a < R, T.cast(UQ_s[s, (K + vv) // 64, a, (K + vv) % 64], F32), 0.0)
|
| 461 |
+
for i in T.unroll(2):
|
| 462 |
+
c32[mt * 4 + hh * 2 + i] += pn * (uo[(mt * 2 + hh) * 4] * mm[i] + uo[(mt * 2 + hh) * 4 + 1] * mm[2 + i] + uo[(mt * 2 + hh) * 4 + 2] * mm[4 + i] + uo[(mt * 2 + hh) * 4 + 3] * mm[6 + i])
|
| 463 |
+
if q4 * 2 < R:
|
| 464 |
+
for mt in T.unroll(2):
|
| 465 |
+
PQ_s[g, 0, w * 32 + mt * 16 + r0, 2 * q4] = c32[mt * 4]
|
| 466 |
+
PQ_s[g, 0, w * 32 + mt * 16 + r0, 2 * q4 + 1] = c32[mt * 4 + 1]
|
| 467 |
+
PQ_s[g, 0, w * 32 + mt * 16 + r0 + 8, 2 * q4] = c32[mt * 4 + 2]
|
| 468 |
+
PQ_s[g, 0, w * 32 + mt * 16 + r0 + 8, 2 * q4 + 1] = c32[mt * 4 + 3]
|
| 469 |
+
T.sync_threads(bar, 128)
|
| 470 |
+
if PROFIT:
|
| 471 |
+
tk2[3] = T.call_extern("int64", "clock64")
|
| 472 |
+
tacc[2] += T.cast(tk2[3] - tk2[2], F32)
|
| 473 |
+
# ---- CholeskyQR2 of Q (V rows = 128 threads), relative pivot floor for rank-deficient heads. Pass 1 in fp32 (shuffle tree);
|
| 474 |
+
# pass 2's Gram on the tensor cores in fp16 (8 mma; the factors are stored in fp16 anyway and the residual uses the same
|
| 475 |
+
# fp16 factors, so a 2^-11 non-orthonormality costs nothing). A 3xTF32 Gram for pass 1 was slower (48 dependent mma). ----
|
| 476 |
+
for r in T.unroll(4):
|
| 477 |
+
pr[r] = T.if_then_else(r < R, PQ_s[g, 0, t, r], 0.0)
|
| 478 |
+
for cq in range(2):
|
| 479 |
+
if cq == 0 or not GRAM16: # pass 1 (kappa up to 1e3): fp32 Gram by the warp-shuffle tree + smem partials. GRAM16=False: pass 2 too --
|
| 480 |
+
# after a floored pass-1 pivot (rank-deficient head, e.g. svals 4.8 / 0.2 / 8e-3 / 1e-3) the 4th column has norm 1e-3..1e-5,
|
| 481 |
+
# its fp16 Gram entry is subnormal/zero, rsqrt blows the column up by 1e3..1e15 and U_4 = B^T q_4 with it
|
| 482 |
+
for r in T.unroll(4):
|
| 483 |
+
for c in T.unroll(r + 1):
|
| 484 |
+
gg[r * (r + 1) // 2 + c] = pr[r] * pr[c]
|
| 485 |
+
for off in (T.unroll(0) if "nogram" in ABL else T.unroll(5)):
|
| 486 |
+
for i in T.unroll(10):
|
| 487 |
+
gg[i] += T.shfl_xor(gg[i], 16 >> off)
|
| 488 |
+
if lane == 0:
|
| 489 |
+
for i in T.unroll(10):
|
| 490 |
+
cpart[g, 4, w * 16 + i] = gg[i] # per-warp Gram partials (cpart row 4: free during the iteration)
|
| 491 |
+
T.sync_threads(bar, 128)
|
| 492 |
+
for i in T.unroll(10):
|
| 493 |
+
gg[i] = cpart[g, 4, i] + cpart[g, 4, 16 + i] + cpart[g, 4, 32 + i] + cpart[g, 4, 48 + i]
|
| 494 |
+
else: # pass 2 (Q nearly orthonormal): Gram on the tensor cores from the fp16 Q tile,
|
| 495 |
+
for i in T.unroll(4): # A = Q^T (rows R.. zero) and B = Q are the same ldmatrix.x2.trans fragment
|
| 496 |
+
mc[i] = 0.0
|
| 497 |
+
for k0 in T.unroll(V // 16):
|
| 498 |
+
kp = k0 % 2
|
| 499 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(St_s[g, k0 * 16 + 8 * ((lane // 8) % 2) + lane % 8, K], "r", extent=4), T.access_ptr(bh2[kp * 4], "w", extent=4))
|
| 500 |
+
for i in T.unroll(2):
|
| 501 |
+
ao[kp * 8 + i] = bh2[kp * 4 + i]
|
| 502 |
+
ao[kp * 8 + 4 + i] = bh2[kp * 4 + 2 + i]
|
| 503 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", ao.data, kp * 8, bh2.data, kp * 4, mc.data, 0, T.bool(False))
|
| 504 |
+
gg[0] = T.shfl_sync(mc[0], 0) # G[a][c] sits in lane 4 a + c // 2, register c % 2
|
| 505 |
+
gg[1] = T.shfl_sync(mc[0], 4)
|
| 506 |
+
gg[2] = T.shfl_sync(mc[1], 4)
|
| 507 |
+
gg[3] = T.shfl_sync(mc[0], 8)
|
| 508 |
+
gg[4] = T.shfl_sync(mc[1], 8)
|
| 509 |
+
gg[5] = T.shfl_sync(mc[0], 9)
|
| 510 |
+
gg[6] = T.shfl_sync(mc[0], 12)
|
| 511 |
+
gg[7] = T.shfl_sync(mc[1], 12)
|
| 512 |
+
gg[8] = T.shfl_sync(mc[0], 13)
|
| 513 |
+
gg[9] = T.shfl_sync(mc[1], 13)
|
| 514 |
+
ll[0] = T.rsqrt(T.max(gg[0], 1e-30)) # reciprocals of the diagonal (1/L_jj)
|
| 515 |
+
ll[1] = gg[1] * ll[0]
|
| 516 |
+
ll[2] = T.rsqrt(T.max(T.max(gg[2] - ll[1] * ll[1], 1e-6 * gg[2]), 1e-30))
|
| 517 |
+
ll[3] = gg[3] * ll[0]
|
| 518 |
+
ll[4] = (gg[4] - ll[3] * ll[1]) * ll[2]
|
| 519 |
+
ll[5] = T.rsqrt(T.max(T.max(gg[5] - ll[3] * ll[3] - ll[4] * ll[4], 1e-6 * gg[5]), 1e-30))
|
| 520 |
+
ll[6] = gg[6] * ll[0]
|
| 521 |
+
ll[7] = (gg[7] - ll[6] * ll[1]) * ll[2]
|
| 522 |
+
ll[8] = (gg[8] - ll[6] * ll[3] - ll[7] * ll[4]) * ll[5]
|
| 523 |
+
ll[9] = T.rsqrt(T.max(T.max(gg[9] - ll[6] * ll[6] - ll[7] * ll[7] - ll[8] * ll[8], 1e-6 * gg[9]), 1e-30))
|
| 524 |
+
pr[0] = pr[0] * ll[0]
|
| 525 |
+
pr[1] = (pr[1] - pr[0] * ll[1]) * ll[2]
|
| 526 |
+
pr[2] = (pr[2] - pr[0] * ll[3] - pr[1] * ll[4]) * ll[5]
|
| 527 |
+
pr[3] = (pr[3] - pr[0] * ll[6] - pr[1] * ll[7] - pr[2] * ll[8]) * ll[9]
|
| 528 |
+
for r in T.unroll(R):
|
| 529 |
+
St_s[g, t, K + r] = T.cast(pr[r], F16) # the fp16 Q tile (pass 2's Gram operand, then the next product)
|
| 530 |
+
T.sync_threads(bar, 128)
|
| 531 |
+
if PROFIT:
|
| 532 |
+
tk2[4] = T.call_extern("int64", "clock64")
|
| 533 |
+
tacc[3] += T.cast(tk2[4] - tk2[3], F32)
|
| 534 |
+
if PROF:
|
| 535 |
+
tk[3] = T.call_extern("int64", "clock64")
|
| 536 |
+
# ---- the fp16 factors (U^T[r][c] = P16[c][r], Q^T[r][v] = Q16[v][r]) to global and, after a barrier, -U^T over the P/Q planes for the residual mma ----
|
| 537 |
+
for r in T.unroll(R):
|
| 538 |
+
uh[r] = UQn1[g, P16OFF + t * 8 + r]
|
| 539 |
+
qh[r] = St_s[g, t, K + r]
|
| 540 |
+
UQ[slot, hv, r, t] = uh[r]
|
| 541 |
+
UQ[slot, hv, r, K + t] = qh[r]
|
| 542 |
+
T.sync_threads(bar, 128)
|
| 543 |
+
for r in T.unroll(R):
|
| 544 |
+
UQn_s[g, r, t] = -uh[r] # -U^T: the residual mma accumulates the subtraction
|
| 545 |
+
for r in T.unroll(8 - R):
|
| 546 |
+
UQn_s[g, R + r, t] = T.cast(0.0, F16)
|
| 547 |
+
T.sync_threads(bar, 128)
|
| 548 |
+
# ---- residual E = fp16(B) + pn Q_old U_old^T - Q U^T in two halves (fp16 mma, fp32 accumulate), |E| column partials, E over B in St_s ----
|
| 549 |
+
for mt in T.unroll(2): # A[m=v][k=r] = Q_old^T[r][v]: x2.trans -> (m 0-7), (m 8-15) of k-rows 0-7
|
| 550 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(UQ_s[s, (K + w * 32 + mt * 16 + 8 * ((lane // 8) % 2)) // 64, lane % 8, (K + w * 32 + mt * 16 + 8 * ((lane // 8) % 2)) % 64], "r", extent=4), T.access_ptr(afrag2[mt * 4], "w", extent=4))
|
| 551 |
+
# A[m=v][k=r] = Q16[v][r] (row-major [m][k], k 0-7): x2 (non-trans) -> rows 0-7, rows 8-15
|
| 552 |
+
T.ptx_ldmatrix(T.bool(False), 2, T.access_ptr(St_s[g, w * 32 + mt * 16 + 8 * ((lane // 8) % 2) + lane % 8, K], "r", extent=4), T.access_ptr(afrag3[mt * 4], "w", extent=4))
|
| 553 |
+
if KEX: # the ring buffer's A fragments again (the rebuild's registers are long dead)
|
| 554 |
+
for i in T.unroll(4):
|
| 555 |
+
svr_l[i] = skv_s[s, K + w * 32 + (i // 2) * 16 + (i % 2) * 8 + lane // 4] * (1.0 / QMAX)
|
| 556 |
+
for mt in T.unroll(2):
|
| 557 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(Ub_s[s, (w * 32 + mt * 16) // (V // 2), (lane % 8) + 8 * (lane // 16), (w * 32 + mt * 16) % (V // 2) + 8 * ((lane // 8) % 2)], "r", extent=8), T.access_ptr(afrag[mt * 8], "w", extent=8))
|
| 558 |
+
for h in T.unroll(2):
|
| 559 |
+
if KEX:
|
| 560 |
+
# KEX: B is rebuilt here in fp32 from the stage instead of read back from the fp16 St_s (its 2^-11 rounding cost +1 %
|
| 561 |
+
# reconstruction error): E = (deq(S0) + Q_old U_old^T) pc + ring buffer - Q U^T, every term accumulated in fp32
|
| 562 |
+
for ntl in T.unroll(8):
|
| 563 |
+
for c1 in T.vectorized(2):
|
| 564 |
+
skl[ntl * 2 + c1] = skv_s[s, (h * 8 + ntl) * 8 + q4 * 2 + c1]
|
| 565 |
+
for rr in T.unroll(4):
|
| 566 |
+
v0 = w * 32 + (rr // 2) * 16 + (rr % 2) * 8 + r0
|
| 567 |
+
for jcl in T.unroll(4):
|
| 568 |
+
jc = h * 4 + jcl
|
| 569 |
+
for nn in T.unroll(2):
|
| 570 |
+
qw[nn] = Qs[s, v0, jc * 4 + nn * 2 + q4 // 2]
|
| 571 |
+
for nn in T.unroll(2):
|
| 572 |
+
ntl = jcl * 2 + nn
|
| 573 |
+
pkw = qw[nn] ^ T.int32(-2139062144)
|
| 574 |
+
for c1 in T.unroll(2):
|
| 575 |
+
x = T.reinterpret(F32, T.call_extern(I32, "__byte_perm", pkw, T.int32(0x4B000000), T.int32(0x7650) + (q4 % 2) * 2 + c1)) - 8388736.0
|
| 576 |
+
cfrag[(ntl * 4 + rr) * 2 + c1] = x * svr_l[rr] * skl[ntl * 2 + c1]
|
| 577 |
+
# E = pn (B / pn + Q_old U_old^T) - Q U^T: the accumulator starts from B (scaled by 1 / pn on GDN, loaded with ldmatrix.x4 in the
|
| 578 |
+
# fragment layout), so both rank-R mma chains accumulate straight into it and there is no elementwise add afterwards
|
| 579 |
+
for mt in (T.unroll(0) if KEX else T.unroll(2)):
|
| 580 |
+
for npl in T.unroll(4):
|
| 581 |
+
T.ptx_ldmatrix(T.bool(False), 4, T.access_ptr(St_s[g, w * 32 + mt * 16 + 8 * ((lane // 8) % 2) + lane % 8, (h * 8 + npl * 2 + lane // 16) * 8], "r", extent=8), T.access_ptr(efrag[0], "w", extent=8))
|
| 582 |
+
for jj in T.unroll(4):
|
| 583 |
+
for c1 in T.unroll(2):
|
| 584 |
+
if KDA:
|
| 585 |
+
cfrag[((npl * 2 + jj // 2) * 4 + mt * 2 + jj % 2) * 2 + c1] = T.cast(efrag[jj * 2 + c1], F32)
|
| 586 |
+
else:
|
| 587 |
+
cfrag[((npl * 2 + jj // 2) * 4 + mt * 2 + jj % 2) * 2 + c1] = T.cast(efrag[jj * 2 + c1], F32) * rpn
|
| 588 |
+
for npl in T.unroll(4):
|
| 589 |
+
n0 = (h * 4 + npl) * 16
|
| 590 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(UQ_s[s, n0 // 64, lane % 8, n0 % 64 + 8 * ((lane // 8) % 2)], "r", extent=4), T.access_ptr(bfr[(npl % 2) * 4], "w", extent=4))
|
| 591 |
+
for mt in T.unroll(2):
|
| 592 |
+
for nn in T.unroll(2):
|
| 593 |
+
T.ptx_mma("float32", "m16n8k8", "row", "col", "fp16", "fp16", "fp32", afrag2.data, mt * 4, bfr.data, (npl % 2) * 4 + nn * 2, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 594 |
+
if not KDA:
|
| 595 |
+
for i in T.unroll(64):
|
| 596 |
+
cfrag[i] = cfrag[i] * pn
|
| 597 |
+
if KEX:
|
| 598 |
+
for nt in T.unroll(8):
|
| 599 |
+
for c1 in T.unroll(2):
|
| 600 |
+
pcl[nt * 2 + c1] = pc_s[g, h * 64 + nt * 8 + 2 * q4 + c1]
|
| 601 |
+
for mr in T.unroll(4):
|
| 602 |
+
for c1 in T.unroll(2):
|
| 603 |
+
cfrag[(nt * 4 + mr) * 2 + c1] = cfrag[(nt * 4 + mr) * 2 + c1] * pcl[nt * 2 + c1]
|
| 604 |
+
for npl in T.unroll(4): # + the ring buffer (bf16 hi + lo decayed keys, exact bf16 values)
|
| 605 |
+
n0 = (h * 4 + npl) * 16
|
| 606 |
+
bo = (npl % 2) * 16
|
| 607 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(Kb_s[s, n0 // (K // 2), (lane % 8) + 8 * ((lane // 8) % 2), n0 % (K // 2) + 8 * (lane // 16)], "r", extent=8), T.access_ptr(bfrag[bo], "w", extent=8))
|
| 608 |
+
T.ptx_ldmatrix(T.bool(True), 4, T.access_ptr(Kbl_s[s, n0 // (K // 2), (lane % 8) + 8 * ((lane // 8) % 2), n0 % (K // 2) + 8 * (lane // 16)], "r", extent=8), T.access_ptr(bfrag[bo + 8], "w", extent=8))
|
| 609 |
+
for mt in T.unroll(2):
|
| 610 |
+
for nn in T.unroll(2):
|
| 611 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "bf16", "bf16", "fp32", afrag.data, mt * 8, bfrag.data, bo + nn * 4, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 612 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "bf16", "bf16", "fp32", afrag.data, mt * 8, bfrag.data, bo + 8 + nn * 4, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 613 |
+
for npl in T.unroll(4):
|
| 614 |
+
n0 = (h * 4 + npl) * 16
|
| 615 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(UQn_s[g, lane % 8, n0 + 8 * ((lane // 8) % 2)], "r", extent=4), T.access_ptr(bfr[(npl % 2) * 4], "w", extent=4))
|
| 616 |
+
for mt in T.unroll(2):
|
| 617 |
+
for nn in T.unroll(2):
|
| 618 |
+
T.ptx_mma("float32", "m16n8k8", "row", "col", "fp16", "fp16", "fp32", afrag3.data, mt * 4, bfr.data, (npl % 2) * 4 + nn * 2, cfrag.data, ((npl * 2 + nn) * 4 + mt * 2) * 2, T.bool(False))
|
| 619 |
+
if KEX:
|
| 620 |
+
# E goes to the fp16 St_s scaled by a power of two per (warp, half): the block maximum lands in [2^14, 2^15), so a tiny
|
| 621 |
+
# head keeps 11 significant bits instead of sinking into fp16 subnormals (the column sums and the quantisation undo it exactly)
|
| 622 |
+
emx[0] = 0.0
|
| 623 |
+
for i in T.unroll(64):
|
| 624 |
+
emx[0] = T.max(emx[0], T.abs(cfrag[i]))
|
| 625 |
+
for i in T.unroll(5):
|
| 626 |
+
emx[0] = T.max(emx[0], T.shfl_xor(emx[0], 1 << i))
|
| 627 |
+
ebx = T.min(T.max(268 - ((T.reinterpret(I32, emx[0]) >> 23) & 255), 2), 252)
|
| 628 |
+
esc[h] = T.reinterpret(F32, (254 - ebx) << 23) # 2^-e: undoes the scaling
|
| 629 |
+
emx[0] = T.reinterpret(F32, ebx << 23) # 2^e
|
| 630 |
+
for i in T.unroll(64):
|
| 631 |
+
cfrag[i] = cfrag[i] * emx[0]
|
| 632 |
+
for mt in T.unroll(2):
|
| 633 |
+
for npl in T.unroll(4):
|
| 634 |
+
if "noste" not in ABL:
|
| 635 |
+
for jj in T.unroll(4):
|
| 636 |
+
for c1 in T.vectorized(2):
|
| 637 |
+
ph[jj * 2 + c1] = T.cast(cfrag[((npl * 2 + jj // 2) * 4 + mt * 2 + jj % 2) * 2 + c1], F16)
|
| 638 |
+
T.call_extern("handle", "tl::ptx_stmatrix_m8n8_x4",
|
| 639 |
+
T.access_ptr(St_s[g, w * 32 + mt * 16 + 8 * ((lane // 8) % 2) + lane % 8, (h * 8 + npl * 2 + lane // 16) * 8], "w", extent=8),
|
| 640 |
+
T.reinterpret(I32, ph[0:2]), T.reinterpret(I32, ph[2:4]), T.reinterpret(I32, ph[4:6]), T.reinterpret(I32, ph[6:8]))
|
| 641 |
+
# ---- |E| column partials of this warp's 32 rows on the tensor cores (this half's 8 n-tiles): C[m][c] = sum_v 1 * |E[v][c]| with
|
| 642 |
+
# A = ones and B = |E| read back from the fp16 E tile (ldmatrix.x2.trans + sign-bit clear), accumulated into the dead cfrag;
|
| 643 |
+
# every m-row of C holds the sums -- lane rows r0 == 0 are used. No shuffle reduction. ----
|
| 644 |
+
T.sync_warp()
|
| 645 |
+
for i in T.unroll(32):
|
| 646 |
+
cfrag[i] = 0.0
|
| 647 |
+
for ntl in T.unroll(8):
|
| 648 |
+
for ks in T.unroll(2):
|
| 649 |
+
T.ptx_ldmatrix(T.bool(True), 2, T.access_ptr(St_s[g, w * 32 + ks * 16 + 8 * ((lane // 8) % 2) + lane % 8, (h * 8 + ntl) * 8], "r", extent=4), T.access_ptr(bh2[ks * 4], "w", extent=4))
|
| 650 |
+
for i in T.unroll(4):
|
| 651 |
+
bhi[i] = T.reinterpret(I32, bh2[i * 2:i * 2 + 2]) & T.int32(0x7FFF7FFF)
|
| 652 |
+
for ks in T.unroll(2):
|
| 653 |
+
T.ptx_mma("float32", "m16n8k16", "row", "col", "fp16", "fp16", "fp32", aone.data, 0, bhi.data, ks * 2, cfrag.data, ntl * 4, T.bool(False))
|
| 654 |
+
for ntl in T.unroll(8):
|
| 655 |
+
for c1 in T.unroll(2):
|
| 656 |
+
if KEX:
|
| 657 |
+
colp[(h * 8 + ntl) * 2 + c1] = cfrag[ntl * 4 + c1] * esc[h]
|
| 658 |
+
else:
|
| 659 |
+
colp[(h * 8 + ntl) * 2 + c1] = cfrag[ntl * 4 + c1]
|
| 660 |
+
T.sync_threads(bar, 128) # the residual mma operands (UQn_s, UQ_s) are consumed: the partials may take the buffer, the stage is free
|
| 661 |
+
T.fence_proxy_async()
|
| 662 |
+
T.mbarrier_arrive(consumed[s])
|
| 663 |
+
if r0 == 0:
|
| 664 |
+
for nt in T.unroll(16):
|
| 665 |
+
for c1 in T.vectorized(2):
|
| 666 |
+
cpart[g, w, nt * 8 + q4 * 2 + c1] = colp[nt * 2 + c1]
|
| 667 |
+
T.sync_threads(bar, 128)
|
| 668 |
+
if PROF:
|
| 669 |
+
tk[4] = T.call_extern("int64", "clock64")
|
| 670 |
+
# (4) column scale s_k (thread per column) from the 4 warp partials, reciprocal to smem
|
| 671 |
+
msum = (cpart[g, 0, t] + cpart[g, 1, t] + cpart[g, 2, t] + cpart[g, 3, t]) * (1.0 / V)
|
| 672 |
+
rskn = T.min(T.rsqrt(msum), 1.0 / EPS) # 1/max(sqrt(m), EPS) without the IEEE division slow path
|
| 673 |
+
Sk[slot, hv, t] = T.max(T.sqrt(msum), EPS)
|
| 674 |
+
rsk[g, 6, t] = rskn
|
| 675 |
+
T.sync_threads(bar, 128)
|
| 676 |
+
if PROF:
|
| 677 |
+
tk[5] = T.call_extern("int64", "clock64")
|
| 678 |
+
# (5) row-wise quantisation: warp w rows 32w.., 8 lanes per row (16 columns each), 4 rows per pass;
|
| 679 |
+
# row max over the 8 lanes, int8 codes packed in registers, one coalesced 16 B store per lane and row
|
| 680 |
+
for i in T.unroll(4):
|
| 681 |
+
for c1 in T.vectorized(4):
|
| 682 |
+
if KEX: # lanes 0-3 hold columns of half 0, lanes 4-7 of half 1
|
| 683 |
+
rk[i * 4 + c1] = rsk[g, 6, (lane % 8) * 16 + i * 4 + c1] * T.if_then_else(lane % 8 < 4, esc[0], esc[1])
|
| 684 |
+
else:
|
| 685 |
+
rk[i * 4 + c1] = rsk[g, 6, (lane % 8) * 16 + i * 4 + c1]
|
| 686 |
+
for i in T.unroll(8):
|
| 687 |
+
v0 = w * 32 + i * 4 + lane // 8
|
| 688 |
+
rmax[0] = 0.0
|
| 689 |
+
for hh in T.unroll(2):
|
| 690 |
+
for c1 in T.vectorized(8):
|
| 691 |
+
eh[((i % 2) * 2 + hh) * 8 + c1] = St_s[g, v0, (lane % 8) * 16 + hh * 8 + c1]
|
| 692 |
+
for hh in T.unroll(2):
|
| 693 |
+
for c1 in T.unroll(8):
|
| 694 |
+
ex[hh * 8 + c1] = T.cast(eh[((i % 2) * 2 + hh) * 8 + c1], F32) * rk[hh * 8 + c1]
|
| 695 |
+
rmax[0] = T.max(rmax[0], T.abs(ex[hh * 8 + c1]))
|
| 696 |
+
rmax[0] = T.max(rmax[0], T.shfl_xor(rmax[0], 1))
|
| 697 |
+
rmax[0] = T.max(rmax[0], T.shfl_xor(rmax[0], 2))
|
| 698 |
+
rmax[0] = T.max(rmax[0], T.shfl_xor(rmax[0], 4))
|
| 699 |
+
rmax[0] = T.max(rmax[0], EPS)
|
| 700 |
+
rmax[1] = QMAX * T.call_extern(F32, "__frcp_rn", rmax[0])
|
| 701 |
+
if lane % 8 == 0:
|
| 702 |
+
Sv[slot, hv, v0] = rmax[0]
|
| 703 |
+
if "nocode" not in ABL:
|
| 704 |
+
for c1 in T.unroll(4):
|
| 705 |
+
qw[c1] = T.call_extern(I32, "__byte_perm",
|
| 706 |
+
T.call_extern(I32, "__byte_perm", T.reinterpret(I32, ex[c1 * 4] * rmax[1] + 12582912.0), T.reinterpret(I32, ex[c1 * 4 + 1] * rmax[1] + 12582912.0), T.int32(0x0040)),
|
| 707 |
+
T.call_extern(I32, "__byte_perm", T.reinterpret(I32, ex[c1 * 4 + 2] * rmax[1] + 12582912.0), T.reinterpret(I32, ex[c1 * 4 + 3] * rmax[1] + 12582912.0), T.int32(0x0040)),
|
| 708 |
+
T.int32(0x5410))
|
| 709 |
+
for c1 in T.vectorized(4):
|
| 710 |
+
Sq[slot, hv, v0, (lane % 8) * 4 + c1] = qw[c1]
|
| 711 |
+
if PROF:
|
| 712 |
+
tk[6] = T.call_extern("int64", "clock64")
|
| 713 |
+
if t < L:
|
| 714 |
+
Wbuf[slot, hv, t] = 0.0
|
| 715 |
+
if KDA:
|
| 716 |
+
Pbuf[slot, hv, t] = 0.0
|
| 717 |
+
for jj in T.unroll(L):
|
| 718 |
+
Gbuf[slot, hv, jj, t] = T.reinterpret(BF16, T.cast(1.0, F16)) # entry factors -> fp16 1.0
|
| 719 |
+
else:
|
| 720 |
+
if t == 0:
|
| 721 |
+
Pbuf[slot, hv, 0] = 1.0
|
| 722 |
+
# hcnt stays at L: 'flushed, ring empty' for the step kernels (a reset here would change the due flags other CTAs are still scanning)
|
| 723 |
+
T.sync_threads(bar, 128) # St_s / UQn_s reuse by the next program of this group
|
| 724 |
+
if PROF:
|
| 725 |
+
tk[7] = T.call_extern("int64", "clock64")
|
| 726 |
+
if not PROFIT:
|
| 727 |
+
for i in T.unroll(7):
|
| 728 |
+
tacc[i] += T.cast(tk[i + 1] - tk[i], F32)
|
| 729 |
+
tacc[8] += 1.0
|
| 730 |
+
if PROF and g == 0 and t == 0 and bid < HV:
|
| 731 |
+
for i in T.unroll(10):
|
| 732 |
+
Wbuf[0, bid, i] = tacc[i]
|
| 733 |
+
return flush
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
class Pool:
|
| 737 |
+
"""Caller-owned state pool, the layout the serving engine uses. Every (slot, head) owns a V x K fp32-sized region
|
| 738 |
+
(64 KB) of one flat buffer; the checkpoint lives in its first 19 KB:
|
| 739 |
+
bytes [0, 16384) int8 codes, row-major [V, K]
|
| 740 |
+
bytes [16384, 16896) fp32 column scales s_k [K]
|
| 741 |
+
bytes [16896, 17408) fp32 row scales s_v [V]
|
| 742 |
+
bytes [17408, 19456) fp16 Compensator Tokens [R, K + V]: row r = (u[r, :K] | q[r, :V])
|
| 743 |
+
Slots are SS fp32 words apart; slot 0 is reserved (idx 0 = "no sequence"). The update buffer (kbuf, ubuf, gbuf, w), the
|
| 744 |
+
cumulative log-gate pcum and the per-(slot, head) fill counter hcnt are separate dense tensors. A program (slot, head) is due when hcnt == L."""
|
| 745 |
+
|
| 746 |
+
def __init__(self, num_slots, device="cuda"):
|
| 747 |
+
NS = self.NS = num_slots
|
| 748 |
+
self.raw = torch.zeros(NS * SS + OFF, dtype=torch.float32, device=device); st = self.raw.untyped_storage()
|
| 749 |
+
def view(dtype, shape, strides, off):
|
| 750 |
+
return torch.empty(0, dtype=dtype, device=device).set_(st).as_strided(shape, strides, off)
|
| 751 |
+
self.codes = view(torch.int8, (NS, HV, V, K), (4 * SS, 4 * V * K, K, 1), 4 * OFF)
|
| 752 |
+
self.codes32 = view(torch.int32, (NS, HV, V, K // 4), (SS, V * K, K // 4, 1), OFF)
|
| 753 |
+
self.codes16 = view(torch.int16, (NS, HV, V, K // 2), (2 * SS, 2 * V * K, K // 2, 1), 2 * OFF)
|
| 754 |
+
self.s_k = view(torch.float32, (NS, HV, K), (SS, V * K, 1), OFF + V * K // 4)
|
| 755 |
+
self.s_v = view(torch.float32, (NS, HV, V), (SS, V * K, 1), OFF + V * K // 4 + K)
|
| 756 |
+
self.s_kv = view(torch.float32, (NS, HV, K + V), (SS, V * K, 1), OFF + V * K // 4)
|
| 757 |
+
self.uq = view(torch.float16, (NS, HV, R, K + V), (2 * SS, 2 * V * K, K + V, 1), 2 * (OFF + V * K // 4 + K + V))
|
| 758 |
+
self.kbuf = torch.zeros(NS, HV, L, K, dtype=torch.bfloat16, device=device)
|
| 759 |
+
self.ubuf = torch.zeros(NS, HV, L, V, dtype=torch.bfloat16, device=device)
|
| 760 |
+
self.w = torch.zeros(NS, HV, L, device=device)
|
| 761 |
+
self.pcum = torch.zeros(NS, HV, K, device=device)
|
| 762 |
+
self.gbuf = torch.ones(NS, HV, L, K, dtype=torch.float16, device=device)
|
| 763 |
+
self.hcnt = torch.zeros(NS, HV, dtype=torch.int32, device=device)
|
| 764 |
+
self.kernel = make_flush_kernel(NS, HV, K, V, L, SS, R=R, ITERS=1, NCG=3, KDA=True, GB16=True,
|
| 765 |
+
SMS=torch.cuda.get_device_properties(self.raw.device).multi_processor_count)
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
def flush_inplace(pool, idx, q0):
|
| 769 |
+
"""Deployment form. idx: int32 [N] slot per sequence (0 = skip). For every (idx[n], head) with hcnt == L: rebuild the
|
| 770 |
+
state from the checkpoint and the update buffer, write the new checkpoint over the old one, reset w = 0, pcum = 0, gbuf = 1 (hcnt stays at L: "flushed, empty")."""
|
| 771 |
+
pool.kernel(pool.codes32, pool.s_k, pool.s_v, pool.s_kv, pool.kbuf, pool.ubuf, pool.w, pool.pcum, pool.gbuf.view(torch.bfloat16), pool.hcnt,
|
| 772 |
+
pool.codes16, pool.uq, q0, idx)
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
_POOLS = {}
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
def run(codes, s_k, s_v, u, q, kbuf, ubuf, gbuf, w, pcum, q0):
|
| 779 |
+
B = codes.shape[0]
|
| 780 |
+
pool = _POOLS.get((B, codes.device))
|
| 781 |
+
if pool is None:
|
| 782 |
+
pool = _POOLS[(B, codes.device)] = Pool(B + 8, codes.device)
|
| 783 |
+
sl = slice(1, B + 1)
|
| 784 |
+
pool.codes[sl] = codes; pool.s_k[sl] = s_k; pool.s_v[sl] = s_v; pool.uq[sl, :, :, :K] = u; pool.uq[sl, :, :, K:] = q
|
| 785 |
+
pool.kbuf[sl] = kbuf; pool.ubuf[sl] = ubuf; pool.gbuf[sl] = gbuf; pool.w[sl] = w; pool.pcum[sl] = pcum
|
| 786 |
+
pool.hcnt.zero_(); pool.hcnt[sl] = L
|
| 787 |
+
flush_inplace(pool, torch.arange(1, B + 1, dtype=torch.int32, device=codes.device), q0.contiguous())
|
| 788 |
+
return (pool.codes[sl].clone(), pool.s_k[sl].clone(), pool.s_v[sl].clone(),
|
| 789 |
+
pool.uq[sl, :, :, :K].clone(), pool.uq[sl, :, :, K:].clone())
|
kda/benchmark.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
"""Correctness and timing of a KDA flush implementation against definition.json (see README.md for the criterion).
|
| 3 |
+
|
| 4 |
+
python benchmark.py # the baseline in this directory
|
| 5 |
+
python benchmark.py --impl my_flush.py # a candidate exposing run(...) and, for timing, Pool / flush_inplace
|
| 6 |
+
|
| 7 |
+
Correctness (functional form `run`, every batch size in workloads.jsonl, three inputs each: a synthetic checkpoint with
|
| 8 |
+
edge-case heads, the checkpoint the reference produced from it, and unstructured in-domain random tensors):
|
| 9 |
+
the new checkpoint is decoded back to a V x K state and compared with the exactly rebuilt fp64 state, head by head:
|
| 10 |
+
err = mean |decode(checkpoint) - S| over the head's V x K elements, for the candidate and for the reference.
|
| 11 |
+
PASS <=> all outputs finite, codes in [-127, 127], and for every head
|
| 12 |
+
err_candidate <= (1 + REL_TOL) * err_reference if err_reference >= FLOOR * mean |S|
|
| 13 |
+
err_candidate <= CAP * mean |S| otherwise (a head the format captures almost exactly)
|
| 14 |
+
The order of operations and the precision of intermediates are free; what is bounded is the accuracy of the
|
| 15 |
+
checkpoint. Timing (deployment form `flush_inplace` on a caller-owned pool, every program due): CUDA kernel time
|
| 16 |
+
from the torch profiler, L2-cold -- NSETS disjoint slot sets are flushed in rotation so no call finds its data in L2.
|
| 17 |
+
"""
|
| 18 |
+
import argparse, importlib.util, json, sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
import torch
|
| 21 |
+
from torch.profiler import profile, ProfilerActivity
|
| 22 |
+
|
| 23 |
+
HERE = Path(__file__).resolve().parent
|
| 24 |
+
HV, K, V, L, R, QMAX = 32, 128, 128, 16, 4, 127.0
|
| 25 |
+
REL_TOL, FLOOR, CAP = 0.01, 1e-4, 1e-3 # 1 % more error than the reference; heads whose reference error is below 1e-4 |S| are held to 1e-3 |S|
|
| 26 |
+
NSETS, WARMUP, ITERS = 8, 4, 16
|
| 27 |
+
KB_PER_PROGRAM = 19 + 8 + 4.5 + 19 + 4.6 # checkpoint read + update buffer and gate history read + checkpoint write + resets (gate history to 1)
|
| 28 |
+
REF_TBPS = 6.3 # read + write bandwidth of the stock vLLM fp32 decode kernel on B200 at batch 256 (the memory-bound yardstick)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def load(path, name):
|
| 32 |
+
spec = importlib.util.spec_from_file_location(name, path); mod = importlib.util.module_from_spec(spec)
|
| 33 |
+
sys.modules[name] = mod; spec.loader.exec_module(mod); return mod
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def decode(codes, s_k, s_v, u, q):
|
| 37 |
+
return (torch.einsum("bhrv,bhrk->bhvk", q.double(), u.double())
|
| 38 |
+
+ codes.double() * (s_k.double()[..., None, :] / QMAX) * s_v.double()[..., :, None])
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def update_buffer(bs, dev, g):
|
| 42 |
+
"""A full window of buffered updates: keys, values, weights, per-channel decay factors in [0.6, 1] and the log-gate they
|
| 43 |
+
add up to (plus the decay the checkpoint saw before the first entry)."""
|
| 44 |
+
rn = lambda *s: torch.randn(*s, device=dev, generator=g)
|
| 45 |
+
kbuf = (rn(bs, HV, L, K) * 0.3).to(torch.bfloat16); ubuf = (rn(bs, HV, L, V) * 0.3).to(torch.bfloat16)
|
| 46 |
+
w = torch.ones(bs, HV, L, device=dev)
|
| 47 |
+
gbuf = (torch.rand(bs, HV, L, K, device=dev, generator=g) * 0.4 + 0.6).half()
|
| 48 |
+
pcum = gbuf.float().log().sum(-2) - torch.rand(bs, HV, K, device=dev, generator=g) * 0.5
|
| 49 |
+
return kbuf, ubuf, gbuf, w, pcum
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def structured_inputs(bs, dev, seed=0):
|
| 53 |
+
"""A synthetic checkpoint (full-rank codes with positive scales, a low-rank part, one hot row) and a full random window.
|
| 54 |
+
Heads 1..6 are edge cases: rank 1, all zero, rank 2, tiny (1e-4), huge (3e2), rank 1 plus a noise floor; head 7 has a
|
| 55 |
+
checkpoint decayed to nothing (log-gate -200) and head 8 one channel group that does not decay at all."""
|
| 56 |
+
g = torch.Generator(device=dev).manual_seed(seed)
|
| 57 |
+
rn = lambda *s: torch.randn(*s, device=dev, generator=g)
|
| 58 |
+
codes = (rn(bs, HV, V, K) * 40).round().clamp(-127, 127).to(torch.int8)
|
| 59 |
+
s_k = torch.rand(bs, HV, K, device=dev, generator=g) * 0.2 + 0.05; s_v = torch.rand(bs, HV, V, device=dev, generator=g) * 0.5 + 0.1
|
| 60 |
+
s_v[..., 5] *= 30
|
| 61 |
+
u = (rn(bs, HV, R, K) * 0.5).to(torch.float16); q = (rn(bs, HV, R, V) * 0.5).to(torch.float16)
|
| 62 |
+
kbuf, ubuf, gbuf, w, pcum = update_buffer(bs, dev, g)
|
| 63 |
+
for h in (1, 2, 3, 6): codes[:, h] = 0; u[:, h] = 0; q[:, h] = 0
|
| 64 |
+
w[:, 1, 1:] = 0; w[:, 2] = 0; w[:, 3, 2:] = 0; w[:, 6, 1:] = 0
|
| 65 |
+
codes[:, 6] = (rn(bs, V, K) * 40).round().clamp(-127, 127).to(torch.int8); s_k[:, 6] *= 1e-6
|
| 66 |
+
s_k[:, 4] *= 1e-4; u[:, 4] *= 1e-2; ubuf[:, 4] *= 1e-4
|
| 67 |
+
s_k[:, 5] *= 3e2; u[:, 5] *= 17; ubuf[:, 5] *= 3e2
|
| 68 |
+
pcum[:, 7] -= 200.0
|
| 69 |
+
gbuf[:, 8, :, :32] = 1.0; pcum[:, 8, :32] = 0.0
|
| 70 |
+
q0 = torch.randn(V, R, generator=torch.Generator().manual_seed(0)).to(dev)
|
| 71 |
+
return codes, s_k, s_v, u, q, kbuf, ubuf, gbuf, w, pcum, q0
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def random_inputs(bs, dev, seed=1):
|
| 75 |
+
"""Unstructured tensors inside the deployment domain: positive scales, decay factors in (0, 1], 0 <= w <= 1, log-gate <= 0."""
|
| 76 |
+
g = torch.Generator(device=dev).manual_seed(seed)
|
| 77 |
+
rn = lambda *s, dt=torch.float32: torch.randn(*s, device=dev, generator=g).to(dt)
|
| 78 |
+
lu = lambda *s: torch.exp(rn(*s) * 0.7) # positive scales spread over about two decades; |S| stays in the deployment range (below 1e4)
|
| 79 |
+
return (torch.randint(-127, 128, (bs, HV, V, K), device=dev, generator=g, dtype=torch.int8), lu(bs, HV, K) * 0.05, lu(bs, HV, V) * 0.3,
|
| 80 |
+
rn(bs, HV, R, K, dt=torch.float16), rn(bs, HV, R, V, dt=torch.float16), rn(bs, HV, L, K, dt=torch.bfloat16),
|
| 81 |
+
rn(bs, HV, L, V, dt=torch.bfloat16), (torch.rand(bs, HV, L, K, device=dev, generator=g) * 0.999 + 0.001).half(),
|
| 82 |
+
torch.rand(bs, HV, L, device=dev, generator=g), -torch.rand(bs, HV, K, device=dev, generator=g) * 20, rn(V, R))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def exact_state(inp):
|
| 86 |
+
codes, s_k, s_v, u, q, kbuf, ubuf, gbuf, w, pcum, q0 = inp
|
| 87 |
+
after = torch.flip(torch.cumprod(torch.flip(gbuf.double(), [-2]), -2), [-2])
|
| 88 |
+
D = torch.cat([after[..., 1:, :], torch.ones_like(after[..., :1, :])], -2)
|
| 89 |
+
return decode(codes, s_k, s_v, u, q) * torch.exp(pcum.double())[..., None, :] + torch.einsum("bhj,bhjv,bhjk->bhvk", w.double(), ubuf.double(), kbuf.double() * D)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def judge(out, ref, S):
|
| 93 |
+
finite = all(bool(torch.isfinite(t.float()).all()) for t in out[1:]); inrange = bool((out[0].int().abs() <= 127).all())
|
| 94 |
+
e_out = (decode(*out) - S).abs().mean((0, 2, 3)); e_ref = (decode(*ref) - S).abs().mean((0, 2, 3)); mag = S.abs().mean((0, 2, 3))
|
| 95 |
+
tight = (e_ref >= FLOOR * mag) & (e_ref > 0) # an all-zero head has e_ref = 0 and falls under the cap (which is then 0)
|
| 96 |
+
ok = finite and inrange and bool((e_out[tight] <= (1 + REL_TOL) * e_ref[tight]).all()) and bool((e_out[~tight] <= CAP * mag[~tight]).all())
|
| 97 |
+
ratio = (e_out[tight] / e_ref[tight]).max().item() # worst head among those compared relatively
|
| 98 |
+
return ok, ratio
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def check(bs, impl, ref_run, dev):
|
| 102 |
+
first = structured_inputs(bs, dev, seed=bs)
|
| 103 |
+
ref1 = ref_run(*[t.clone() for t in first])
|
| 104 |
+
second = (*ref1, *update_buffer(bs, dev, torch.Generator(device=dev).manual_seed(bs + 1)), first[10]) # the next window, from the reference's checkpoint
|
| 105 |
+
res = []
|
| 106 |
+
for inp, ref in ((first, ref1), (second, None), (random_inputs(bs, dev, seed=bs + 2), None)):
|
| 107 |
+
ref = ref_run(*[t.clone() for t in inp]) if ref is None else ref
|
| 108 |
+
out = impl.run(*[t.clone() for t in inp]); torch.cuda.synchronize()
|
| 109 |
+
res.append(judge(out, ref, exact_state(inp)))
|
| 110 |
+
return res
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def ktime(fn):
|
| 114 |
+
for i in range(WARMUP): fn(i % NSETS)
|
| 115 |
+
torch.cuda.synchronize()
|
| 116 |
+
with profile(activities=[ProfilerActivity.CUDA]) as prof:
|
| 117 |
+
for i in range(ITERS): fn(i % NSETS)
|
| 118 |
+
torch.cuda.synchronize()
|
| 119 |
+
ev = [e for e in prof.events() if e.device_type.name == "CUDA" and "fill" not in e.name.lower() and "mem" not in e.name.lower()]
|
| 120 |
+
return sum(e.device_time for e in ev) / ITERS / 1000
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def timing(bs, impl, dev):
|
| 124 |
+
pool = impl.Pool(NSETS * bs + 8, dev)
|
| 125 |
+
pool.raw.normal_(0, 0.1); pool.uq.normal_(0, 0.1) # arbitrary checkpoint contents: timing only
|
| 126 |
+
pool.kbuf.copy_(torch.randn(pool.kbuf.shape, device=dev)); pool.ubuf.copy_(torch.randn(pool.ubuf.shape, device=dev)); pool.w.uniform_(0, 1)
|
| 127 |
+
pool.gbuf.uniform_(0.6, 1.0); pool.pcum.uniform_(-5, 0)
|
| 128 |
+
q0 = torch.randn(V, R, generator=torch.Generator().manual_seed(0)).to(dev)
|
| 129 |
+
idxs = [torch.arange(1 + j * bs, 1 + (j + 1) * bs, dtype=torch.int32, device=dev) for j in range(NSETS)]
|
| 130 |
+
def call(j):
|
| 131 |
+
pool.hcnt.index_fill_(0, idxs[j].long(), L) # every program of the set is due (the kernel resets the counter)
|
| 132 |
+
impl.flush_inplace(pool, idxs[j], q0)
|
| 133 |
+
return ktime(call)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def main():
|
| 137 |
+
ap = argparse.ArgumentParser(); ap.add_argument("--impl", default=str(HERE / "baseline.py")); ap.add_argument("--skip-timing", action="store_true")
|
| 138 |
+
a = ap.parse_args(); dev = torch.device("cuda")
|
| 139 |
+
name = torch.cuda.get_device_name(0); assert any(m in name.split() for m in ("B200", "B300")), name
|
| 140 |
+
d = json.loads((HERE / "definition.json").read_text()); ns = {}; exec(d["reference"], ns); ref_run = ns["run"]
|
| 141 |
+
sizes = [json.loads(l)["workload"]["axes"]["batch_size"] for l in (HERE / "workloads.jsonl").read_text().splitlines() if line_ok(l)]
|
| 142 |
+
impl = load(a.impl, "flush_impl")
|
| 143 |
+
print(f"{name}, torch {torch.__version__}, impl {Path(a.impl).name}\n")
|
| 144 |
+
print("| batch_size | programs | worst-head error ratio vs reference (structured / second window / random) | correctness | all-due latency (ms) | memory bound (ms) |")
|
| 145 |
+
print("| --- | --- | --- | --- | --- | --- |")
|
| 146 |
+
allok = True
|
| 147 |
+
for bs in sizes:
|
| 148 |
+
res = check(bs, impl, ref_run, dev); ok = all(r[0] for r in res); allok &= ok
|
| 149 |
+
t_ms = float("nan") if a.skip_timing or not hasattr(impl, "flush_inplace") else timing(bs, impl, dev)
|
| 150 |
+
bound = KB_PER_PROGRAM * 1024 * bs * HV / REF_TBPS / 1e12 * 1e3
|
| 151 |
+
print(f"| {bs} | {bs * HV} | {res[0][1]:.4f} / {res[1][1]:.4f} / {res[2][1]:.4f} | {'PASS' if ok else 'FAIL'} | {t_ms:.4f} | {bound:.3f} |", flush=True)
|
| 152 |
+
assert allok, f"correctness failed (limit: {1 + REL_TOL:.2f}x the reference's error per head, or {CAP:g} |S| where the reference error is below {FLOOR:g} |S|)"
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def line_ok(l):
|
| 156 |
+
return bool(l.strip())
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
if __name__ == "__main__":
|
| 160 |
+
main()
|
kda/benchmark_results.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"measurement": "Final authoritative KDA paired evaluation of the unmodified PR #10 benchmark.",
|
| 3 |
+
"timestamp_utc": "2026-10-24T12:38:34Z",
|
| 4 |
+
"gpu": "NVIDIA B300 SXM6 AC",
|
| 5 |
+
"toolchain": {
|
| 6 |
+
"torch": "2.12.1+cu130",
|
| 7 |
+
"tilelang_baseline": "0.1.12",
|
| 8 |
+
"cutlass_dsl": "4.6.0",
|
| 9 |
+
"claude_cli": "2.1.308",
|
| 10 |
+
"codex_cli": "0.163.0"
|
| 11 |
+
},
|
| 12 |
+
"kernel_sha256": "2f635896b70d13ddfd76822d711f75c8c3abb4606f0ccd25dd04b583b95b7ec6",
|
| 13 |
+
"submission_id": "e797d585430d45e1",
|
| 14 |
+
"all_geomean": 2.999299707826145,
|
| 15 |
+
"large_geomean": 3.1278874935669196,
|
| 16 |
+
"workloads": [
|
| 17 |
+
{
|
| 18 |
+
"batch_size": 16,
|
| 19 |
+
"speedup": 2.669491525423729,
|
| 20 |
+
"correctness_passed": true
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"batch_size": 32,
|
| 24 |
+
"speedup": 2.8111111111111113,
|
| 25 |
+
"correctness_passed": true
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"batch_size": 64,
|
| 29 |
+
"speedup": 3.1700000000000004,
|
| 30 |
+
"correctness_passed": true
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"batch_size": 128,
|
| 34 |
+
"speedup": 3.2187500000000004,
|
| 35 |
+
"correctness_passed": true
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"batch_size": 256,
|
| 39 |
+
"speedup": 3.093658536585366,
|
| 40 |
+
"correctness_passed": true
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"batch_size": 512,
|
| 44 |
+
"speedup": 3.0732206861239115,
|
| 45 |
+
"correctness_passed": true
|
| 46 |
+
}
|
| 47 |
+
]
|
| 48 |
+
}
|
kda/definition.json
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "leapquant_kda_flush_r4_int8_h32_v128_k128",
|
| 3 |
+
"op_type": "leapquant_kda_flush",
|
| 4 |
+
"description": "LeapQuant window flush (arXiv:2609.38166) for Kimi Delta Attention (per-key-channel gate): at the end of a 16-token window, rebuild each head's V x K fp32 recurrent state from its quantized checkpoint (4 fp16 Compensator Tokens + smoothed int8 residual) decayed per channel and the window's 16 buffered rank-1 updates with their per-channel decay histories, then re-quantize it (one round of subspace iteration for the new Compensator Tokens, smoothing scales and int8 codes for the residual). Correctness is judged on the decoded state (see the request README), not elementwise.",
|
| 5 |
+
"axes": {
|
| 6 |
+
"batch_size": {
|
| 7 |
+
"type": "var"
|
| 8 |
+
},
|
| 9 |
+
"num_heads": {
|
| 10 |
+
"type": "const",
|
| 11 |
+
"value": 32
|
| 12 |
+
},
|
| 13 |
+
"value_dim": {
|
| 14 |
+
"type": "const",
|
| 15 |
+
"value": 128
|
| 16 |
+
},
|
| 17 |
+
"key_dim": {
|
| 18 |
+
"type": "const",
|
| 19 |
+
"value": 128
|
| 20 |
+
},
|
| 21 |
+
"window": {
|
| 22 |
+
"type": "const",
|
| 23 |
+
"value": 16
|
| 24 |
+
},
|
| 25 |
+
"rank": {
|
| 26 |
+
"type": "const",
|
| 27 |
+
"value": 4
|
| 28 |
+
}
|
| 29 |
+
},
|
| 30 |
+
"inputs": {
|
| 31 |
+
"codes": {
|
| 32 |
+
"shape": [
|
| 33 |
+
"batch_size",
|
| 34 |
+
"num_heads",
|
| 35 |
+
"value_dim",
|
| 36 |
+
"key_dim"
|
| 37 |
+
],
|
| 38 |
+
"dtype": "int8"
|
| 39 |
+
},
|
| 40 |
+
"s_k": {
|
| 41 |
+
"shape": [
|
| 42 |
+
"batch_size",
|
| 43 |
+
"num_heads",
|
| 44 |
+
"key_dim"
|
| 45 |
+
],
|
| 46 |
+
"dtype": "float32"
|
| 47 |
+
},
|
| 48 |
+
"s_v": {
|
| 49 |
+
"shape": [
|
| 50 |
+
"batch_size",
|
| 51 |
+
"num_heads",
|
| 52 |
+
"value_dim"
|
| 53 |
+
],
|
| 54 |
+
"dtype": "float32"
|
| 55 |
+
},
|
| 56 |
+
"u": {
|
| 57 |
+
"shape": [
|
| 58 |
+
"batch_size",
|
| 59 |
+
"num_heads",
|
| 60 |
+
"rank",
|
| 61 |
+
"key_dim"
|
| 62 |
+
],
|
| 63 |
+
"dtype": "float16"
|
| 64 |
+
},
|
| 65 |
+
"q": {
|
| 66 |
+
"shape": [
|
| 67 |
+
"batch_size",
|
| 68 |
+
"num_heads",
|
| 69 |
+
"rank",
|
| 70 |
+
"value_dim"
|
| 71 |
+
],
|
| 72 |
+
"dtype": "float16"
|
| 73 |
+
},
|
| 74 |
+
"kbuf": {
|
| 75 |
+
"shape": [
|
| 76 |
+
"batch_size",
|
| 77 |
+
"num_heads",
|
| 78 |
+
"window",
|
| 79 |
+
"key_dim"
|
| 80 |
+
],
|
| 81 |
+
"dtype": "bfloat16"
|
| 82 |
+
},
|
| 83 |
+
"ubuf": {
|
| 84 |
+
"shape": [
|
| 85 |
+
"batch_size",
|
| 86 |
+
"num_heads",
|
| 87 |
+
"window",
|
| 88 |
+
"value_dim"
|
| 89 |
+
],
|
| 90 |
+
"dtype": "bfloat16"
|
| 91 |
+
},
|
| 92 |
+
"gbuf": {
|
| 93 |
+
"shape": [
|
| 94 |
+
"batch_size",
|
| 95 |
+
"num_heads",
|
| 96 |
+
"window",
|
| 97 |
+
"key_dim"
|
| 98 |
+
],
|
| 99 |
+
"dtype": "float16"
|
| 100 |
+
},
|
| 101 |
+
"w": {
|
| 102 |
+
"shape": [
|
| 103 |
+
"batch_size",
|
| 104 |
+
"num_heads",
|
| 105 |
+
"window"
|
| 106 |
+
],
|
| 107 |
+
"dtype": "float32"
|
| 108 |
+
},
|
| 109 |
+
"pcum": {
|
| 110 |
+
"shape": [
|
| 111 |
+
"batch_size",
|
| 112 |
+
"num_heads",
|
| 113 |
+
"key_dim"
|
| 114 |
+
],
|
| 115 |
+
"dtype": "float32"
|
| 116 |
+
},
|
| 117 |
+
"q0": {
|
| 118 |
+
"shape": [
|
| 119 |
+
"value_dim",
|
| 120 |
+
"rank"
|
| 121 |
+
],
|
| 122 |
+
"dtype": "float32"
|
| 123 |
+
}
|
| 124 |
+
},
|
| 125 |
+
"outputs": {
|
| 126 |
+
"codes_new": {
|
| 127 |
+
"shape": [
|
| 128 |
+
"batch_size",
|
| 129 |
+
"num_heads",
|
| 130 |
+
"value_dim",
|
| 131 |
+
"key_dim"
|
| 132 |
+
],
|
| 133 |
+
"dtype": "int8"
|
| 134 |
+
},
|
| 135 |
+
"s_k_new": {
|
| 136 |
+
"shape": [
|
| 137 |
+
"batch_size",
|
| 138 |
+
"num_heads",
|
| 139 |
+
"key_dim"
|
| 140 |
+
],
|
| 141 |
+
"dtype": "float32"
|
| 142 |
+
},
|
| 143 |
+
"s_v_new": {
|
| 144 |
+
"shape": [
|
| 145 |
+
"batch_size",
|
| 146 |
+
"num_heads",
|
| 147 |
+
"value_dim"
|
| 148 |
+
],
|
| 149 |
+
"dtype": "float32"
|
| 150 |
+
},
|
| 151 |
+
"u_new": {
|
| 152 |
+
"shape": [
|
| 153 |
+
"batch_size",
|
| 154 |
+
"num_heads",
|
| 155 |
+
"rank",
|
| 156 |
+
"key_dim"
|
| 157 |
+
],
|
| 158 |
+
"dtype": "float16"
|
| 159 |
+
},
|
| 160 |
+
"q_new": {
|
| 161 |
+
"shape": [
|
| 162 |
+
"batch_size",
|
| 163 |
+
"num_heads",
|
| 164 |
+
"rank",
|
| 165 |
+
"value_dim"
|
| 166 |
+
],
|
| 167 |
+
"dtype": "float16"
|
| 168 |
+
}
|
| 169 |
+
},
|
| 170 |
+
"constraints": [
|
| 171 |
+
"batch_size >= 1"
|
| 172 |
+
],
|
| 173 |
+
"reference": "# SPDX-License-Identifier: Apache-2.0\nimport torch\n\nQMAX = 127.0\nEPS = 1e-12\n\n\ndef _mgs(m):\n \"\"\"Modified Gram-Schmidt on the columns of m, projections applied twice (\"twice is enough\"): a column that is\n numerically dependent on the previous ones (a rank-deficient head) still comes out orthogonal to them.\"\"\"\n cols = []\n for j in range(m.shape[-1]):\n v = m[..., j]\n for _ in range(2):\n for c in cols:\n v = v - c * (c * v).sum(-1, keepdim=True)\n cols.append(v / v.norm(dim=-1, keepdim=True).clamp_min(1e-30))\n return torch.stack(cols, -1)\n\n\ndef run(codes, s_k, s_v, u, q, kbuf, ubuf, gbuf, w, pcum, q0):\n \"\"\"LeapQuant window flush for Kimi Delta Attention (per-key-channel gate): fold the buffered updates of one window into a new\n quantized checkpoint.\n\n codes int8 [B, H, V, K], s_k f32 [B, H, K], s_v f32 [B, H, V]: smoothed int8 residual of the old checkpoint\n u f16 [B, H, R, K], q f16 [B, H, R, V]: the R Compensator Tokens of the old checkpoint (rank-R part = q^T u)\n kbuf bf16 [B, H, L, K], ubuf bf16 [B, H, L, V]: the window's buffered updates; w f32 [B, H, L]: their weights\n gbuf f16 [B, H, L, K]: per-channel decay factor of the step that appended each entry; pcum f32 [B, H, K]: log-gate summed\n over the window (the checkpoint's decay is exp(pcum))\n q0 f32 [V, R]: fixed start of the subspace iteration\n Returns the new (codes, s_k, s_v, u, q). fp32 arithmetic; the order of operations is not part of the contract.\n \"\"\"\n # 1. rebuild the fp32 state: S = (q^T u + dequant(codes)) diag(exp(pcum)) + sum_j w_j ubuf_j (kbuf_j * D_j)^T [V, K]\n # with D_j = prod_{i > j} gbuf_i (the decay entry j has seen since it was appended)\n s_old = torch.einsum(\"bhrv,bhrk->bhvk\", q.float(), u.float())\n s_old = s_old + codes.float() * (s_k[..., None, :] / QMAX) * s_v[..., :, None]\n after = torch.flip(torch.cumprod(torch.flip(gbuf.float(), [-2]), -2), [-2]) # prod_{i >= j}\n D = torch.cat([after[..., 1:, :], torch.ones_like(after[..., :1, :])], -2) # prod_{i > j}\n s = s_old * torch.exp(pcum)[..., None, :] + torch.einsum(\"bhj,bhjv,bhjk->bhvk\", w, ubuf.float(), kbuf.float() * D)\n # 2. Compensator Tokens: ONE round of subspace iteration from q0, stored as fp16\n x = s.transpose(-1, -2) # [K, V]\n qk = _mgs(x @ q0) # [K, R]\n qv = _mgs(x.transpose(-1, -2) @ qk) # [V, R], orthonormal columns\n uk = x @ qv # [K, R]\n u_new = uk.transpose(-1, -2).to(torch.float16)\n q_new = qv.transpose(-1, -2).to(torch.float16)\n # 3. residual, smoothing scales (column scale = sqrt of the mean |E| over rows, row scale = max of the smoothed row), int8\n e = s - torch.einsum(\"bhrv,bhrk->bhvk\", q_new.float(), u_new.float())\n sk = e.abs().mean(-2).sqrt().clamp_min(EPS)\n sv = (e.abs() / sk[..., None, :]).amax(-1).clamp_min(EPS)\n c = torch.round(e / (sk[..., None, :] * sv[..., :, None]) * QMAX).clamp(-QMAX, QMAX).to(torch.int8)\n return c, sk, sv, u_new, q_new\n"
|
| 174 |
+
}
|
kda/provenance.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"repo_id": "humanfia-lab/kernels",
|
| 3 |
+
"version": 1,
|
| 4 |
+
"source_url": "https://github.com/NVlabs/kda/pull/10",
|
| 5 |
+
"source_commit": "48f02e6ba0e98a1841ab6f0a2d99a90b2de1a326",
|
| 6 |
+
"upstream_sha256": {
|
| 7 |
+
"baseline.py": "97b4e538674bd5a9310e41c3e7dfa19a9c76314f511acd5f5c29fdce95bfffb5",
|
| 8 |
+
"benchmark.py": "69e24658f3091c9fdd23873498dcbc6b243ce3816a7480435bd59cd0ef82751d",
|
| 9 |
+
"definition.json": "f25aac78d32ccc50401e2fb1a56d2c0a3ee27548b5d91f9e4d7e5a7c9d2dc323",
|
| 10 |
+
"workloads.jsonl": "ee5c437eeca601e5a83f5b3a4c07a6c11822e4e9438487a893ad6668a7075dfe"
|
| 11 |
+
},
|
| 12 |
+
"kernel_sha256": "2f635896b70d13ddfd76822d711f75c8c3abb4606f0ccd25dd04b583b95b7ec6",
|
| 13 |
+
"kernel_git_commit": "61f43860e7a487c9d9cbaccc043f270f2eb8693c",
|
| 14 |
+
"official_submission_id": "e797d585430d45e1",
|
| 15 |
+
"official_artifact_digest": "ac983001fb75c5ae2f66b557dcacf40332493853f741d812245839bb7110849d",
|
| 16 |
+
"official_benchmarks_sha": "3ac105d12ef108513555f8eac2a39203c0a18c5af3a8b6f77cb12751274ede75",
|
| 17 |
+
"official_evaluation_utc": "2026-10-24T12:38:34Z",
|
| 18 |
+
"experiment_hours": 48,
|
| 19 |
+
"models": [
|
| 20 |
+
"codex/gpt-6.1-sol:max",
|
| 21 |
+
"claude/claude-opus-5-5:max"
|
| 22 |
+
],
|
| 23 |
+
"packaging": "Unmodified accepted kernel; exposed as a module of the combined HF package.",
|
| 24 |
+
"component": "kda",
|
| 25 |
+
"kernel_path": "build/torch-cuda/_kda.py"
|
| 26 |
+
}
|
kda/validate.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
"""Validate the local HF package and caller-owned deployment contract on CUDA."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import base64
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from kernels import get_local_kernel
|
| 12 |
+
|
| 13 |
+
import benchmark as bench
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def main() -> None:
|
| 17 |
+
here = Path(__file__).resolve().parent
|
| 18 |
+
runtime = here.parent / "build/torch-cuda"
|
| 19 |
+
metadata = json.loads((runtime / "metadata.json").read_text())
|
| 20 |
+
for filename, expected in metadata["digest"]["files"].items():
|
| 21 |
+
actual = base64.b64encode(hashlib.sha256((runtime / filename).read_bytes()).digest()).decode()
|
| 22 |
+
assert actual == expected, f"digest mismatch: {filename}"
|
| 23 |
+
op = get_local_kernel(here.parent, trust_remote_code=True).kda
|
| 24 |
+
assert all(hasattr(op, name) for name in ("Pool", "flush_inplace", "run"))
|
| 25 |
+
namespace = {}
|
| 26 |
+
exec(json.loads((here / "definition.json").read_text())["reference"], namespace)
|
| 27 |
+
reference = namespace["run"]
|
| 28 |
+
device = torch.device("cuda")
|
| 29 |
+
ns = 8
|
| 30 |
+
pool = op.Pool(ns, device=device)
|
| 31 |
+
is_kda = hasattr(pool, "gbuf")
|
| 32 |
+
idx = torch.tensor([0, 7, 2, 5, 1, 3], dtype=torch.int32, device=device)
|
| 33 |
+
counters = torch.where(torch.arange(ns * 32, device=device).reshape(ns, 32) % 3 == 0, 16, 7).int()
|
| 34 |
+
selected = torch.zeros(ns, dtype=torch.bool, device=device)
|
| 35 |
+
selected[idx.long()] = True
|
| 36 |
+
selected[0] = False
|
| 37 |
+
due = selected[:, None] & (counters == 16)
|
| 38 |
+
fields = ["codes", "s_k", "s_v", "uq", "kbuf", "ubuf", "w", "hcnt"] + (["gbuf", "pcum"] if is_kda else ["p"])
|
| 39 |
+
q0 = torch.empty(128, 4, device=device)
|
| 40 |
+
|
| 41 |
+
def restore(inputs):
|
| 42 |
+
pool.codes.copy_(inputs[0]); pool.s_k.copy_(inputs[1]); pool.s_v.copy_(inputs[2])
|
| 43 |
+
pool.uq[..., :128].copy_(inputs[3]); pool.uq[..., 128:].copy_(inputs[4])
|
| 44 |
+
pool.kbuf.copy_(inputs[5]); pool.ubuf.copy_(inputs[6])
|
| 45 |
+
if is_kda:
|
| 46 |
+
pool.gbuf.copy_(inputs[7]); pool.w.copy_(inputs[8]); pool.pcum.copy_(inputs[9])
|
| 47 |
+
else:
|
| 48 |
+
pool.w.copy_(inputs[7]); pool.p[..., 0].copy_(inputs[8])
|
| 49 |
+
pool.hcnt.copy_(counters)
|
| 50 |
+
q0.copy_(inputs[-1])
|
| 51 |
+
|
| 52 |
+
def snapshot():
|
| 53 |
+
return {name: getattr(pool, name).clone() for name in fields}
|
| 54 |
+
|
| 55 |
+
def verify(inputs, before):
|
| 56 |
+
ref = reference(*[tensor.clone() for tensor in inputs])
|
| 57 |
+
actual = (pool.codes, pool.s_k, pool.s_v, pool.uq[..., :128], pool.uq[..., 128:])
|
| 58 |
+
# Each selected (slot, head) is a separate checked head, never averaged across slots.
|
| 59 |
+
out = tuple(tensor[due].unsqueeze(0) for tensor in actual)
|
| 60 |
+
ref = tuple(tensor[due].unsqueeze(0) for tensor in ref)
|
| 61 |
+
exact = bench.exact_state(inputs)[due].unsqueeze(0)
|
| 62 |
+
passed, ratio = bench.judge(out, ref, exact)
|
| 63 |
+
assert passed, f"deployment accuracy failed: {ratio}"
|
| 64 |
+
for name in fields:
|
| 65 |
+
assert torch.equal(getattr(pool, name)[~due], before[name][~due]), f"non-due/slot-0 write: {name}"
|
| 66 |
+
for name in ("kbuf", "ubuf"):
|
| 67 |
+
assert torch.equal(getattr(pool, name), before[name]), f"update buffer changed: {name}"
|
| 68 |
+
# The serving contract leaves hcnt at L ("flushed, empty"); the decode
|
| 69 |
+
# step consumes that sentinel. Clearing it in flush would race scanners.
|
| 70 |
+
assert torch.equal(pool.hcnt, before["hcnt"]), "flush changed fill counters"
|
| 71 |
+
assert bool((pool.w[due] == 0).all())
|
| 72 |
+
if is_kda:
|
| 73 |
+
assert bool((pool.gbuf[due] == 1).all())
|
| 74 |
+
assert bool((pool.pcum[due] == 0).all())
|
| 75 |
+
else:
|
| 76 |
+
assert bool((pool.p[due] == 1).all())
|
| 77 |
+
return float(ratio)
|
| 78 |
+
|
| 79 |
+
stream = torch.cuda.Stream()
|
| 80 |
+
inputs = bench.structured_inputs(ns, device, seed=91)
|
| 81 |
+
restore(inputs)
|
| 82 |
+
torch.cuda.synchronize()
|
| 83 |
+
before = snapshot()
|
| 84 |
+
torch.cuda.synchronize()
|
| 85 |
+
with torch.cuda.stream(stream):
|
| 86 |
+
op.flush_inplace(pool, idx, q0)
|
| 87 |
+
stream.synchronize()
|
| 88 |
+
ratios = [verify(inputs, before)]
|
| 89 |
+
before = snapshot()
|
| 90 |
+
op.flush_inplace(pool, torch.empty(0, dtype=torch.int32, device=device), q0)
|
| 91 |
+
torch.cuda.synchronize()
|
| 92 |
+
assert all(torch.equal(getattr(pool, name), before[name]) for name in fields), "empty idx is not a no-op"
|
| 93 |
+
|
| 94 |
+
restore(inputs)
|
| 95 |
+
torch.cuda.synchronize()
|
| 96 |
+
graph = torch.cuda.CUDAGraph()
|
| 97 |
+
with torch.cuda.graph(graph, stream=stream):
|
| 98 |
+
op.flush_inplace(pool, idx, q0)
|
| 99 |
+
for seed in (92, 93):
|
| 100 |
+
inputs = bench.structured_inputs(ns, device, seed=seed)
|
| 101 |
+
# structured_inputs always uses the same q0; vary it explicitly here.
|
| 102 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 103 |
+
inputs = (*inputs[:-1], torch.randn(128, 4, device=device, generator=generator))
|
| 104 |
+
restore(inputs)
|
| 105 |
+
before = snapshot()
|
| 106 |
+
torch.cuda.synchronize()
|
| 107 |
+
graph.replay()
|
| 108 |
+
torch.cuda.synchronize()
|
| 109 |
+
ratios.append(verify(inputs, before))
|
| 110 |
+
# Simulate the caller advancing the counters so no head is due.
|
| 111 |
+
pool.hcnt[due] = 0
|
| 112 |
+
after = snapshot()
|
| 113 |
+
torch.cuda.synchronize()
|
| 114 |
+
graph.replay()
|
| 115 |
+
torch.cuda.synchronize()
|
| 116 |
+
assert all(torch.equal(getattr(pool, name), after[name]) for name in fields), "replay with no due heads is not a no-op"
|
| 117 |
+
print(json.dumps({
|
| 118 |
+
"status": "pass", "gpu": torch.cuda.get_device_name(),
|
| 119 |
+
"compute_capability": list(torch.cuda.get_device_capability()),
|
| 120 |
+
"checks": ["runtime digests", "HF get_local_kernel", "mixed due heads", "unselected slots", "reserved slot 0", "window resets", "fill counters unchanged", "empty idx", "non-default stream", "graph capture", "graph replay with changed inputs and q0", "no-op replay with no due heads"],
|
| 121 |
+
"deployment_worst_head_error_ratios": ratios,
|
| 122 |
+
}, indent=2))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
main()
|
kda/validation_results.json
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"validated_at_utc": "2026-10-25T20:03:16.828102+00:00",
|
| 3 |
+
"kernel_sha256": "2f635896b70d13ddfd76822d711f75c8c3abb4606f0ccd25dd04b583b95b7ec6",
|
| 4 |
+
"deployment": {
|
| 5 |
+
"status": "pass",
|
| 6 |
+
"gpu": "NVIDIA B300 SXM6 AC",
|
| 7 |
+
"compute_capability": [
|
| 8 |
+
10,
|
| 9 |
+
3
|
| 10 |
+
],
|
| 11 |
+
"checks": [
|
| 12 |
+
"runtime digests",
|
| 13 |
+
"HF get_local_kernel",
|
| 14 |
+
"mixed due heads",
|
| 15 |
+
"unselected slots",
|
| 16 |
+
"reserved slot 0",
|
| 17 |
+
"window resets",
|
| 18 |
+
"fill counters unchanged",
|
| 19 |
+
"empty idx",
|
| 20 |
+
"non-default stream",
|
| 21 |
+
"graph capture",
|
| 22 |
+
"graph replay with changed inputs and q0",
|
| 23 |
+
"no-op replay with no due heads"
|
| 24 |
+
],
|
| 25 |
+
"deployment_worst_head_error_ratios": [
|
| 26 |
+
1.00270965549408,
|
| 27 |
+
1.0036139557099675,
|
| 28 |
+
1.0016564812747861
|
| 29 |
+
]
|
| 30 |
+
},
|
| 31 |
+
"original_benchmark": {
|
| 32 |
+
"workloads_passed": 6,
|
| 33 |
+
"input_families_per_workload": 3,
|
| 34 |
+
"thresholds_modified": false,
|
| 35 |
+
"workloads": [
|
| 36 |
+
{
|
| 37 |
+
"batch_size": 16,
|
| 38 |
+
"programs": 512,
|
| 39 |
+
"error_ratios": [
|
| 40 |
+
1.0004,
|
| 41 |
+
1.0006,
|
| 42 |
+
1.0011
|
| 43 |
+
],
|
| 44 |
+
"latency_ms": 0.0118,
|
| 45 |
+
"correctness_passed": true
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"batch_size": 32,
|
| 49 |
+
"programs": 1024,
|
| 50 |
+
"error_ratios": [
|
| 51 |
+
1.0004,
|
| 52 |
+
1.0004,
|
| 53 |
+
1.0005
|
| 54 |
+
],
|
| 55 |
+
"latency_ms": 0.0181,
|
| 56 |
+
"correctness_passed": true
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"batch_size": 64,
|
| 60 |
+
"programs": 2048,
|
| 61 |
+
"error_ratios": [
|
| 62 |
+
1.0004,
|
| 63 |
+
1.0003,
|
| 64 |
+
1.0007
|
| 65 |
+
],
|
| 66 |
+
"latency_ms": 0.0303,
|
| 67 |
+
"correctness_passed": true
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"batch_size": 128,
|
| 71 |
+
"programs": 4096,
|
| 72 |
+
"error_ratios": [
|
| 73 |
+
1.0004,
|
| 74 |
+
1.0002,
|
| 75 |
+
1.0004
|
| 76 |
+
],
|
| 77 |
+
"latency_ms": 0.0546,
|
| 78 |
+
"correctness_passed": true
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"batch_size": 256,
|
| 82 |
+
"programs": 8192,
|
| 83 |
+
"error_ratios": [
|
| 84 |
+
1.0002,
|
| 85 |
+
1.0001,
|
| 86 |
+
1.0002
|
| 87 |
+
],
|
| 88 |
+
"latency_ms": 0.1024,
|
| 89 |
+
"correctness_passed": true
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"batch_size": 512,
|
| 93 |
+
"programs": 16384,
|
| 94 |
+
"error_ratios": [
|
| 95 |
+
1.0001,
|
| 96 |
+
1.0001,
|
| 97 |
+
1.0002
|
| 98 |
+
],
|
| 99 |
+
"latency_ms": 0.1934,
|
| 100 |
+
"correctness_passed": true
|
| 101 |
+
}
|
| 102 |
+
]
|
| 103 |
+
},
|
| 104 |
+
"environment": {
|
| 105 |
+
"python": "3.12.13",
|
| 106 |
+
"torch": "2.12.1+cu130",
|
| 107 |
+
"cutlass_dsl": "4.6.0",
|
| 108 |
+
"cuda_bindings": "13.3.1",
|
| 109 |
+
"kernels": "0.17.2",
|
| 110 |
+
"huggingface_hub": "2.2.0"
|
| 111 |
+
}
|
| 112 |
+
}
|
kda/workloads.jsonl
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"definition": "leapquant_kda_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "07c593f1-14d2-4b26-a792-11e20b573fcd", "axes": {"batch_size": 16}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "gbuf": {"type": "random"}, "w": {"type": "random"}, "pcum": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
| 2 |
+
{"definition": "leapquant_kda_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "f5821023-5d61-473a-87ea-7dc6de4090f3", "axes": {"batch_size": 32}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "gbuf": {"type": "random"}, "w": {"type": "random"}, "pcum": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
| 3 |
+
{"definition": "leapquant_kda_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "a27c0f52-7524-4463-b0be-bf4b1546c69f", "axes": {"batch_size": 64}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "gbuf": {"type": "random"}, "w": {"type": "random"}, "pcum": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
| 4 |
+
{"definition": "leapquant_kda_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "5156fd10-5f43-43f8-a328-f1439cce0ea2", "axes": {"batch_size": 128}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "gbuf": {"type": "random"}, "w": {"type": "random"}, "pcum": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
| 5 |
+
{"definition": "leapquant_kda_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "37471ec1-91a1-4202-a419-f8be63bcb015", "axes": {"batch_size": 256}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "gbuf": {"type": "random"}, "w": {"type": "random"}, "pcum": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
| 6 |
+
{"definition": "leapquant_kda_flush_r4_int8_h32_v128_k128", "workload": {"uuid": "119b1bc8-ecfe-41f8-840b-e333f9344092", "axes": {"batch_size": 512}, "inputs": {"codes": {"type": "random"}, "s_k": {"type": "random"}, "s_v": {"type": "random"}, "u": {"type": "random"}, "q": {"type": "random"}, "kbuf": {"type": "random"}, "ubuf": {"type": "random"}, "gbuf": {"type": "random"}, "w": {"type": "random"}, "pcum": {"type": "random"}, "q0": {"type": "random"}}}, "solution": null, "evaluation": null}
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Install the CUDA 13.0 PyTorch wheel first; see README.md.
|
| 2 |
+
torch==2.12.1
|
| 3 |
+
nvidia-cutlass-dsl[cu13]==4.6.0
|
| 4 |
+
cuda-bindings==13.3.1
|
| 5 |
+
kernels==0.17.2
|
| 6 |
+
huggingface-hub==2.2.0
|
| 7 |
+
tilelang==0.1.12
|