Datasets:
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tile_kernels_src/.editorconfig +58 -0
- tile_kernels_src/.gitignore +20 -0
- tile_kernels_src/LICENSE +21 -0
- tile_kernels_src/README.md +88 -0
- tile_kernels_src/UNKNOWN.egg-info/PKG-INFO +11 -0
- tile_kernels_src/UNKNOWN.egg-info/SOURCES.txt +131 -0
- tile_kernels_src/UNKNOWN.egg-info/dependency_links.txt +1 -0
- tile_kernels_src/UNKNOWN.egg-info/top_level.txt +1 -0
- tile_kernels_src/pyproject.toml +58 -0
- tile_kernels_src/tests/__init__.py +0 -0
- tile_kernels_src/tests/conftest.py +10 -0
- tile_kernels_src/tests/engram/test_engram_fused_weight.py +56 -0
- tile_kernels_src/tests/engram/test_engram_gate_bwd.py +112 -0
- tile_kernels_src/tests/engram/test_engram_gate_fwd.py +108 -0
- tile_kernels_src/tests/engram/test_engram_grad_w_reduce.py +76 -0
- tile_kernels_src/tests/engram/test_engram_hash.py +71 -0
- tile_kernels_src/tests/mhc/test_expand.py +45 -0
- tile_kernels_src/tests/mhc/test_head_compute_mix.py +54 -0
- tile_kernels_src/tests/mhc/test_multilayer_recompute.py +157 -0
- tile_kernels_src/tests/mhc/test_norm_fn.py +130 -0
- tile_kernels_src/tests/mhc/test_post.py +72 -0
- tile_kernels_src/tests/mhc/test_pre_apply_mix.py +52 -0
- tile_kernels_src/tests/mhc/test_pre_big_fuse.py +138 -0
- tile_kernels_src/tests/mhc/test_pre_split_mixes.py +103 -0
- tile_kernels_src/tests/mhc/test_sinkhorn.py +43 -0
- tile_kernels_src/tests/moe/test_aux_fi.py +65 -0
- tile_kernels_src/tests/moe/test_expand_to_fused.py +150 -0
- tile_kernels_src/tests/moe/test_get_fused_mapping.py +103 -0
- tile_kernels_src/tests/moe/test_group_count.py +55 -0
- tile_kernels_src/tests/moe/test_inplace_unique_group_indices.py +79 -0
- tile_kernels_src/tests/moe/test_mask_indices_by_tp.py +70 -0
- tile_kernels_src/tests/moe/test_normalize_weight.py +57 -0
- tile_kernels_src/tests/moe/test_reduce_fused.py +112 -0
- tile_kernels_src/tests/moe/test_top2_sum_gate.py +359 -0
- tile_kernels_src/tests/moe/test_topk_gate.py +75 -0
- tile_kernels_src/tests/moe/test_topk_sum_and_topk_idx.py +86 -0
- tile_kernels_src/tests/pytest_benchmark_plugin.py +477 -0
- tile_kernels_src/tests/pytest_random_plugin.py +18 -0
- tile_kernels_src/tests/quant/test_cast_back.py +157 -0
- tile_kernels_src/tests/quant/test_cast_back_e5m6.py +120 -0
- tile_kernels_src/tests/quant/test_per_block_cast.py +110 -0
- tile_kernels_src/tests/quant/test_per_block_cast_lossless.py +114 -0
- tile_kernels_src/tests/quant/test_per_channel_cast.py +75 -0
- tile_kernels_src/tests/quant/test_per_channel_cast_and_transpose.py +77 -0
- tile_kernels_src/tests/quant/test_per_channel_cast_fused.py +104 -0
- tile_kernels_src/tests/quant/test_per_token_cast.py +166 -0
- tile_kernels_src/tests/quant/test_per_token_cast_to_e5m6.py +118 -0
- tile_kernels_src/tests/quant/test_swiglu_backward_and_per_token_cast.py +149 -0
- tile_kernels_src/tests/quant/test_swiglu_forward_and_per_channel_cast_and_transpose.py +114 -0
- tile_kernels_src/tests/quant/test_swiglu_forward_and_per_token_cast.py +179 -0
tile_kernels_src/.editorconfig
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# https://editorconfig.org/
|
| 2 |
+
|
| 3 |
+
root = true
|
| 4 |
+
|
| 5 |
+
[*]
|
| 6 |
+
charset = utf-8
|
| 7 |
+
end_of_line = lf
|
| 8 |
+
indent_style = space
|
| 9 |
+
indent_size = 4
|
| 10 |
+
trim_trailing_whitespace = true
|
| 11 |
+
insert_final_newline = true
|
| 12 |
+
|
| 13 |
+
[*.{py,pyi}]
|
| 14 |
+
indent_size = 4
|
| 15 |
+
|
| 16 |
+
[*.{cpp,hpp,cxx,cc,c,h,cu,cuh}]
|
| 17 |
+
indent_size = 4
|
| 18 |
+
|
| 19 |
+
[*.rs]
|
| 20 |
+
indent_size = 4
|
| 21 |
+
|
| 22 |
+
[*.go]
|
| 23 |
+
indent_style = tab
|
| 24 |
+
|
| 25 |
+
[*.{yaml,yml}]
|
| 26 |
+
indent_size = 2
|
| 27 |
+
|
| 28 |
+
[.clang-{format,tidy}]
|
| 29 |
+
indent_size = 2
|
| 30 |
+
|
| 31 |
+
[Makefile]
|
| 32 |
+
indent_style = tab
|
| 33 |
+
|
| 34 |
+
[*.sh]
|
| 35 |
+
indent_size = 4
|
| 36 |
+
|
| 37 |
+
[*.bat]
|
| 38 |
+
indent_size = 4
|
| 39 |
+
end_of_line = crlf
|
| 40 |
+
|
| 41 |
+
[*.md]
|
| 42 |
+
indent_size = 2
|
| 43 |
+
x-soft-wrap-text = true
|
| 44 |
+
|
| 45 |
+
[*.rst]
|
| 46 |
+
indent_size = 4
|
| 47 |
+
x-soft-wrap-text = true
|
| 48 |
+
|
| 49 |
+
[*.{html,xml,css,scss,js,jsx,ts,tsx,vue}]
|
| 50 |
+
indent_size = 2
|
| 51 |
+
|
| 52 |
+
[**/test{,s,ing}/**/*.txt]
|
| 53 |
+
trim_trailing_whitespace = false
|
| 54 |
+
insert_final_newline = false
|
| 55 |
+
|
| 56 |
+
[**/example{,s}/**/*.txt]
|
| 57 |
+
trim_trailing_whitespace = false
|
| 58 |
+
insert_final_newline = false
|
tile_kernels_src/.gitignore
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.DS_Store
|
| 2 |
+
build
|
| 3 |
+
dist
|
| 4 |
+
*.egg-info
|
| 5 |
+
*.pyc
|
| 6 |
+
__pycache__/
|
| 7 |
+
|
| 8 |
+
# PyCharm Settings
|
| 9 |
+
.idea/
|
| 10 |
+
*.iml
|
| 11 |
+
*.iws
|
| 12 |
+
|
| 13 |
+
# Python packaging version file
|
| 14 |
+
_version.py
|
| 15 |
+
|
| 16 |
+
# VSCode Settings
|
| 17 |
+
/.vscode
|
| 18 |
+
|
| 19 |
+
# workspace
|
| 20 |
+
workspace
|
tile_kernels_src/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 DeepSeek
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
tile_kernels_src/README.md
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tile Kernels
|
| 2 |
+
|
| 3 |
+
Optimized GPU kernels for LLM operations, built with [TileLang](https://github.com/tile-ai/tilelang). TileLang is a domain-specific language for expressing high-performance GPU kernels in Python, featuring easy migration, agile development, and automatic optimization.
|
| 4 |
+
|
| 5 |
+
Most kernels in this project approach the limit of hardware performance regarding the compute intensity and memory bandwidth. Some of them have already been used in internal training and inference scenarios. However, they do not represent best practices and we are actively working on improving the code quality and documentation.
|
| 6 |
+
|
| 7 |
+
## Features
|
| 8 |
+
|
| 9 |
+
- **Gating** — Top-k expert selection and scoring for Mixture of Experts routing
|
| 10 |
+
- **MoE Routing** — Token-to-expert mapping, fused expansion/reduction and weight normalization
|
| 11 |
+
- **Quantization** — Per-token, per-block, and per-channel FP8/FP4/E5M6 casting with fused SwiGLU+quantization ops
|
| 12 |
+
- **Transpose** — Batched transpose operations
|
| 13 |
+
- **Engram** — Engram gating kernels with fused RMSNorm, forward/backward passes and weight gradient reduction
|
| 14 |
+
- **Manifold HyperConnection** — Hyper-connection kernels including Sinkhorn normalization and mix splitting/application
|
| 15 |
+
- **Modeling** — High-level `torch.autograd.Function` wrappers composing low-level kernels into trainable layers (engram gate, mHC pipeline)
|
| 16 |
+
|
| 17 |
+
## Requirements
|
| 18 |
+
|
| 19 |
+
- Python 3.10 or higher
|
| 20 |
+
- PyTorch 2.10 or higher
|
| 21 |
+
- TileLang 0.1.9 or higher
|
| 22 |
+
- NVIDIA SM90 or SM100 architecture GPU
|
| 23 |
+
- CUDA Toolkit 13.1 or higher
|
| 24 |
+
|
| 25 |
+
## Installation
|
| 26 |
+
|
| 27 |
+
### Install a local development version
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
pip install -e ".[dev]"
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
### Install a release version
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
pip install tile-kernels
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
## Testing
|
| 40 |
+
|
| 41 |
+
Tests using pytest:
|
| 42 |
+
|
| 43 |
+
### Test single test file
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
pytest tests/transpose/test_transpose.py -n 4 # Correctness only with 4 workers
|
| 47 |
+
pytest tests/transpose/test_transpose.py --run-benchmark # Correctness + Benchmarking
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
### Pressure test
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
TK_FULL_TEST=1 pytest -n 4 --count 2
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
## Project Structure
|
| 57 |
+
|
| 58 |
+
```txt
|
| 59 |
+
tile_kernels/
|
| 60 |
+
├── moe/ # Mixture of Experts routing related kernels
|
| 61 |
+
├── quant/ # FP8/FP4/E5M6 quantization
|
| 62 |
+
├── transpose/ # Batched transpose
|
| 63 |
+
├── engram/ # Engram gating kernels
|
| 64 |
+
├── mhc/ # Manifold HyperConnection kernels
|
| 65 |
+
├── modeling/ # High-level autograd modeling layers (engram, mHC)
|
| 66 |
+
├── torch/ # PyTorch reference implementations
|
| 67 |
+
└── testing/ # Test and benchmark utilities
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
## Acknowledgement
|
| 71 |
+
|
| 72 |
+
This project is built on [TileLang](https://github.com/tile-ai/tilelang). Thanks and respect to the developers!
|
| 73 |
+
|
| 74 |
+
## License
|
| 75 |
+
|
| 76 |
+
This code repository is released under [the MIT License](LICENSE).
|
| 77 |
+
|
| 78 |
+
## Citation
|
| 79 |
+
|
| 80 |
+
```bibtex
|
| 81 |
+
@misc{tilekernels,
|
| 82 |
+
title={TileKernels},
|
| 83 |
+
author={Xiangwen Wang, Chenhao Xu, Huanqi Cao, Rui Tian, Weilin Zhao, Kuai Yu and Chenggang Zhao},
|
| 84 |
+
year={2026},
|
| 85 |
+
publisher = {GitHub},
|
| 86 |
+
howpublished = {\url{https://github.com/deepseek-ai/TileKernels}},
|
| 87 |
+
}
|
| 88 |
+
```
|
tile_kernels_src/UNKNOWN.egg-info/PKG-INFO
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: UNKNOWN
|
| 3 |
+
Version: 0.1.dev3+g36d9e45d3
|
| 4 |
+
Summary: UNKNOWN
|
| 5 |
+
Home-page: UNKNOWN
|
| 6 |
+
License: UNKNOWN
|
| 7 |
+
Platform: UNKNOWN
|
| 8 |
+
License-File: LICENSE
|
| 9 |
+
|
| 10 |
+
UNKNOWN
|
| 11 |
+
|
tile_kernels_src/UNKNOWN.egg-info/SOURCES.txt
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.editorconfig
|
| 2 |
+
.gitignore
|
| 3 |
+
LICENSE
|
| 4 |
+
README.md
|
| 5 |
+
pyproject.toml
|
| 6 |
+
UNKNOWN.egg-info/PKG-INFO
|
| 7 |
+
UNKNOWN.egg-info/SOURCES.txt
|
| 8 |
+
UNKNOWN.egg-info/dependency_links.txt
|
| 9 |
+
UNKNOWN.egg-info/top_level.txt
|
| 10 |
+
tests/__init__.py
|
| 11 |
+
tests/conftest.py
|
| 12 |
+
tests/pytest_benchmark_plugin.py
|
| 13 |
+
tests/pytest_random_plugin.py
|
| 14 |
+
tests/engram/test_engram_fused_weight.py
|
| 15 |
+
tests/engram/test_engram_gate_bwd.py
|
| 16 |
+
tests/engram/test_engram_gate_fwd.py
|
| 17 |
+
tests/engram/test_engram_grad_w_reduce.py
|
| 18 |
+
tests/engram/test_engram_hash.py
|
| 19 |
+
tests/mhc/test_expand.py
|
| 20 |
+
tests/mhc/test_head_compute_mix.py
|
| 21 |
+
tests/mhc/test_multilayer_recompute.py
|
| 22 |
+
tests/mhc/test_norm_fn.py
|
| 23 |
+
tests/mhc/test_post.py
|
| 24 |
+
tests/mhc/test_pre_apply_mix.py
|
| 25 |
+
tests/mhc/test_pre_big_fuse.py
|
| 26 |
+
tests/mhc/test_pre_split_mixes.py
|
| 27 |
+
tests/mhc/test_sinkhorn.py
|
| 28 |
+
tests/moe/test_aux_fi.py
|
| 29 |
+
tests/moe/test_expand_to_fused.py
|
| 30 |
+
tests/moe/test_get_fused_mapping.py
|
| 31 |
+
tests/moe/test_group_count.py
|
| 32 |
+
tests/moe/test_inplace_unique_group_indices.py
|
| 33 |
+
tests/moe/test_mask_indices_by_tp.py
|
| 34 |
+
tests/moe/test_normalize_weight.py
|
| 35 |
+
tests/moe/test_reduce_fused.py
|
| 36 |
+
tests/moe/test_top2_sum_gate.py
|
| 37 |
+
tests/moe/test_topk_gate.py
|
| 38 |
+
tests/moe/test_topk_sum_and_topk_idx.py
|
| 39 |
+
tests/quant/test_cast_back.py
|
| 40 |
+
tests/quant/test_cast_back_e5m6.py
|
| 41 |
+
tests/quant/test_per_block_cast.py
|
| 42 |
+
tests/quant/test_per_block_cast_lossless.py
|
| 43 |
+
tests/quant/test_per_channel_cast.py
|
| 44 |
+
tests/quant/test_per_channel_cast_and_transpose.py
|
| 45 |
+
tests/quant/test_per_channel_cast_fused.py
|
| 46 |
+
tests/quant/test_per_token_cast.py
|
| 47 |
+
tests/quant/test_per_token_cast_to_e5m6.py
|
| 48 |
+
tests/quant/test_swiglu_backward_and_per_token_cast.py
|
| 49 |
+
tests/quant/test_swiglu_forward_and_per_channel_cast_and_transpose.py
|
| 50 |
+
tests/quant/test_swiglu_forward_and_per_token_cast.py
|
| 51 |
+
tests/transpose/test_transpose.py
|
| 52 |
+
tile_kernels/__init__.py
|
| 53 |
+
tile_kernels/config.py
|
| 54 |
+
tile_kernels/utils.py
|
| 55 |
+
tile_kernels/engram/__init__.py
|
| 56 |
+
tile_kernels/engram/engram_fused_weight_kernel.py
|
| 57 |
+
tile_kernels/engram/engram_gate_kernel.py
|
| 58 |
+
tile_kernels/engram/engram_grad_w_reduce_kernel.py
|
| 59 |
+
tile_kernels/engram/engram_hash_kernel.py
|
| 60 |
+
tile_kernels/mhc/__init__.py
|
| 61 |
+
tile_kernels/mhc/expand_kernel.py
|
| 62 |
+
tile_kernels/mhc/head_compute_mix_kernel.py
|
| 63 |
+
tile_kernels/mhc/multilayer_recompute_kernel.py
|
| 64 |
+
tile_kernels/mhc/norm_fn_kernel.py
|
| 65 |
+
tile_kernels/mhc/post_kernel.py
|
| 66 |
+
tile_kernels/mhc/pre_apply_mix_kernel.py
|
| 67 |
+
tile_kernels/mhc/pre_big_fuse_kernel.py
|
| 68 |
+
tile_kernels/mhc/pre_split_mixes_kernel.py
|
| 69 |
+
tile_kernels/mhc/sinkhorn_kernel.py
|
| 70 |
+
tile_kernels/modeling/__init__.py
|
| 71 |
+
tile_kernels/modeling/engram/__init__.py
|
| 72 |
+
tile_kernels/modeling/engram/engram_gate.py
|
| 73 |
+
tile_kernels/modeling/mhc/__init__.py
|
| 74 |
+
tile_kernels/modeling/mhc/functional.py
|
| 75 |
+
tile_kernels/modeling/mhc/ops/__init__.py
|
| 76 |
+
tile_kernels/modeling/mhc/ops/expand.py
|
| 77 |
+
tile_kernels/modeling/mhc/ops/head_compute_mix.py
|
| 78 |
+
tile_kernels/modeling/mhc/ops/multilayer_recompute.py
|
| 79 |
+
tile_kernels/modeling/mhc/ops/norm_fn.py
|
| 80 |
+
tile_kernels/modeling/mhc/ops/post.py
|
| 81 |
+
tile_kernels/modeling/mhc/ops/pre_apply_mix.py
|
| 82 |
+
tile_kernels/modeling/mhc/ops/pre_big_fuse.py
|
| 83 |
+
tile_kernels/modeling/mhc/ops/pre_split_mixes.py
|
| 84 |
+
tile_kernels/modeling/mhc/ops/sinkhorn.py
|
| 85 |
+
tile_kernels/moe/__init__.py
|
| 86 |
+
tile_kernels/moe/aux_fi_kernel.py
|
| 87 |
+
tile_kernels/moe/common.py
|
| 88 |
+
tile_kernels/moe/expand_to_fused_kernel.py
|
| 89 |
+
tile_kernels/moe/get_fused_mapping_kernel.py
|
| 90 |
+
tile_kernels/moe/group_count_kernel.py
|
| 91 |
+
tile_kernels/moe/inplace_unique_group_indices_kernel.py
|
| 92 |
+
tile_kernels/moe/mask_indices_by_tp_kernel.py
|
| 93 |
+
tile_kernels/moe/normalize_weight_kernel.py
|
| 94 |
+
tile_kernels/moe/reduce_fused_kernel.py
|
| 95 |
+
tile_kernels/moe/scoring.py
|
| 96 |
+
tile_kernels/moe/top2_sum_gate_kernel.py
|
| 97 |
+
tile_kernels/moe/topk_gate_kernel.py
|
| 98 |
+
tile_kernels/moe/topk_sum_and_topk_group_idx_kernel.py
|
| 99 |
+
tile_kernels/quant/__init__.py
|
| 100 |
+
tile_kernels/quant/cast_back_e5m6_kernel.py
|
| 101 |
+
tile_kernels/quant/cast_back_kernel.py
|
| 102 |
+
tile_kernels/quant/common.py
|
| 103 |
+
tile_kernels/quant/per_block_cast_kernel.py
|
| 104 |
+
tile_kernels/quant/per_block_cast_lossless_kernel.py
|
| 105 |
+
tile_kernels/quant/per_channel_cast_and_transpose_kernel.py
|
| 106 |
+
tile_kernels/quant/per_channel_cast_fused_kernel.py
|
| 107 |
+
tile_kernels/quant/per_channel_cast_kernel.py
|
| 108 |
+
tile_kernels/quant/per_token_cast_kernel.py
|
| 109 |
+
tile_kernels/quant/per_token_cast_to_e5m6_kernel.py
|
| 110 |
+
tile_kernels/quant/swiglu_backward_and_per_token_cast_kernel.py
|
| 111 |
+
tile_kernels/quant/swiglu_forward_and_per_channel_cast_and_transpose_kernel.py
|
| 112 |
+
tile_kernels/quant/swiglu_forward_and_per_token_cast_kernel.py
|
| 113 |
+
tile_kernels/quant/types.py
|
| 114 |
+
tile_kernels/testing/__init__.py
|
| 115 |
+
tile_kernels/testing/bench.py
|
| 116 |
+
tile_kernels/testing/generator.py
|
| 117 |
+
tile_kernels/testing/numeric.py
|
| 118 |
+
tile_kernels/testing/quant.py
|
| 119 |
+
tile_kernels/torch/__init__.py
|
| 120 |
+
tile_kernels/torch/cast.py
|
| 121 |
+
tile_kernels/torch/cast_e5m6.py
|
| 122 |
+
tile_kernels/torch/engram.py
|
| 123 |
+
tile_kernels/torch/expand_to_fused.py
|
| 124 |
+
tile_kernels/torch/mhc.py
|
| 125 |
+
tile_kernels/torch/moe.py
|
| 126 |
+
tile_kernels/torch/per_channel_cast_fused.py
|
| 127 |
+
tile_kernels/torch/reduce_fused.py
|
| 128 |
+
tile_kernels/torch/swiglu.py
|
| 129 |
+
tile_kernels/torch/topk.py
|
| 130 |
+
tile_kernels/transpose/__init__.py
|
| 131 |
+
tile_kernels/transpose/batched_transpose_kernel.py
|
tile_kernels_src/UNKNOWN.egg-info/dependency_links.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
tile_kernels_src/UNKNOWN.egg-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
tile_kernels_src/pyproject.toml
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools", "wheel", "setuptools-scm>=8"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[tool.setuptools_scm]
|
| 6 |
+
version_file = "tile_kernels/_version.py"
|
| 7 |
+
|
| 8 |
+
[project]
|
| 9 |
+
name = "tile_kernels"
|
| 10 |
+
dynamic = ["version"]
|
| 11 |
+
description = "Tilelang-based kernels."
|
| 12 |
+
readme = "README.md"
|
| 13 |
+
license = "MIT"
|
| 14 |
+
authors = [
|
| 15 |
+
{ name = "Chenhao Xu", email = "xch@deepseek.com" },
|
| 16 |
+
{ name = "Xiangwen Wang", email = "xiangwen.wang@deepseek.com" },
|
| 17 |
+
{ name = "Huanqi Cao", email = "caohuanqi@deepseek.com" },
|
| 18 |
+
{ name = "Rui Tian", email = "tianr22@deepseek.com"},
|
| 19 |
+
{ name = "Weilin Zhao", email = "zhaoweilin@deepseek.com" },
|
| 20 |
+
{ name = "Kuai Yu", email = "yukuai@deepseek.com" },
|
| 21 |
+
{ name = "Chenggang Zhao", email = "chenggangz@deepseek.com"}
|
| 22 |
+
]
|
| 23 |
+
dependencies = [
|
| 24 |
+
"torch>=2.10",
|
| 25 |
+
"tilelang>=0.1.9"
|
| 26 |
+
]
|
| 27 |
+
requires-python = ">=3.10"
|
| 28 |
+
classifiers = [
|
| 29 |
+
"Development Status :: 3 - Alpha",
|
| 30 |
+
"Intended Audience :: Developers",
|
| 31 |
+
"Programming Language :: Python :: 3",
|
| 32 |
+
"Programming Language :: Python :: 3.10",
|
| 33 |
+
"Programming Language :: Python :: 3.11",
|
| 34 |
+
"Programming Language :: Python :: 3.12",
|
| 35 |
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
[project.optional-dependencies]
|
| 39 |
+
dev = ["setuptools", "wheel", "setuptools-scm>=8", "pytest", "pytest-xdist", "pytest-repeat"]
|
| 40 |
+
|
| 41 |
+
[tool.setuptools.packages.find]
|
| 42 |
+
where = ["."]
|
| 43 |
+
include = ["tile_kernels*"]
|
| 44 |
+
|
| 45 |
+
[project.urls]
|
| 46 |
+
Homepage = "https://github.com/deepseek-ai/TileKernels"
|
| 47 |
+
|
| 48 |
+
# Linter tools
|
| 49 |
+
|
| 50 |
+
[tool.ruff]
|
| 51 |
+
line-length = 150
|
| 52 |
+
|
| 53 |
+
[tool.ruff.lint]
|
| 54 |
+
select = ["Q000"]
|
| 55 |
+
fixable = ["Q000"]
|
| 56 |
+
|
| 57 |
+
[tool.ruff.lint.flake8-quotes]
|
| 58 |
+
inline-quotes = "single"
|
tile_kernels_src/tests/__init__.py
ADDED
|
File without changes
|
tile_kernels_src/tests/conftest.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Root-level conftest
|
| 2 |
+
#
|
| 3 |
+
# Loads the benchmark plugin (CLI options, markers, fixtures).
|
| 4 |
+
# The plugin lives in a file deliberately NOT named conftest.py to
|
| 5 |
+
# avoid pluggy's duplicate-registration error.
|
| 6 |
+
|
| 7 |
+
pytest_plugins = [
|
| 8 |
+
'tests.pytest_random_plugin',
|
| 9 |
+
'tests.pytest_benchmark_plugin',
|
| 10 |
+
]
|
tile_kernels_src/tests/engram/test_engram_fused_weight.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from tile_kernels.engram import fused_weight
|
| 6 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 7 |
+
from tile_kernels.testing.generator import generate_hidden_sizes
|
| 8 |
+
from tile_kernels.testing.bench import make_param_id
|
| 9 |
+
|
| 10 |
+
# Disable TileLang prints
|
| 11 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def generate_test_data(params):
|
| 15 |
+
hc_mult = params['hc']
|
| 16 |
+
hidden_size = params['hidden']
|
| 17 |
+
wh_data = torch.randn(hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 18 |
+
we_data = torch.randn(hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 19 |
+
return (wh_data, we_data)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 23 |
+
return [
|
| 24 |
+
{'hc': hc, 'hidden': hidden_size}
|
| 25 |
+
for hc in (4,)
|
| 26 |
+
for hidden_size in generate_hidden_sizes(128)
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 31 |
+
def test_engram_fused_weight(params):
|
| 32 |
+
wh_data, we_data = generate_test_data(params)
|
| 33 |
+
|
| 34 |
+
ref = wh_data.float() * we_data.float()
|
| 35 |
+
out = fused_weight(wh_data, we_data)
|
| 36 |
+
|
| 37 |
+
assert_equal(out, ref)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.mark.benchmark
|
| 41 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 42 |
+
def test_engram_fused_weight_benchmark(benchmark_timer, benchmark_record, params):
|
| 43 |
+
wh_data, we_data = generate_test_data(params)
|
| 44 |
+
out = fused_weight(wh_data, we_data)
|
| 45 |
+
|
| 46 |
+
t_us = benchmark_timer(lambda: fused_weight(wh_data, we_data))
|
| 47 |
+
|
| 48 |
+
num_bytes = count_bytes(wh_data, we_data, out)
|
| 49 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 50 |
+
benchmark_record(
|
| 51 |
+
kernel='fused_weight',
|
| 52 |
+
operation='fwd',
|
| 53 |
+
params=params,
|
| 54 |
+
time_us=t_us,
|
| 55 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 56 |
+
)
|
tile_kernels_src/tests/engram/test_engram_gate_bwd.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from tile_kernels.engram import engram_gate_bwd
|
| 6 |
+
from tile_kernels.torch.engram import engram_gate_ref
|
| 7 |
+
from tile_kernels.testing.numeric import calc_diff, count_bytes
|
| 8 |
+
from tile_kernels.testing.generator import generate_hidden_sizes, generate_num_tokens
|
| 9 |
+
from tile_kernels.testing.bench import make_param_id
|
| 10 |
+
|
| 11 |
+
# Disable TileLang prints
|
| 12 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def generate_test_data(params):
|
| 16 |
+
num_tokens = params['num_tokens']
|
| 17 |
+
hc_mult = params['hc']
|
| 18 |
+
hidden_size = params['hidden']
|
| 19 |
+
eps = 1e-20
|
| 20 |
+
clamp_value = 1e-6
|
| 21 |
+
x_data = torch.randn(num_tokens, hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 22 |
+
k_data = torch.randn(num_tokens, hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 23 |
+
v_data = torch.randn(num_tokens, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 24 |
+
wh_data = torch.randn(hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 25 |
+
we_data = torch.randn(hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 26 |
+
weight_fused = wh_data.float() * we_data.float()
|
| 27 |
+
grad_out = torch.randn(num_tokens, hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 28 |
+
return (x_data, k_data, v_data, wh_data, we_data, weight_fused, grad_out, eps, clamp_value)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 32 |
+
return [
|
| 33 |
+
{'num_tokens': t, 'hc': hc, 'hidden': hidden_size}
|
| 34 |
+
for t in generate_num_tokens(is_benchmark=is_benchmark)
|
| 35 |
+
for hc in (4,)
|
| 36 |
+
for hidden_size in generate_hidden_sizes(128)
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 41 |
+
def test_engram_gate_bwd(params):
|
| 42 |
+
(x_data, k_data, v_data, wh_data, we_data, weight_fused, grad_out, eps, clamp_value) = generate_test_data(params)
|
| 43 |
+
|
| 44 |
+
# Reference: forward with intermediates + autograd backward
|
| 45 |
+
x_ref = x_data.clone().requires_grad_(True)
|
| 46 |
+
k_ref = k_data.clone().requires_grad_(True)
|
| 47 |
+
v_ref = v_data.clone().requires_grad_(True)
|
| 48 |
+
# Cast to float32 so autograd produces fp32 gradients matching the kernel
|
| 49 |
+
wh_ref = wh_data.float().requires_grad_(True)
|
| 50 |
+
we_ref = we_data.float().requires_grad_(True)
|
| 51 |
+
o_ref, dot_ref, gate_score_ref, rstd_x_ref, rstd_k_ref = engram_gate_ref(
|
| 52 |
+
x_ref, k_ref, v_ref, wh_ref, we_ref, clamp_value, eps, save_for_backward=True,
|
| 53 |
+
)
|
| 54 |
+
o_ref.backward(grad_out)
|
| 55 |
+
|
| 56 |
+
# Kernel backward using ref intermediates
|
| 57 |
+
grad_x, grad_k, grad_v, grad_w_partial = engram_gate_bwd(
|
| 58 |
+
grad_out, x_data, k_data, v_data, weight_fused,
|
| 59 |
+
dot_ref, gate_score_ref, rstd_x_ref, rstd_k_ref, clamp_value,
|
| 60 |
+
)
|
| 61 |
+
grad_w_fused = grad_w_partial.sum(0)
|
| 62 |
+
grad_wh = grad_w_fused * we_data.float()
|
| 63 |
+
grad_we = grad_w_fused * wh_data.float()
|
| 64 |
+
|
| 65 |
+
# Correctness
|
| 66 |
+
diff_x = calc_diff(grad_x, x_ref.grad)
|
| 67 |
+
assert diff_x < 1e-8, f'grad_x mismatch: {diff_x:.6e}'
|
| 68 |
+
diff_k = calc_diff(grad_k, k_ref.grad)
|
| 69 |
+
assert diff_k < 1e-8, f'grad_k mismatch: {diff_k:.6e}'
|
| 70 |
+
diff_v = calc_diff(grad_v, v_ref.grad)
|
| 71 |
+
assert diff_v < 1e-8, f'grad_v mismatch: {diff_v:.6e}'
|
| 72 |
+
diff_wh = calc_diff(grad_wh, wh_ref.grad)
|
| 73 |
+
assert diff_wh < 1e-8, f'grad_wh mismatch: {diff_wh:.6e}'
|
| 74 |
+
diff_we = calc_diff(grad_we, we_ref.grad)
|
| 75 |
+
assert diff_we < 1e-8, f'grad_we mismatch: {diff_we:.6e}'
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@pytest.mark.benchmark
|
| 79 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 80 |
+
def test_engram_gate_bwd_benchmark(benchmark_timer, benchmark_record, params):
|
| 81 |
+
(x_data, k_data, v_data, wh_data, we_data, weight_fused, grad_out, eps, clamp_value) = generate_test_data(params)
|
| 82 |
+
|
| 83 |
+
# Forward to get intermediates
|
| 84 |
+
o_ref, dot_ref, gate_score_ref, rstd_x_ref, rstd_k_ref = engram_gate_ref(
|
| 85 |
+
x_data, k_data, v_data, wh_data, we_data, clamp_value, eps, save_for_backward=True,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
grad_x, grad_k, grad_v, grad_w_partial = engram_gate_bwd(
|
| 89 |
+
grad_out, x_data, k_data, v_data, weight_fused,
|
| 90 |
+
dot_ref, gate_score_ref, rstd_x_ref, rstd_k_ref, clamp_value,
|
| 91 |
+
)
|
| 92 |
+
grad_w_fused = grad_w_partial.sum(0)
|
| 93 |
+
grad_wh = grad_w_fused * we_data.float()
|
| 94 |
+
grad_we = grad_w_fused * wh_data.float()
|
| 95 |
+
|
| 96 |
+
func_bwd = lambda: engram_gate_bwd(
|
| 97 |
+
grad_out, x_data, k_data, v_data, weight_fused,
|
| 98 |
+
dot_ref, gate_score_ref, rstd_x_ref, rstd_k_ref, clamp_value,
|
| 99 |
+
)
|
| 100 |
+
t_us = benchmark_timer(func_bwd)
|
| 101 |
+
num_bytes = count_bytes(
|
| 102 |
+
grad_out, x_data, k_data, v_data, weight_fused,
|
| 103 |
+
dot_ref, gate_score_ref, rstd_x_ref, rstd_k_ref,
|
| 104 |
+
grad_x, grad_k, grad_v, grad_wh, grad_we,
|
| 105 |
+
)
|
| 106 |
+
benchmark_record(
|
| 107 |
+
kernel='engram_gate_bwd',
|
| 108 |
+
operation='bwd',
|
| 109 |
+
params=params,
|
| 110 |
+
time_us=t_us,
|
| 111 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 112 |
+
)
|
tile_kernels_src/tests/engram/test_engram_gate_fwd.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from tile_kernels.engram import engram_gate_fwd
|
| 6 |
+
from tile_kernels.torch.engram import engram_gate_ref
|
| 7 |
+
from tile_kernels.testing.numeric import assert_equal, calc_diff, count_bytes
|
| 8 |
+
from tile_kernels.testing.generator import generate_hidden_sizes, generate_num_tokens
|
| 9 |
+
from tile_kernels.testing.bench import make_param_id
|
| 10 |
+
|
| 11 |
+
# Disable TileLang prints
|
| 12 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def generate_test_data(params):
|
| 16 |
+
num_tokens = params['num_tokens']
|
| 17 |
+
hc_mult = params['hc']
|
| 18 |
+
hidden_size = params['hidden']
|
| 19 |
+
eps = 1e-20
|
| 20 |
+
clamp_value = 1e-6
|
| 21 |
+
x_data = torch.randn(num_tokens, hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 22 |
+
k_data = torch.randn(num_tokens, hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 23 |
+
v_data = torch.randn(num_tokens, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 24 |
+
wh_data = torch.randn(hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 25 |
+
we_data = torch.randn(hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 26 |
+
weight_fused = wh_data.float() * we_data.float()
|
| 27 |
+
return (x_data, k_data, v_data, wh_data, we_data, weight_fused, eps, clamp_value)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 31 |
+
return [
|
| 32 |
+
{'num_tokens': t, 'hc': hc, 'hidden': hidden_size}
|
| 33 |
+
for t in generate_num_tokens(is_benchmark=is_benchmark)
|
| 34 |
+
for hc in (4,)
|
| 35 |
+
for hidden_size in generate_hidden_sizes(128)
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 40 |
+
def test_engram_gate_fwd(params):
|
| 41 |
+
(x_data, k_data, v_data, wh_data, we_data, weight_fused, eps, clamp_value) = generate_test_data(params)
|
| 42 |
+
|
| 43 |
+
out_ref, dot_ref, gate_score_ref, rstd_x_ref, rstd_k_ref = engram_gate_ref(
|
| 44 |
+
x_data, k_data, v_data, wh_data, we_data, clamp_value, eps, save_for_backward=True,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# Correctness: save_for_backward=True
|
| 48 |
+
out_save, dot, gate_score, rstd_x, rstd_k = engram_gate_fwd(
|
| 49 |
+
x_data, k_data, v_data, weight_fused, eps, clamp_value, save_for_backward=True,
|
| 50 |
+
)
|
| 51 |
+
assert dot is not None and gate_score is not None and rstd_x is not None and rstd_k is not None
|
| 52 |
+
diff_out = calc_diff(out_save, out_ref)
|
| 53 |
+
assert diff_out < 2e-10, f'out_save mismatch: {diff_out:.6e}'
|
| 54 |
+
diff_dot = calc_diff(dot, dot_ref)
|
| 55 |
+
assert diff_dot < 2e-10, f'dot mismatch: {diff_dot:.6e}'
|
| 56 |
+
diff_gate = calc_diff(gate_score, gate_score_ref)
|
| 57 |
+
assert diff_gate < 2e-10, f'gate_score mismatch: {diff_gate:.6e}'
|
| 58 |
+
diff_rstd_x = calc_diff(rstd_x, rstd_x_ref)
|
| 59 |
+
assert diff_rstd_x < 2e-10, f'rstd_x mismatch: {diff_rstd_x:.6e}'
|
| 60 |
+
diff_rstd_k = calc_diff(rstd_k, rstd_k_ref)
|
| 61 |
+
assert diff_rstd_k < 2e-10, f'rstd_k mismatch: {diff_rstd_k:.6e}'
|
| 62 |
+
|
| 63 |
+
# Correctness: save_for_backward=False
|
| 64 |
+
out_no_save, dot_n, gate_score_n, rstd_x_n, rstd_k_n = engram_gate_fwd(
|
| 65 |
+
x_data, k_data, v_data, weight_fused, eps, clamp_value, save_for_backward=False,
|
| 66 |
+
)
|
| 67 |
+
assert dot_n is None and gate_score_n is None and rstd_x_n is None and rstd_k_n is None
|
| 68 |
+
diff_out = calc_diff(out_no_save, out_ref)
|
| 69 |
+
assert diff_out < 2e-10, f'out_no_save mismatch: {diff_out:.6e}'
|
| 70 |
+
assert_equal(out_no_save, out_save)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@pytest.mark.benchmark
|
| 74 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 75 |
+
def test_engram_gate_fwd_benchmark(benchmark_timer, benchmark_record, params):
|
| 76 |
+
(x_data, k_data, v_data, _, _, weight_fused, eps, clamp_value) = generate_test_data(params)
|
| 77 |
+
|
| 78 |
+
# Benchmark save_for_backward=True
|
| 79 |
+
out_save, dot, gate_score, rstd_x, rstd_k = engram_gate_fwd(
|
| 80 |
+
x_data, k_data, v_data, weight_fused, eps, clamp_value, save_for_backward=True,
|
| 81 |
+
)
|
| 82 |
+
t_save_us = benchmark_timer(lambda: engram_gate_fwd(
|
| 83 |
+
x_data, k_data, v_data, weight_fused, eps, clamp_value, save_for_backward=True,
|
| 84 |
+
))
|
| 85 |
+
num_bytes_save = count_bytes(x_data, k_data, v_data, weight_fused, out_save, dot, gate_score, rstd_x, rstd_k)
|
| 86 |
+
benchmark_record(
|
| 87 |
+
kernel='engram_gate_fwd',
|
| 88 |
+
operation='fwd',
|
| 89 |
+
params={**params, 'save': True},
|
| 90 |
+
time_us=t_save_us,
|
| 91 |
+
bandwidth_gbs=num_bytes_save / t_save_us / 1e3,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
# Benchmark save_for_backward=False
|
| 95 |
+
out_no_save = engram_gate_fwd(
|
| 96 |
+
x_data, k_data, v_data, weight_fused, eps, clamp_value, save_for_backward=False,
|
| 97 |
+
)[0]
|
| 98 |
+
t_no_save_us = benchmark_timer(lambda: engram_gate_fwd(
|
| 99 |
+
x_data, k_data, v_data, weight_fused, eps, clamp_value, save_for_backward=False,
|
| 100 |
+
))
|
| 101 |
+
num_bytes_no_save = count_bytes(x_data, k_data, v_data, weight_fused, out_no_save)
|
| 102 |
+
benchmark_record(
|
| 103 |
+
kernel='engram_gate_fwd',
|
| 104 |
+
operation='fwd',
|
| 105 |
+
params={**params, 'save': False},
|
| 106 |
+
time_us=t_no_save_us,
|
| 107 |
+
bandwidth_gbs=num_bytes_no_save / t_no_save_us / 1e3,
|
| 108 |
+
)
|
tile_kernels_src/tests/engram/test_engram_grad_w_reduce.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from tile_kernels.config import get_num_sms
|
| 6 |
+
from tile_kernels.engram import grad_w_reduce
|
| 7 |
+
from tile_kernels.testing.numeric import calc_diff, count_bytes
|
| 8 |
+
from tile_kernels.testing.generator import generate_hidden_sizes
|
| 9 |
+
from tile_kernels.testing.bench import make_param_id
|
| 10 |
+
|
| 11 |
+
# Disable TileLang prints
|
| 12 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def grad_w_reduce_ref(grad_w_partial, weight_hidden, weight_embed, grad_weight_hidden, grad_weight_embed):
|
| 16 |
+
grad_w_sum = grad_w_partial.sum(0)
|
| 17 |
+
grad_weight_hidden += grad_w_sum * weight_embed.float()
|
| 18 |
+
grad_weight_embed += grad_w_sum * weight_hidden.float()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def generate_test_data(params):
|
| 22 |
+
hidden_size = params['hidden']
|
| 23 |
+
hc_mult = 4
|
| 24 |
+
num_persistent_blocks = get_num_sms()
|
| 25 |
+
grad_w_partial = torch.randn(num_persistent_blocks, hc_mult, hidden_size, dtype=torch.float32, device='cuda')
|
| 26 |
+
weight_hidden = torch.randn(hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 27 |
+
weight_embed = torch.randn(hc_mult, hidden_size, dtype=torch.bfloat16, device='cuda')
|
| 28 |
+
return (grad_w_partial, weight_hidden, weight_embed)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 32 |
+
return [
|
| 33 |
+
{'hidden': hidden_size}
|
| 34 |
+
for hidden_size in generate_hidden_sizes(128)
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 39 |
+
def test_engram_grad_w_reduce(params):
|
| 40 |
+
hidden_size = params['hidden']
|
| 41 |
+
grad_w_partial, weight_hidden, weight_embed = generate_test_data(params)
|
| 42 |
+
hc_mult = grad_w_partial.shape[1]
|
| 43 |
+
|
| 44 |
+
# Correctness
|
| 45 |
+
grad_wh_ref = torch.randn(hc_mult, hidden_size, dtype=torch.float32, device='cuda')
|
| 46 |
+
grad_we_ref = torch.randn(hc_mult, hidden_size, dtype=torch.float32, device='cuda')
|
| 47 |
+
grad_weight_hidden = grad_wh_ref.clone()
|
| 48 |
+
grad_weight_embed = grad_we_ref.clone()
|
| 49 |
+
grad_w_reduce_ref(grad_w_partial, weight_hidden, weight_embed, grad_wh_ref, grad_we_ref)
|
| 50 |
+
grad_w_reduce(grad_w_partial, weight_hidden, weight_embed, grad_weight_hidden, grad_weight_embed)
|
| 51 |
+
diff_wh = calc_diff(grad_weight_hidden, grad_wh_ref)
|
| 52 |
+
assert diff_wh < 1e-10, f'grad_wh mismatch: {diff_wh:.6e}'
|
| 53 |
+
diff_we = calc_diff(grad_weight_embed, grad_we_ref)
|
| 54 |
+
assert diff_we < 1e-10, f'grad_we mismatch: {diff_we:.6e}'
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@pytest.mark.benchmark
|
| 58 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 59 |
+
def test_engram_grad_w_reduce_benchmark(benchmark_timer, benchmark_record, params):
|
| 60 |
+
hidden_size = params['hidden']
|
| 61 |
+
grad_w_partial, weight_hidden, weight_embed = generate_test_data(params)
|
| 62 |
+
hc_mult = grad_w_partial.shape[1]
|
| 63 |
+
grad_weight_hidden = torch.randn(hc_mult, hidden_size, dtype=torch.float32, device='cuda')
|
| 64 |
+
grad_weight_embed = torch.randn(hc_mult, hidden_size, dtype=torch.float32, device='cuda')
|
| 65 |
+
|
| 66 |
+
t_us = benchmark_timer(lambda: grad_w_reduce(grad_w_partial, weight_hidden, weight_embed, grad_weight_hidden, grad_weight_embed))
|
| 67 |
+
|
| 68 |
+
num_bytes = count_bytes(grad_w_partial, weight_hidden, weight_embed, grad_weight_hidden, grad_weight_embed)
|
| 69 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 70 |
+
benchmark_record(
|
| 71 |
+
kernel='grad_w_reduce',
|
| 72 |
+
operation='fwd',
|
| 73 |
+
params=params,
|
| 74 |
+
time_us=t_us,
|
| 75 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 76 |
+
)
|
tile_kernels_src/tests/engram/test_engram_hash.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from tile_kernels.engram import engram_hash
|
| 6 |
+
from tile_kernels.torch.engram import engram_hash_ref, make_offsets
|
| 7 |
+
from tile_kernels.testing.generator import generate_num_tokens
|
| 8 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 9 |
+
from tile_kernels.testing.bench import make_param_id
|
| 10 |
+
|
| 11 |
+
# Disable TileLang prints
|
| 12 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def generate_test_data(params):
|
| 16 |
+
num_tokens = params['num_tokens']
|
| 17 |
+
max_ngram_size = params['ngram']
|
| 18 |
+
num_ngram_layers = params['layers']
|
| 19 |
+
num_embed_table_per_ngram = params['tables']
|
| 20 |
+
ngram_token_ids = torch.randint(0, 100000, (num_tokens, max_ngram_size), dtype=torch.int32, device='cuda')
|
| 21 |
+
multipliers = torch.randint(0, 100000, (num_ngram_layers, max_ngram_size), dtype=torch.int64, device='cuda')
|
| 22 |
+
vocab_sizes = torch.randint(100000, 1000000, (num_ngram_layers, max_ngram_size - 1, num_embed_table_per_ngram), dtype=torch.int32, device='cuda')
|
| 23 |
+
offsets = make_offsets(vocab_sizes)
|
| 24 |
+
return (ngram_token_ids, multipliers, vocab_sizes, offsets)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 28 |
+
return [
|
| 29 |
+
{'num_tokens': t}
|
| 30 |
+
for t in generate_num_tokens(is_benchmark=is_benchmark)
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 35 |
+
def test_engram_hash(params):
|
| 36 |
+
num_tokens = params['num_tokens']
|
| 37 |
+
max_ngram_size = 3
|
| 38 |
+
num_ngram_layers = 2
|
| 39 |
+
num_embed_table_per_ngram = 8
|
| 40 |
+
|
| 41 |
+
ngram_token_ids, multipliers, vocab_sizes, offsets = generate_test_data(
|
| 42 |
+
{'num_tokens': num_tokens, 'ngram': max_ngram_size, 'layers': num_ngram_layers, 'tables': num_embed_table_per_ngram})
|
| 43 |
+
|
| 44 |
+
# Correctness
|
| 45 |
+
output = engram_hash(ngram_token_ids, multipliers, vocab_sizes, offsets)
|
| 46 |
+
output_ref = engram_hash_ref(ngram_token_ids, multipliers, vocab_sizes, offsets)
|
| 47 |
+
assert_equal(output, output_ref)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@pytest.mark.benchmark
|
| 51 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 52 |
+
def test_engram_hash_benchmark(benchmark_timer, benchmark_record, params):
|
| 53 |
+
max_ngram_size = 3
|
| 54 |
+
num_ngram_layers = 2
|
| 55 |
+
num_embed_table_per_ngram = 8
|
| 56 |
+
|
| 57 |
+
ngram_token_ids, multipliers, vocab_sizes, offsets = generate_test_data(
|
| 58 |
+
{**params, 'ngram': max_ngram_size, 'layers': num_ngram_layers, 'tables': num_embed_table_per_ngram})
|
| 59 |
+
output = engram_hash(ngram_token_ids, multipliers, vocab_sizes, offsets)
|
| 60 |
+
|
| 61 |
+
t_us = benchmark_timer(lambda: engram_hash(ngram_token_ids, multipliers, vocab_sizes, offsets))
|
| 62 |
+
|
| 63 |
+
num_bytes = count_bytes(ngram_token_ids, multipliers, vocab_sizes, offsets, output)
|
| 64 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 65 |
+
benchmark_record(
|
| 66 |
+
kernel='engram_hash',
|
| 67 |
+
operation='fwd',
|
| 68 |
+
params={**params, 'ngram': max_ngram_size, 'layers': num_ngram_layers, 'tables': num_embed_table_per_ngram},
|
| 69 |
+
time_us=t_us,
|
| 70 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 71 |
+
)
|
tile_kernels_src/tests/mhc/test_expand.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
from tile_kernels.modeling.mhc.ops import expand_to_mhc
|
| 6 |
+
from tile_kernels.torch.mhc import expand_to_mhc_ref
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def generate_expand_test_data(
|
| 10 |
+
n0: int, n1: int, mhc_mult: int, h: int, device: str = 'cuda'
|
| 11 |
+
) -> dict[str, torch.Tensor]:
|
| 12 |
+
torch.random.manual_seed(42)
|
| 13 |
+
|
| 14 |
+
x = torch.randn(n0, n1, h, dtype=torch.bfloat16, device=device)
|
| 15 |
+
o_grad = torch.randn(n0, n1, mhc_mult, h, dtype=torch.bfloat16, device=device)
|
| 16 |
+
|
| 17 |
+
return {'x': x, 'o_grad': o_grad, 'mhc_mult': mhc_mult}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@pytest.mark.parametrize('n0', [1, 2])
|
| 21 |
+
@pytest.mark.parametrize('n1', [1024, 4096])
|
| 22 |
+
@pytest.mark.parametrize('mhc_mult', [2, 4, 8])
|
| 23 |
+
@pytest.mark.parametrize('h', [1280, 2560, 7168])
|
| 24 |
+
def test_expand_comprehensive(n0: int, n1: int, mhc_mult: int, h: int) -> None:
|
| 25 |
+
test_data = generate_expand_test_data(n0=n0, n1=n1, mhc_mult=mhc_mult, h=h)
|
| 26 |
+
|
| 27 |
+
with torch.no_grad():
|
| 28 |
+
out_tl = expand_to_mhc(test_data['x'], test_data['mhc_mult'])
|
| 29 |
+
out_ref = expand_to_mhc_ref(test_data['x'], test_data['mhc_mult'])
|
| 30 |
+
|
| 31 |
+
torch.testing.assert_close(out_tl, out_ref)
|
| 32 |
+
|
| 33 |
+
def _tester(
|
| 34 |
+
impl: Callable[[torch.Tensor, int], torch.Tensor],
|
| 35 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 36 |
+
x_ = test_data['x'].clone().requires_grad_()
|
| 37 |
+
o_ = impl(x_, test_data['mhc_mult'])
|
| 38 |
+
torch.autograd.backward([o_], [test_data['o_grad']])
|
| 39 |
+
return o_, x_.grad
|
| 40 |
+
|
| 41 |
+
o_tl, x_grad_tl = _tester(expand_to_mhc)
|
| 42 |
+
o_ref, x_grad_ref = _tester(expand_to_mhc_ref)
|
| 43 |
+
|
| 44 |
+
torch.testing.assert_close(o_tl, o_ref)
|
| 45 |
+
torch.testing.assert_close(x_grad_tl, x_grad_ref)
|
tile_kernels_src/tests/mhc/test_head_compute_mix.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
from tile_kernels.modeling.mhc.ops import mhc_head_compute_mix
|
| 6 |
+
from tile_kernels.torch.mhc import mhc_head_compute_mix_ref
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def generate_head_compute_mix_test_data(
|
| 10 |
+
n0: int, n1: int, mhc_mult: int, device: str = 'cuda'
|
| 11 |
+
) -> dict[str, torch.Tensor]:
|
| 12 |
+
input_mix = torch.randn((n0, n1, mhc_mult), dtype=torch.float, device=device)
|
| 13 |
+
mhc_scale = torch.randn(1, dtype=torch.float, device=device)
|
| 14 |
+
mhc_base = torch.randn(mhc_mult, dtype=torch.float, device=device)
|
| 15 |
+
output_mix_grad = torch.randn((n0, n1, mhc_mult), dtype=torch.float, device=device)
|
| 16 |
+
|
| 17 |
+
return {
|
| 18 |
+
'input_mix': input_mix,
|
| 19 |
+
'mhc_scale': mhc_scale,
|
| 20 |
+
'mhc_base': mhc_base,
|
| 21 |
+
'output_mix_grad': output_mix_grad,
|
| 22 |
+
'mhc_pre_eps': 1e-2,
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _tester(
|
| 27 |
+
impl: Callable[[torch.Tensor, torch.Tensor, torch.Tensor, float], torch.Tensor],
|
| 28 |
+
test_data: dict[str, torch.Tensor],
|
| 29 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 30 |
+
input_mix_ = test_data['input_mix'].clone().requires_grad_()
|
| 31 |
+
mhc_scale_ = test_data['mhc_scale'].clone().requires_grad_()
|
| 32 |
+
mhc_base_ = test_data['mhc_base'].clone().requires_grad_()
|
| 33 |
+
output_mix_ = impl(input_mix_, mhc_scale_, mhc_base_, test_data['mhc_pre_eps'])
|
| 34 |
+
torch.autograd.backward([output_mix_], [test_data['output_mix_grad']])
|
| 35 |
+
return output_mix_, input_mix_.grad, mhc_scale_.grad, mhc_base_.grad
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@pytest.mark.parametrize('n0', [1, 2])
|
| 39 |
+
@pytest.mark.parametrize('n1', [1024, 4096])
|
| 40 |
+
@pytest.mark.parametrize('mhc_mult', [4])
|
| 41 |
+
def test_head_compute_mix_comprehensive(n0: int, n1: int, mhc_mult: int) -> None:
|
| 42 |
+
test_data = generate_head_compute_mix_test_data(n0=n0, n1=n1, mhc_mult=mhc_mult)
|
| 43 |
+
|
| 44 |
+
output_mix_tl, grad_input_mix_tl, grad_mhc_scale_tl, grad_mhc_base_tl = _tester(
|
| 45 |
+
mhc_head_compute_mix, test_data
|
| 46 |
+
)
|
| 47 |
+
output_mix_ref, grad_input_mix_ref, grad_mhc_scale_ref, grad_mhc_base_ref = _tester(
|
| 48 |
+
mhc_head_compute_mix_ref, test_data
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
torch.testing.assert_close(output_mix_tl, output_mix_ref, rtol=1e-4, atol=1e-5)
|
| 52 |
+
torch.testing.assert_close(grad_input_mix_tl, grad_input_mix_ref, rtol=1e-4, atol=1e-5)
|
| 53 |
+
torch.testing.assert_close(grad_mhc_scale_tl, grad_mhc_scale_ref, rtol=1e-4, atol=1e-5)
|
| 54 |
+
torch.testing.assert_close(grad_mhc_base_tl, grad_mhc_base_ref, rtol=1e-4, atol=1e-5)
|
tile_kernels_src/tests/mhc/test_multilayer_recompute.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import torch
|
| 3 |
+
from tile_kernels.modeling.mhc.ops.multilayer_recompute import mhc_multilayer_recompute
|
| 4 |
+
from tile_kernels.modeling.mhc.ops.post import mhc_post
|
| 5 |
+
from tile_kernels.modeling.mhc.ops.pre_apply_mix import mhc_pre_apply_mix
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
_CORRECTNESS_CASES = [
|
| 9 |
+
(1, 1, 2560),
|
| 10 |
+
(3, 2, 2560),
|
| 11 |
+
(3, 3, 2560),
|
| 12 |
+
(10, 9, 2560),
|
| 13 |
+
(10, 10, 2560),
|
| 14 |
+
(10, 9, 4096),
|
| 15 |
+
(10, 10, 4096),
|
| 16 |
+
(10, 9, 7168),
|
| 17 |
+
(10, 10, 7168),
|
| 18 |
+
(10, 9, 8192),
|
| 19 |
+
(10, 10, 8192),
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
_BENCH_CASES = [
|
| 23 |
+
(10, 9, 1, 8192, 4, 2560),
|
| 24 |
+
(10, 10, 1, 8192, 4, 2560),
|
| 25 |
+
(10, 9, 1, 8192, 4, 4096),
|
| 26 |
+
(10, 10, 1, 8192, 4, 4096),
|
| 27 |
+
(10, 9, 1, 8192, 4, 7168),
|
| 28 |
+
(10, 10, 1, 8192, 4, 7168),
|
| 29 |
+
(10, 9, 1, 8192, 4, 8192),
|
| 30 |
+
(10, 10, 1, 8192, 4, 8192),
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def generate_multilayer_recompute_test_data(
|
| 35 |
+
bs: int,
|
| 36 |
+
seq: int,
|
| 37 |
+
mhc_mult: int,
|
| 38 |
+
hidden: int,
|
| 39 |
+
num_layers: int,
|
| 40 |
+
num_post: int,
|
| 41 |
+
) -> tuple[
|
| 42 |
+
torch.Tensor,
|
| 43 |
+
list[torch.Tensor],
|
| 44 |
+
list[torch.Tensor],
|
| 45 |
+
list[torch.Tensor],
|
| 46 |
+
list[torch.Tensor],
|
| 47 |
+
list[torch.Tensor],
|
| 48 |
+
list[torch.Tensor],
|
| 49 |
+
]:
|
| 50 |
+
initial_residual = torch.randn(bs, seq, mhc_mult, hidden, device='cuda', dtype=torch.bfloat16)
|
| 51 |
+
pre_mix_list = [torch.randn(bs, seq, mhc_mult, 1, device='cuda', dtype=torch.float32) for _ in range(num_layers)]
|
| 52 |
+
layer_output_list = [torch.randn(bs, seq, hidden, device='cuda', dtype=torch.bfloat16) for _ in range(num_post)]
|
| 53 |
+
post_mix_list = [torch.randn(bs, seq, mhc_mult, 1, device='cuda', dtype=torch.float32) for _ in range(num_post)]
|
| 54 |
+
comb_mix_list = [torch.randn(bs, seq, mhc_mult, mhc_mult, device='cuda', dtype=torch.float32) for _ in range(num_post)]
|
| 55 |
+
layer_input_list = [torch.empty(bs, seq, hidden, device='cuda', dtype=torch.bfloat16) for _ in range(num_layers)]
|
| 56 |
+
residual_list = [torch.empty(bs, seq, mhc_mult, hidden, device='cuda', dtype=torch.bfloat16) for _ in range(num_post)]
|
| 57 |
+
return initial_residual, pre_mix_list, layer_output_list, post_mix_list, comb_mix_list, layer_input_list, residual_list
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _mhc_multilayer_recompute_ref(
|
| 61 |
+
initial_residual: torch.Tensor,
|
| 62 |
+
pre_mix_list: list[torch.Tensor],
|
| 63 |
+
layer_output_list: list[torch.Tensor],
|
| 64 |
+
post_mix_list: list[torch.Tensor],
|
| 65 |
+
comb_mix_list: list[torch.Tensor],
|
| 66 |
+
) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
|
| 67 |
+
layer_input_refs: list[torch.Tensor] = []
|
| 68 |
+
residual_refs: list[torch.Tensor] = []
|
| 69 |
+
residual = initial_residual
|
| 70 |
+
for i in range(len(pre_mix_list)):
|
| 71 |
+
layer_input = mhc_pre_apply_mix(residual, pre_mix_list[i])
|
| 72 |
+
layer_input_refs.append(layer_input)
|
| 73 |
+
if i < len(layer_output_list):
|
| 74 |
+
residual = mhc_post(layer_output_list[i], residual, post_mix_list[i], comb_mix_list[i])
|
| 75 |
+
residual_refs.append(residual)
|
| 76 |
+
return layer_input_refs, residual_refs
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _compute_io_bytes(n: int, mhc_mult: int, hidden: int, num_layers: int, num_post: int) -> tuple[int, int]:
|
| 80 |
+
io_pre = n * mhc_mult * hidden * 2 + n * mhc_mult * 4 + n * hidden * 2
|
| 81 |
+
io_post = n * hidden * 2 + n * mhc_mult * hidden * 2 + n * mhc_mult * 4 + n * mhc_mult * mhc_mult * 4 + n * mhc_mult * hidden * 2
|
| 82 |
+
io_ref = num_layers * io_pre + num_post * io_post
|
| 83 |
+
io_fused = (
|
| 84 |
+
n * mhc_mult * hidden * 2
|
| 85 |
+
+ num_layers * (n * mhc_mult * 4 + n * hidden * 2)
|
| 86 |
+
+ num_post * (n * hidden * 2 + n * mhc_mult * 4 + n * mhc_mult * mhc_mult * 4 + n * mhc_mult * hidden * 2)
|
| 87 |
+
)
|
| 88 |
+
return io_ref, io_fused
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@pytest.mark.parametrize('num_layers,num_post,hidden', _CORRECTNESS_CASES)
|
| 92 |
+
def test_mhc_multilayer_recompute_correctness(num_layers: int, num_post: int, hidden: int) -> None:
|
| 93 |
+
torch.manual_seed(0)
|
| 94 |
+
initial_residual, pre_mix_list, layer_output_list, post_mix_list, comb_mix_list, layer_input_list, residual_list = (
|
| 95 |
+
generate_multilayer_recompute_test_data(1, 8192, 4, hidden, num_layers, num_post)
|
| 96 |
+
)
|
| 97 |
+
layer_input_ref, residual_ref = _mhc_multilayer_recompute_ref(initial_residual, pre_mix_list, layer_output_list, post_mix_list, comb_mix_list)
|
| 98 |
+
mhc_multilayer_recompute(initial_residual, pre_mix_list, layer_output_list, post_mix_list, comb_mix_list, layer_input_list, residual_list)
|
| 99 |
+
|
| 100 |
+
for i in range(num_layers):
|
| 101 |
+
assert torch.equal(layer_input_list[i], layer_input_ref[i]), (
|
| 102 |
+
f'layer_input[{i}] mismatch! max diff = {(layer_input_list[i].float() - layer_input_ref[i].float()).abs().max().item()}'
|
| 103 |
+
)
|
| 104 |
+
for i in range(num_post):
|
| 105 |
+
assert torch.equal(residual_list[i], residual_ref[i]), (
|
| 106 |
+
f'residual[{i}] mismatch! max diff = {(residual_list[i].float() - residual_ref[i].float()).abs().max().item()}'
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@pytest.mark.benchmark
|
| 111 |
+
@pytest.mark.parametrize('num_layers,num_post,bs,seq,mhc_mult,hidden', _BENCH_CASES)
|
| 112 |
+
def test_mhc_multilayer_recompute_benchmark(
|
| 113 |
+
num_layers: int,
|
| 114 |
+
num_post: int,
|
| 115 |
+
bs: int,
|
| 116 |
+
seq: int,
|
| 117 |
+
mhc_mult: int,
|
| 118 |
+
hidden: int,
|
| 119 |
+
benchmark_record,
|
| 120 |
+
benchmark_timer,
|
| 121 |
+
) -> None:
|
| 122 |
+
torch.manual_seed(0)
|
| 123 |
+
n = bs * seq
|
| 124 |
+
io_ref, io_fused = _compute_io_bytes(n, mhc_mult, hidden, num_layers, num_post)
|
| 125 |
+
theory = io_ref / io_fused
|
| 126 |
+
initial_residual, pre_mix_list, layer_output_list, post_mix_list, comb_mix_list, layer_input_list, residual_list = (
|
| 127 |
+
generate_multilayer_recompute_test_data(bs, seq, mhc_mult, hidden, num_layers, num_post)
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
def fn_ref() -> tuple[list[torch.Tensor], list[torch.Tensor]]:
|
| 131 |
+
return _mhc_multilayer_recompute_ref(initial_residual, pre_mix_list, layer_output_list, post_mix_list, comb_mix_list)
|
| 132 |
+
|
| 133 |
+
def fn_fused() -> None:
|
| 134 |
+
mhc_multilayer_recompute(initial_residual, pre_mix_list, layer_output_list, post_mix_list, comb_mix_list, layer_input_list, residual_list)
|
| 135 |
+
|
| 136 |
+
fn_ref()
|
| 137 |
+
fn_fused()
|
| 138 |
+
t_ref_us = benchmark_timer(fn_ref)
|
| 139 |
+
t_fused_us = benchmark_timer(fn_fused)
|
| 140 |
+
speedup = t_ref_us / t_fused_us
|
| 141 |
+
bw_ref_gbs = io_ref / t_ref_us / 1e3
|
| 142 |
+
bw_fused_gbs = io_fused / t_fused_us / 1e3
|
| 143 |
+
|
| 144 |
+
benchmark_record(
|
| 145 |
+
kernel='mhc_multilayer_recompute',
|
| 146 |
+
operation='recompute',
|
| 147 |
+
params={'num_layers': num_layers, 'num_post': num_post, 'bs': bs, 'seq': seq, 'mhc_mult': mhc_mult, 'hidden': hidden},
|
| 148 |
+
time_us=t_fused_us,
|
| 149 |
+
bandwidth_gbs=bw_fused_gbs,
|
| 150 |
+
extras={
|
| 151 |
+
'ref_time_us': t_ref_us,
|
| 152 |
+
'speedup': speedup,
|
| 153 |
+
'bw_ref_gbs': bw_ref_gbs,
|
| 154 |
+
'theory': theory,
|
| 155 |
+
'efficiency': speedup / theory,
|
| 156 |
+
},
|
| 157 |
+
)
|
tile_kernels_src/tests/mhc/test_norm_fn.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import torch
|
| 3 |
+
from tile_kernels.modeling.mhc.ops import mhc_pre_norm_fn
|
| 4 |
+
from tile_kernels.torch.mhc import mhc_pre_norm_fn_ref
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def generate_norm_fn_test_data(
|
| 8 |
+
n1: int,
|
| 9 |
+
mhc_mult: int,
|
| 10 |
+
hidden_size: int,
|
| 11 |
+
generate_normw: bool,
|
| 12 |
+
) -> dict[str, torch.Tensor]:
|
| 13 |
+
n0 = 1
|
| 14 |
+
mhc_mult3 = mhc_mult * (2 + mhc_mult)
|
| 15 |
+
mhc_hidden_size = mhc_mult * hidden_size
|
| 16 |
+
device = 'cuda'
|
| 17 |
+
|
| 18 |
+
residual = (
|
| 19 |
+
torch.randn((n0, n1, mhc_mult, hidden_size), dtype=torch.float, device=device)
|
| 20 |
+
.mul(1 + torch.arange(mhc_mult, device=device).mul(0.01).view(1, 1, -1, 1))
|
| 21 |
+
.bfloat16()
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
fn = (
|
| 25 |
+
torch.randn((mhc_mult3, mhc_mult, hidden_size), dtype=torch.float, device=device)
|
| 26 |
+
* 1e-4
|
| 27 |
+
* (1 + torch.arange(mhc_mult, device=device).mul(0.01).view(1, -1, 1))
|
| 28 |
+
).flatten(1, 2)
|
| 29 |
+
|
| 30 |
+
if generate_normw:
|
| 31 |
+
normw = torch.randn((mhc_hidden_size,), dtype=torch.float, device=device) * 0.1 + 1.0
|
| 32 |
+
else:
|
| 33 |
+
normw = None
|
| 34 |
+
|
| 35 |
+
out_grad = torch.randn((n0, n1, mhc_mult3), dtype=torch.float, device=device)
|
| 36 |
+
|
| 37 |
+
return {
|
| 38 |
+
'residual': residual,
|
| 39 |
+
'fn': fn,
|
| 40 |
+
'normw': normw,
|
| 41 |
+
'out_grad': out_grad,
|
| 42 |
+
'mhc_norm_eps': 1e-6,
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@pytest.mark.parametrize('n1', [4096, 8192])
|
| 47 |
+
@pytest.mark.parametrize('hidden_size', [1280, 2560, 7168])
|
| 48 |
+
@pytest.mark.parametrize('generate_normw', [False, True])
|
| 49 |
+
def test_correctness(
|
| 50 |
+
n1: int,
|
| 51 |
+
hidden_size: int,
|
| 52 |
+
generate_normw: bool,
|
| 53 |
+
) -> None:
|
| 54 |
+
mhc_mult = 4
|
| 55 |
+
|
| 56 |
+
test_data = generate_norm_fn_test_data(
|
| 57 |
+
n1=n1,
|
| 58 |
+
mhc_mult=mhc_mult,
|
| 59 |
+
hidden_size=hidden_size,
|
| 60 |
+
generate_normw=generate_normw,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
residual_tl = test_data['residual'].clone().requires_grad_()
|
| 64 |
+
fn_tl = test_data['fn'].clone().requires_grad_()
|
| 65 |
+
normw_tl = test_data['normw'].clone().requires_grad_() if test_data['normw'] is not None else None
|
| 66 |
+
|
| 67 |
+
residual_ref = test_data['residual'].clone().requires_grad_()
|
| 68 |
+
fn_ref = test_data['fn'].clone().requires_grad_()
|
| 69 |
+
normw_ref = test_data['normw'].clone().requires_grad_() if test_data['normw'] is not None else None
|
| 70 |
+
|
| 71 |
+
out_tl = mhc_pre_norm_fn(
|
| 72 |
+
residual_tl,
|
| 73 |
+
fn_tl,
|
| 74 |
+
normw_tl,
|
| 75 |
+
test_data['mhc_norm_eps'],
|
| 76 |
+
)
|
| 77 |
+
residual_tl_grad = residual_tl.untyped_storage().grad_from_mhc_post = torch.zeros_like(residual_tl)
|
| 78 |
+
torch.autograd.backward([out_tl], [test_data['out_grad']])
|
| 79 |
+
|
| 80 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 81 |
+
out_ref = mhc_pre_norm_fn_ref(
|
| 82 |
+
residual_ref,
|
| 83 |
+
fn_ref,
|
| 84 |
+
normw_ref,
|
| 85 |
+
test_data['mhc_norm_eps'],
|
| 86 |
+
)
|
| 87 |
+
torch.autograd.backward([out_ref], [test_data['out_grad']])
|
| 88 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 89 |
+
|
| 90 |
+
torch.testing.assert_close(out_tl, out_ref, atol=1e-3, rtol=1e-3)
|
| 91 |
+
torch.testing.assert_close(residual_tl_grad, residual_ref.grad)
|
| 92 |
+
torch.testing.assert_close(fn_tl.grad, fn_ref.grad, atol=3e-2, rtol=1e-3)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@pytest.mark.parametrize('n1', [13, 48, 512])
|
| 96 |
+
@pytest.mark.parametrize('hidden_size', [1280, 2560, 4096, 7168])
|
| 97 |
+
def test_split_k_correctness(n1: int, hidden_size: int) -> None:
|
| 98 |
+
mhc_mult = 4
|
| 99 |
+
|
| 100 |
+
test_data = generate_norm_fn_test_data(
|
| 101 |
+
n1=n1,
|
| 102 |
+
mhc_mult=mhc_mult,
|
| 103 |
+
hidden_size=hidden_size,
|
| 104 |
+
generate_normw=False,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
residual_tl = test_data['residual'].clone().requires_grad_()
|
| 108 |
+
fn_tl = test_data['fn'].clone().requires_grad_()
|
| 109 |
+
|
| 110 |
+
residual_ref = test_data['residual'].clone().requires_grad_()
|
| 111 |
+
fn_ref = test_data['fn'].clone().requires_grad_()
|
| 112 |
+
|
| 113 |
+
out_tl = mhc_pre_norm_fn(
|
| 114 |
+
residual_tl,
|
| 115 |
+
fn_tl,
|
| 116 |
+
None,
|
| 117 |
+
test_data['mhc_norm_eps'],
|
| 118 |
+
n_splits=16,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 122 |
+
out_ref = mhc_pre_norm_fn_ref(
|
| 123 |
+
residual_ref,
|
| 124 |
+
fn_ref,
|
| 125 |
+
None,
|
| 126 |
+
test_data['mhc_norm_eps'],
|
| 127 |
+
)
|
| 128 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 129 |
+
|
| 130 |
+
torch.testing.assert_close(out_tl, out_ref, atol=1e-3, rtol=1e-3)
|
tile_kernels_src/tests/mhc/test_post.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
from tile_kernels.modeling.mhc.ops import mhc_post
|
| 6 |
+
from tile_kernels.torch.mhc import mhc_post_ref
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def generate_mhc_post_test_data(
|
| 10 |
+
n0: int,
|
| 11 |
+
n1: int,
|
| 12 |
+
h: int,
|
| 13 |
+
mhc_mult: int,
|
| 14 |
+
device: str = 'cuda',
|
| 15 |
+
) -> dict[str, torch.Tensor]:
|
| 16 |
+
x = torch.randn((n0, n1, h), dtype=torch.bfloat16, device=device)
|
| 17 |
+
residual = torch.randn((n0, n1, mhc_mult, h), dtype=torch.bfloat16, device=device)
|
| 18 |
+
post_layer_mix = torch.randn((n0, n1, mhc_mult, 1), dtype=torch.float32, device=device)
|
| 19 |
+
comb_res_mix = torch.randn((n0, n1, mhc_mult, mhc_mult), dtype=torch.float32, device=device)
|
| 20 |
+
|
| 21 |
+
o_grad = torch.randn((n0, n1, mhc_mult, h), dtype=torch.bfloat16, device=device)
|
| 22 |
+
|
| 23 |
+
return {
|
| 24 |
+
'x': x,
|
| 25 |
+
'residual': residual,
|
| 26 |
+
'post_layer_mix': post_layer_mix,
|
| 27 |
+
'comb_res_mix': comb_res_mix,
|
| 28 |
+
'o_grad': o_grad,
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _tester(
|
| 33 |
+
impl: Callable[[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor], torch.Tensor],
|
| 34 |
+
test_data: dict[str, torch.Tensor],
|
| 35 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 36 |
+
x_ = test_data['x'].clone().requires_grad_()
|
| 37 |
+
residual_ = test_data['residual'].clone().requires_grad_()
|
| 38 |
+
post_layer_mix_ = test_data['post_layer_mix'].clone().requires_grad_()
|
| 39 |
+
comb_res_mix_ = test_data['comb_res_mix'].clone().requires_grad_()
|
| 40 |
+
out_ = impl(x_, residual_, post_layer_mix_, comb_res_mix_)
|
| 41 |
+
torch.autograd.backward([out_], [test_data['o_grad']])
|
| 42 |
+
return out_, x_.grad, residual_.grad, post_layer_mix_.grad, comb_res_mix_.grad
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@pytest.mark.parametrize('n0', [1, 2])
|
| 46 |
+
@pytest.mark.parametrize('n1', [4096])
|
| 47 |
+
@pytest.mark.parametrize('h', [1280, 2560, 7168])
|
| 48 |
+
def test_mhc_post_comprehensive(n0: int, n1: int, h: int) -> None:
|
| 49 |
+
test_data = generate_mhc_post_test_data(n0=n0, n1=n1, h=h, mhc_mult=4)
|
| 50 |
+
|
| 51 |
+
out_tl, grad_x_tl, grad_residual_tl, grad_post_layer_mix_tl, grad_comb_res_mix_tl = _tester(
|
| 52 |
+
mhc_post, test_data
|
| 53 |
+
)
|
| 54 |
+
out_ref, grad_x_ref, grad_residual_ref, grad_post_layer_mix_ref, grad_comb_res_mix_ref = _tester(
|
| 55 |
+
mhc_post_ref, test_data
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
torch.testing.assert_close(out_tl, out_ref)
|
| 59 |
+
torch.testing.assert_close(grad_x_tl, grad_x_ref)
|
| 60 |
+
torch.testing.assert_close(grad_residual_tl, grad_residual_ref)
|
| 61 |
+
torch.testing.assert_close(
|
| 62 |
+
grad_post_layer_mix_tl,
|
| 63 |
+
grad_post_layer_mix_ref,
|
| 64 |
+
atol=1e-4,
|
| 65 |
+
rtol=1e-4,
|
| 66 |
+
)
|
| 67 |
+
torch.testing.assert_close(
|
| 68 |
+
grad_comb_res_mix_tl,
|
| 69 |
+
grad_comb_res_mix_ref,
|
| 70 |
+
atol=1e-4,
|
| 71 |
+
rtol=1e-4,
|
| 72 |
+
)
|
tile_kernels_src/tests/mhc/test_pre_apply_mix.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
from tile_kernels.modeling.mhc.ops import mhc_pre_apply_mix
|
| 6 |
+
from tile_kernels.torch.mhc import mhc_pre_apply_mix_ref
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def generate_pre_apply_mix_test_data(
|
| 10 |
+
n0: int, n1: int, mhc: int, h: int, device: str = 'cuda'
|
| 11 |
+
) -> dict[str, torch.Tensor]:
|
| 12 |
+
x = torch.randn(n0, n1, mhc, h, dtype=torch.bfloat16, device=device).sigmoid()
|
| 13 |
+
mix = torch.randn(n0, n1, mhc, 1, dtype=torch.float32, device=device).softmax(-2)
|
| 14 |
+
o_grad = torch.randn(n0, n1, h, dtype=torch.bfloat16, device=device)
|
| 15 |
+
|
| 16 |
+
return {
|
| 17 |
+
'x': x,
|
| 18 |
+
'mix': mix,
|
| 19 |
+
'o_grad': o_grad,
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _tester(
|
| 24 |
+
impl: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
|
| 25 |
+
test_data: dict[str, torch.Tensor],
|
| 26 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 27 |
+
x_ = test_data['x'].clone().requires_grad_()
|
| 28 |
+
mix_ = test_data['mix'].clone().requires_grad_()
|
| 29 |
+
o_ = impl(x_, mix_)
|
| 30 |
+
x_.untyped_storage().grad_from_mhc_post = torch.zeros_like(x_)
|
| 31 |
+
torch.autograd.backward([o_], [test_data['o_grad']])
|
| 32 |
+
return (
|
| 33 |
+
o_,
|
| 34 |
+
x_.untyped_storage().grad_from_mhc_post if x_.grad is None else x_.grad,
|
| 35 |
+
mix_.grad,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.parametrize('n0', [1, 2])
|
| 40 |
+
@pytest.mark.parametrize('n1', [1024, 4096])
|
| 41 |
+
@pytest.mark.parametrize('h', [1280, 2560, 7680])
|
| 42 |
+
def test_pre_apply_mix_comprehensive(n0: int, n1: int, h: int) -> None:
|
| 43 |
+
mhc = 4
|
| 44 |
+
|
| 45 |
+
test_data = generate_pre_apply_mix_test_data(n0=n0, n1=n1, mhc=mhc, h=h)
|
| 46 |
+
|
| 47 |
+
o_tl, x_grad_tl, mix_grad_tl = _tester(mhc_pre_apply_mix, test_data)
|
| 48 |
+
o_ref, x_grad_ref, mix_grad_ref = _tester(mhc_pre_apply_mix_ref, test_data)
|
| 49 |
+
|
| 50 |
+
torch.testing.assert_close(o_tl, o_ref, atol=1e-2, rtol=1e-3)
|
| 51 |
+
torch.testing.assert_close(x_grad_tl, x_grad_ref, atol=1e-2, rtol=1e-3)
|
| 52 |
+
torch.testing.assert_close(mix_grad_tl, mix_grad_ref, atol=1e-2, rtol=1e-3)
|
tile_kernels_src/tests/mhc/test_pre_big_fuse.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import torch
|
| 3 |
+
from tile_kernels.modeling.mhc.ops import (
|
| 4 |
+
mhc_pre_apply_mix,
|
| 5 |
+
mhc_pre_big_fuse,
|
| 6 |
+
mhc_pre_norm_fn,
|
| 7 |
+
mhc_pre_split_mixes,
|
| 8 |
+
sinkhorn_normalize,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def generate_big_fuse_test_data(
|
| 13 |
+
n1: int,
|
| 14 |
+
mhc_mult: int,
|
| 15 |
+
hidden_size: int,
|
| 16 |
+
rms_eps: float = 1e-6,
|
| 17 |
+
mhc_pre_eps: float = 1e-6,
|
| 18 |
+
mhc_sinkhorn_eps: float = 1e-6,
|
| 19 |
+
mhc_post_mult_value: float = 1.0,
|
| 20 |
+
sinkhorn_repeat: int = 10,
|
| 21 |
+
n_splits: int = 16,
|
| 22 |
+
) -> dict[str, torch.Tensor | float]:
|
| 23 |
+
n0 = 1
|
| 24 |
+
mhc_mult2 = mhc_mult * mhc_mult
|
| 25 |
+
mhc_mult3 = mhc_mult * 2 + mhc_mult2
|
| 26 |
+
device = 'cuda'
|
| 27 |
+
|
| 28 |
+
residual = (
|
| 29 |
+
torch.randn((n0, n1, mhc_mult, hidden_size), dtype=torch.float, device=device)
|
| 30 |
+
.mul(1 + torch.arange(mhc_mult, device=device).mul(0.01).view(1, 1, -1, 1))
|
| 31 |
+
.bfloat16()
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
fn = (
|
| 35 |
+
torch.randn((mhc_mult3, mhc_mult, hidden_size), dtype=torch.float, device=device)
|
| 36 |
+
* 1e-4
|
| 37 |
+
* (1 + torch.arange(mhc_mult, device=device).mul(0.01).view(1, -1, 1))
|
| 38 |
+
).flatten(1, 2)
|
| 39 |
+
|
| 40 |
+
mhc_scale = torch.randn((3,), dtype=torch.float, device=device) * 0.1
|
| 41 |
+
mhc_base = torch.randn((mhc_mult3,), dtype=torch.float, device=device) * 0.1
|
| 42 |
+
|
| 43 |
+
return {
|
| 44 |
+
'residual': residual,
|
| 45 |
+
'fn': fn,
|
| 46 |
+
'mhc_scale': mhc_scale,
|
| 47 |
+
'mhc_base': mhc_base,
|
| 48 |
+
'rms_eps': rms_eps,
|
| 49 |
+
'mhc_pre_eps': mhc_pre_eps,
|
| 50 |
+
'mhc_sinkhorn_eps': mhc_sinkhorn_eps,
|
| 51 |
+
'mhc_post_mult_value': mhc_post_mult_value,
|
| 52 |
+
'sinkhorn_repeat': sinkhorn_repeat,
|
| 53 |
+
'n_splits': n_splits,
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def big_fuse_reference(
|
| 58 |
+
residual: torch.Tensor,
|
| 59 |
+
fn: torch.Tensor,
|
| 60 |
+
mhc_scale: torch.Tensor,
|
| 61 |
+
mhc_base: torch.Tensor,
|
| 62 |
+
rms_eps: float,
|
| 63 |
+
mhc_pre_eps: float,
|
| 64 |
+
mhc_sinkhorn_eps: float,
|
| 65 |
+
mhc_post_mult_value: float,
|
| 66 |
+
sinkhorn_repeat: int,
|
| 67 |
+
n_splits: int,
|
| 68 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 69 |
+
mhc_mult = residual.shape[-2]
|
| 70 |
+
|
| 71 |
+
mixes = mhc_pre_norm_fn(
|
| 72 |
+
residual,
|
| 73 |
+
fn,
|
| 74 |
+
None,
|
| 75 |
+
rms_eps,
|
| 76 |
+
fuse_grad_acc=False,
|
| 77 |
+
n_splits=n_splits,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
pre_mix, post_mix, comb_mix = mhc_pre_split_mixes(
|
| 81 |
+
mixes,
|
| 82 |
+
mhc_scale,
|
| 83 |
+
mhc_base,
|
| 84 |
+
mhc_mult,
|
| 85 |
+
mhc_post_mult_value,
|
| 86 |
+
mhc_pre_eps,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
comb_mix = sinkhorn_normalize(comb_mix, repeat=sinkhorn_repeat, eps=mhc_sinkhorn_eps)
|
| 90 |
+
|
| 91 |
+
layer_input = mhc_pre_apply_mix(residual, pre_mix)
|
| 92 |
+
|
| 93 |
+
return post_mix, comb_mix, layer_input
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@pytest.mark.parametrize('n1', [512, 1024, 2048, 8192])
|
| 97 |
+
@pytest.mark.parametrize('hidden_size', [1280, 2560, 4096])
|
| 98 |
+
@pytest.mark.parametrize('mhc_mult', [4])
|
| 99 |
+
def test_correctness(
|
| 100 |
+
n1: int,
|
| 101 |
+
hidden_size: int,
|
| 102 |
+
mhc_mult: int,
|
| 103 |
+
) -> None:
|
| 104 |
+
test_data = generate_big_fuse_test_data(
|
| 105 |
+
n1=n1,
|
| 106 |
+
mhc_mult=mhc_mult,
|
| 107 |
+
hidden_size=hidden_size,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
post_mix_fused, comb_mix_fused, layer_input_fused = mhc_pre_big_fuse(
|
| 111 |
+
test_data['residual'],
|
| 112 |
+
test_data['fn'],
|
| 113 |
+
test_data['mhc_scale'],
|
| 114 |
+
test_data['mhc_base'],
|
| 115 |
+
rms_eps=test_data['rms_eps'],
|
| 116 |
+
mhc_pre_eps=test_data['mhc_pre_eps'],
|
| 117 |
+
mhc_sinkhorn_eps=test_data['mhc_sinkhorn_eps'],
|
| 118 |
+
mhc_post_mult_value=test_data['mhc_post_mult_value'],
|
| 119 |
+
sinkhorn_repeat=test_data['sinkhorn_repeat'],
|
| 120 |
+
n_splits=test_data['n_splits'],
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
post_mix_ref, comb_mix_ref, layer_input_ref = big_fuse_reference(
|
| 124 |
+
test_data['residual'],
|
| 125 |
+
test_data['fn'],
|
| 126 |
+
test_data['mhc_scale'],
|
| 127 |
+
test_data['mhc_base'],
|
| 128 |
+
test_data['rms_eps'],
|
| 129 |
+
test_data['mhc_pre_eps'],
|
| 130 |
+
test_data['mhc_sinkhorn_eps'],
|
| 131 |
+
test_data['mhc_post_mult_value'],
|
| 132 |
+
test_data['sinkhorn_repeat'],
|
| 133 |
+
test_data['n_splits'],
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
assert torch.equal(post_mix_fused, post_mix_ref)
|
| 137 |
+
assert torch.equal(comb_mix_fused, comb_mix_ref)
|
| 138 |
+
assert torch.equal(layer_input_fused, layer_input_ref)
|
tile_kernels_src/tests/mhc/test_pre_split_mixes.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
from tile_kernels.modeling.mhc.ops import mhc_pre_split_mixes
|
| 6 |
+
from tile_kernels.torch.mhc import mhc_pre_split_mixes_ref
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def generate_pre_split_mixes_test_data(
|
| 10 |
+
n0: int, n1: int, mhc_mult: int, device: str = 'cuda'
|
| 11 |
+
) -> dict[str, torch.Tensor]:
|
| 12 |
+
mhc_mult3 = mhc_mult * 2 + mhc_mult * mhc_mult
|
| 13 |
+
|
| 14 |
+
input_mixes = torch.randn((n0, n1, mhc_mult3), dtype=torch.float, device=device)
|
| 15 |
+
mhc_scale = torch.randn((3,), dtype=torch.float, device=device)
|
| 16 |
+
mhc_base = torch.randn((mhc_mult3,), dtype=torch.float, device=device)
|
| 17 |
+
|
| 18 |
+
pre_layer_mix_grad = torch.randn((n0, n1, mhc_mult, 1), dtype=torch.float, device=device)
|
| 19 |
+
post_layer_mix_grad = torch.randn((n0, n1, mhc_mult, 1), dtype=torch.float, device=device)
|
| 20 |
+
comb_res_mix_grad = torch.randn((n0, n1, mhc_mult, mhc_mult), dtype=torch.float, device=device)
|
| 21 |
+
|
| 22 |
+
return {
|
| 23 |
+
'input_mixes': input_mixes,
|
| 24 |
+
'mhc_scale': mhc_scale,
|
| 25 |
+
'mhc_base': mhc_base,
|
| 26 |
+
'pre_layer_mix_grad': pre_layer_mix_grad,
|
| 27 |
+
'post_layer_mix_grad': post_layer_mix_grad,
|
| 28 |
+
'comb_res_mix_grad': comb_res_mix_grad,
|
| 29 |
+
'mhc_post_mult_value': 2.0,
|
| 30 |
+
'mhc_pre_eps': 1e-2,
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _tester(
|
| 35 |
+
impl: Callable[
|
| 36 |
+
[torch.Tensor, torch.Tensor, torch.Tensor, int, float, float],
|
| 37 |
+
tuple[torch.Tensor, torch.Tensor, torch.Tensor],
|
| 38 |
+
],
|
| 39 |
+
test_data: dict[str, torch.Tensor],
|
| 40 |
+
mhc_mult: int,
|
| 41 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 42 |
+
input_mixes_ = test_data['input_mixes'].clone().requires_grad_()
|
| 43 |
+
mhc_scale_ = test_data['mhc_scale'].clone().requires_grad_()
|
| 44 |
+
mhc_base_ = test_data['mhc_base'].clone().requires_grad_()
|
| 45 |
+
|
| 46 |
+
pre_layer_mix_, post_layer_mix_, comb_res_mix_ = impl(
|
| 47 |
+
input_mixes_,
|
| 48 |
+
mhc_scale_,
|
| 49 |
+
mhc_base_,
|
| 50 |
+
mhc_mult,
|
| 51 |
+
test_data['mhc_post_mult_value'],
|
| 52 |
+
test_data['mhc_pre_eps'],
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
torch.autograd.backward(
|
| 56 |
+
[pre_layer_mix_, post_layer_mix_, comb_res_mix_],
|
| 57 |
+
[
|
| 58 |
+
test_data['pre_layer_mix_grad'],
|
| 59 |
+
test_data['post_layer_mix_grad'],
|
| 60 |
+
test_data['comb_res_mix_grad'],
|
| 61 |
+
],
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
return (
|
| 65 |
+
pre_layer_mix_,
|
| 66 |
+
post_layer_mix_,
|
| 67 |
+
comb_res_mix_,
|
| 68 |
+
input_mixes_.grad,
|
| 69 |
+
mhc_scale_.grad,
|
| 70 |
+
mhc_base_.grad,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@pytest.mark.parametrize('n0', [1, 2])
|
| 75 |
+
@pytest.mark.parametrize('n1', [1024, 4096])
|
| 76 |
+
@pytest.mark.parametrize('mhc_mult', [4])
|
| 77 |
+
def test_pre_split_mixes_comprehensive(n0: int, n1: int, mhc_mult: int) -> None:
|
| 78 |
+
test_data = generate_pre_split_mixes_test_data(n0=n0, n1=n1, mhc_mult=mhc_mult)
|
| 79 |
+
|
| 80 |
+
(
|
| 81 |
+
pre_layer_mix_tl,
|
| 82 |
+
post_layer_mix_tl,
|
| 83 |
+
comb_res_mix_tl,
|
| 84 |
+
grad_input_mixes_tl,
|
| 85 |
+
grad_mhc_scale_tl,
|
| 86 |
+
grad_mhc_base_tl,
|
| 87 |
+
) = _tester(mhc_pre_split_mixes, test_data, mhc_mult)
|
| 88 |
+
|
| 89 |
+
(
|
| 90 |
+
pre_layer_mix_ref,
|
| 91 |
+
post_layer_mix_ref,
|
| 92 |
+
comb_res_mix_ref,
|
| 93 |
+
grad_input_mixes_ref,
|
| 94 |
+
grad_mhc_scale_ref,
|
| 95 |
+
grad_mhc_base_ref,
|
| 96 |
+
) = _tester(mhc_pre_split_mixes_ref, test_data, mhc_mult)
|
| 97 |
+
|
| 98 |
+
torch.testing.assert_close(pre_layer_mix_tl, pre_layer_mix_ref, rtol=1e-5, atol=2e-5)
|
| 99 |
+
torch.testing.assert_close(post_layer_mix_tl, post_layer_mix_ref, rtol=1e-5, atol=2e-5)
|
| 100 |
+
torch.testing.assert_close(comb_res_mix_tl, comb_res_mix_ref, rtol=1e-5, atol=2e-5)
|
| 101 |
+
torch.testing.assert_close(grad_input_mixes_tl, grad_input_mixes_ref, rtol=1e-5, atol=2e-5)
|
| 102 |
+
torch.testing.assert_close(grad_mhc_scale_tl, grad_mhc_scale_ref, rtol=1e-5, atol=2e-5)
|
| 103 |
+
torch.testing.assert_close(grad_mhc_base_tl, grad_mhc_base_ref, rtol=1e-5, atol=2e-5)
|
tile_kernels_src/tests/mhc/test_sinkhorn.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
from tile_kernels.modeling.mhc.ops import sinkhorn_normalize
|
| 6 |
+
from tile_kernels.torch.mhc import sinkhorn_normalize_ref
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def generate_sinkhorn_test_data(
|
| 10 |
+
n0: int, n1: int, mhc: int, device: str = 'cuda'
|
| 11 |
+
) -> dict[str, torch.Tensor]:
|
| 12 |
+
comb_res_mix = torch.randn((n0, n1, mhc, mhc), dtype=torch.float32, device=device)
|
| 13 |
+
out_grad = torch.randn((n0, n1, mhc, mhc), dtype=torch.float32, device=device)
|
| 14 |
+
|
| 15 |
+
return {
|
| 16 |
+
'comb_res_mix': comb_res_mix,
|
| 17 |
+
'out_grad': out_grad,
|
| 18 |
+
'repeat': 10,
|
| 19 |
+
'eps': 1e-6,
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _tester(
|
| 24 |
+
impl: Callable[[torch.Tensor, int, float], torch.Tensor],
|
| 25 |
+
test_data: dict[str, torch.Tensor],
|
| 26 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 27 |
+
comb_res_mix_ = test_data['comb_res_mix'].clone().requires_grad_()
|
| 28 |
+
out_ = impl(comb_res_mix_, test_data['repeat'], test_data['eps'])
|
| 29 |
+
torch.autograd.backward([out_], [test_data['out_grad']])
|
| 30 |
+
return out_, comb_res_mix_.grad
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@pytest.mark.parametrize('n0', [1, 2])
|
| 34 |
+
@pytest.mark.parametrize('n1', [1, 1024, 4096])
|
| 35 |
+
@pytest.mark.parametrize('mhc', [4])
|
| 36 |
+
def test_sinkhorn_comprehensive(n0: int, n1: int, mhc: int) -> None:
|
| 37 |
+
test_data = generate_sinkhorn_test_data(n0=n0, n1=n1, mhc=mhc)
|
| 38 |
+
|
| 39 |
+
out_tl, grad_tl = _tester(sinkhorn_normalize, test_data)
|
| 40 |
+
out_ref, grad_ref = _tester(sinkhorn_normalize_ref, test_data)
|
| 41 |
+
|
| 42 |
+
torch.testing.assert_close(out_tl, out_ref)
|
| 43 |
+
torch.testing.assert_close(grad_tl, grad_ref)
|
tile_kernels_src/tests/moe/test_aux_fi.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import tile_kernels
|
| 7 |
+
from tile_kernels.config import set_num_sms
|
| 8 |
+
from tile_kernels.testing.generator import generate_topk_idx, generate_moe_params, generate_num_sms
|
| 9 |
+
from tile_kernels.testing.numeric import calc_diff, count_bytes
|
| 10 |
+
from tile_kernels.torch import aux_fi as torch_aux_fi
|
| 11 |
+
from tile_kernels.testing.bench import make_param_id
|
| 12 |
+
|
| 13 |
+
# Disable TileLang prints
|
| 14 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def generate_test_data(params):
|
| 18 |
+
topk_idx = generate_topk_idx(params)
|
| 19 |
+
num_tokens = topk_idx.shape[0]
|
| 20 |
+
|
| 21 |
+
return (topk_idx, num_tokens)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 25 |
+
return [
|
| 26 |
+
{**moe, 'num_aux_topk': num_aux_topk}
|
| 27 |
+
for moe in generate_moe_params(is_benchmark=is_benchmark)
|
| 28 |
+
for num_aux_topk in (1, moe['num_topk'])
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 33 |
+
def test_aux_fi(params):
|
| 34 |
+
topk_idx, num_tokens = generate_test_data(params)
|
| 35 |
+
num_experts = params['num_experts']
|
| 36 |
+
num_aux_topk = params['num_aux_topk']
|
| 37 |
+
|
| 38 |
+
# Test correctness
|
| 39 |
+
fi_ref = torch_aux_fi(topk_idx, num_experts, num_aux_topk)
|
| 40 |
+
|
| 41 |
+
for num_sms in generate_num_sms():
|
| 42 |
+
set_num_sms(num_sms)
|
| 43 |
+
fi = tile_kernels.moe.aux_fi(topk_idx, num_experts, num_aux_topk)
|
| 44 |
+
assert calc_diff(fi, fi_ref) < 2e-7, f'aux_fi mismatch\n{fi}\nvs\n{fi_ref}'
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@pytest.mark.benchmark
|
| 48 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 49 |
+
def test_aux_fi_benchmark(benchmark_timer, benchmark_record, params):
|
| 50 |
+
topk_idx, num_tokens = generate_test_data(params)
|
| 51 |
+
num_experts = params['num_experts']
|
| 52 |
+
num_aux_topk = params['num_aux_topk']
|
| 53 |
+
|
| 54 |
+
t_us = benchmark_timer(lambda: tile_kernels.moe.aux_fi(topk_idx, num_experts, num_aux_topk))
|
| 55 |
+
num_bytes = count_bytes(topk_idx)
|
| 56 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 57 |
+
|
| 58 |
+
params.pop('num_send_tokens')
|
| 59 |
+
benchmark_record(
|
| 60 |
+
kernel='aux_fi',
|
| 61 |
+
operation='fwd',
|
| 62 |
+
params={'num_tokens': num_tokens, **params},
|
| 63 |
+
time_us=t_us,
|
| 64 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 65 |
+
)
|
tile_kernels_src/tests/moe/test_expand_to_fused.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import tile_kernels
|
| 7 |
+
from tile_kernels.testing.generator import generate_topk_idx, generate_hidden_sizes, generate_moe_params
|
| 8 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 9 |
+
from tile_kernels.testing.bench import make_param_id
|
| 10 |
+
|
| 11 |
+
# Disable TileLang prints
|
| 12 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def generate_test_data_expand_to_fused(params):
|
| 16 |
+
num_experts = params['num_experts']
|
| 17 |
+
num_ep_ranks = params['num_ep_ranks']
|
| 18 |
+
hidden = params['hidden']
|
| 19 |
+
|
| 20 |
+
topk_idx = generate_topk_idx(params)
|
| 21 |
+
num_tokens = topk_idx.shape[0]
|
| 22 |
+
x = torch.randn((num_tokens, hidden), dtype=torch.bfloat16, device='cuda')
|
| 23 |
+
pos_to_expert, _, _, token_topk_to_pos, _, _, _, _ = tile_kernels.moe.get_fused_mapping(topk_idx, num_experts, 0, 16)
|
| 24 |
+
|
| 25 |
+
return (x, pos_to_expert, token_topk_to_pos, num_tokens)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def generate_test_params_expand(is_benchmark: bool) -> list[dict]:
|
| 29 |
+
return [
|
| 30 |
+
{**moe, 'hidden': hidden}
|
| 31 |
+
for moe in generate_moe_params(is_benchmark=is_benchmark)
|
| 32 |
+
for hidden in generate_hidden_sizes()
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@pytest.mark.parametrize('params', generate_test_params_expand(is_benchmark=False), ids=make_param_id)
|
| 37 |
+
def test_expand_to_fused(params):
|
| 38 |
+
x, pos_to_expert, token_topk_to_pos, num_tokens = generate_test_data_expand_to_fused(params)
|
| 39 |
+
|
| 40 |
+
expanded_x = tile_kernels.moe.expand_to_fused(x, token_topk_to_pos, pos_to_expert)
|
| 41 |
+
|
| 42 |
+
# Test correctness: torch reference
|
| 43 |
+
expanded_x_ref = tile_kernels.torch.expand_to_fused(x, token_topk_to_pos, pos_to_expert)
|
| 44 |
+
assert_equal(expanded_x, expanded_x_ref)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@pytest.mark.benchmark
|
| 48 |
+
@pytest.mark.parametrize('params', generate_test_params_expand(is_benchmark=True), ids=make_param_id)
|
| 49 |
+
def test_expand_to_fused_benchmark(benchmark_timer, benchmark_record, params):
|
| 50 |
+
x, pos_to_expert, token_topk_to_pos, num_tokens = generate_test_data_expand_to_fused(params)
|
| 51 |
+
|
| 52 |
+
expanded_x = tile_kernels.moe.expand_to_fused(x, token_topk_to_pos, pos_to_expert)
|
| 53 |
+
|
| 54 |
+
t_us = benchmark_timer(lambda: tile_kernels.moe.expand_to_fused(x, token_topk_to_pos, pos_to_expert))
|
| 55 |
+
|
| 56 |
+
num_bytes = count_bytes(x, token_topk_to_pos, pos_to_expert, expanded_x)
|
| 57 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 58 |
+
|
| 59 |
+
params.pop('num_send_tokens')
|
| 60 |
+
benchmark_record(
|
| 61 |
+
kernel='expand_to_fused',
|
| 62 |
+
operation='fwd',
|
| 63 |
+
params={'num_tokens': num_tokens, **params},
|
| 64 |
+
time_us=t_us,
|
| 65 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def generate_test_data_expand_to_fused_with_sf(params):
|
| 70 |
+
num_experts = params['num_experts']
|
| 71 |
+
num_ep_ranks = params['num_ep_ranks']
|
| 72 |
+
hidden = params['hidden']
|
| 73 |
+
num_per_channels = params['num_per_channels']
|
| 74 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 75 |
+
round_sf = params['round_sf']
|
| 76 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 77 |
+
|
| 78 |
+
topk_idx = generate_topk_idx(params)
|
| 79 |
+
num_tokens = topk_idx.shape[0]
|
| 80 |
+
x = torch.randn((num_tokens, hidden), dtype=torch.bfloat16, device='cuda')
|
| 81 |
+
x_fp8, x_sf = tile_kernels.quant.per_token_cast(
|
| 82 |
+
x, 'e4m3',
|
| 83 |
+
num_per_channels=num_per_channels,
|
| 84 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf,
|
| 85 |
+
round_sf=round_sf,
|
| 86 |
+
use_packed_ue8m0=use_packed_ue8m0,
|
| 87 |
+
)
|
| 88 |
+
pos_to_expert, _, _, token_topk_to_pos, _, _, _, _ = tile_kernels.moe.get_fused_mapping(topk_idx, num_experts, 0, 16)
|
| 89 |
+
|
| 90 |
+
return (x_fp8, x_sf, pos_to_expert, token_topk_to_pos, num_tokens)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def generate_test_params_expand_with_sf(is_benchmark: bool) -> list[dict]:
|
| 94 |
+
return [
|
| 95 |
+
{**moe, 'hidden': hidden, 'num_per_channels': num_per_channels,
|
| 96 |
+
'use_tma_aligned_col_major_sf': col_major, 'round_sf': round_sf,
|
| 97 |
+
'use_packed_ue8m0': packed_ue8m0}
|
| 98 |
+
for moe in generate_moe_params(is_benchmark=is_benchmark)
|
| 99 |
+
for hidden in generate_hidden_sizes()
|
| 100 |
+
for num_per_channels in (32, 128)
|
| 101 |
+
for col_major, round_sf, packed_ue8m0 in [(False, True, False), (True, True, True)]
|
| 102 |
+
]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@pytest.mark.parametrize('params', generate_test_params_expand_with_sf(is_benchmark=False), ids=make_param_id)
|
| 106 |
+
def test_expand_to_fused_with_sf(params):
|
| 107 |
+
x_fp8, x_sf, pos_to_expert, token_topk_to_pos, num_tokens = generate_test_data_expand_to_fused_with_sf(params)
|
| 108 |
+
num_per_channels = params['num_per_channels']
|
| 109 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 110 |
+
|
| 111 |
+
func = lambda: tile_kernels.moe.expand_to_fused_with_sf(
|
| 112 |
+
(x_fp8, x_sf.contiguous()), num_per_channels, token_topk_to_pos, pos_to_expert, use_tma_aligned_col_major_sf,
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
expanded_x, expanded_x_sf = func()
|
| 116 |
+
|
| 117 |
+
# Test correctness: torch reference
|
| 118 |
+
expanded_x_ref, expanded_x_sf_ref = tile_kernels.torch.expand_to_fused_with_sf(
|
| 119 |
+
(x_fp8, x_sf.contiguous()), num_per_channels, token_topk_to_pos, pos_to_expert, use_tma_aligned_col_major_sf,
|
| 120 |
+
)
|
| 121 |
+
assert_equal(expanded_x, expanded_x_ref)
|
| 122 |
+
assert_equal(expanded_x_sf, expanded_x_sf_ref, check_stride=num_tokens > 0)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@pytest.mark.benchmark
|
| 126 |
+
@pytest.mark.parametrize('params', generate_test_params_expand_with_sf(is_benchmark=True), ids=make_param_id)
|
| 127 |
+
def test_expand_to_fused_with_sf_benchmark(benchmark_timer, benchmark_record, params):
|
| 128 |
+
x_fp8, x_sf, pos_to_expert, token_topk_to_pos, num_tokens = generate_test_data_expand_to_fused_with_sf(params)
|
| 129 |
+
num_per_channels = params['num_per_channels']
|
| 130 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 131 |
+
|
| 132 |
+
func = lambda: tile_kernels.moe.expand_to_fused_with_sf(
|
| 133 |
+
(x_fp8, x_sf.contiguous()), num_per_channels, token_topk_to_pos, pos_to_expert, use_tma_aligned_col_major_sf,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
expanded_x, expanded_x_sf = func()
|
| 137 |
+
|
| 138 |
+
t_us = benchmark_timer(func)
|
| 139 |
+
|
| 140 |
+
num_bytes = count_bytes(x_fp8, x_sf, token_topk_to_pos, pos_to_expert, expanded_x, expanded_x_sf)
|
| 141 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 142 |
+
|
| 143 |
+
params.pop('num_send_tokens')
|
| 144 |
+
benchmark_record(
|
| 145 |
+
kernel='expand_to_fused_with_sf',
|
| 146 |
+
operation='fwd',
|
| 147 |
+
params={'num_tokens': num_tokens, **params},
|
| 148 |
+
time_us=t_us,
|
| 149 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 150 |
+
)
|
tile_kernels_src/tests/moe/test_get_fused_mapping.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
import tile_kernels
|
| 8 |
+
from tile_kernels.config import set_num_sms
|
| 9 |
+
from tile_kernels.testing.generator import generate_topk_idx, generate_moe_params, generate_num_sms
|
| 10 |
+
from tile_kernels.testing.numeric import count_bytes
|
| 11 |
+
from tile_kernels.testing.bench import make_param_id
|
| 12 |
+
|
| 13 |
+
# Disable TileLang prints
|
| 14 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def generate_test_data(params):
|
| 18 |
+
num_experts = params['num_experts']
|
| 19 |
+
|
| 20 |
+
topk_idx = generate_topk_idx(params)
|
| 21 |
+
num_tokens = topk_idx.shape[0]
|
| 22 |
+
|
| 23 |
+
return (topk_idx, num_tokens)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 27 |
+
params = [
|
| 28 |
+
{**moe, 'alignment': alignment}
|
| 29 |
+
for moe in generate_moe_params(is_benchmark=is_benchmark)
|
| 30 |
+
for alignment in (64, 128)
|
| 31 |
+
]
|
| 32 |
+
if is_benchmark:
|
| 33 |
+
params = [{**param, 'alignment': 128} for param in params]
|
| 34 |
+
return params
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 38 |
+
def test_get_fused_mapping(params):
|
| 39 |
+
alignment = params['alignment']
|
| 40 |
+
|
| 41 |
+
topk_idx, num_tokens = generate_test_data(params)
|
| 42 |
+
num_topk = params['num_topk']
|
| 43 |
+
num_experts = params['num_experts']
|
| 44 |
+
|
| 45 |
+
func = lambda: tile_kernels.moe.get_fused_mapping(topk_idx, num_experts, 0, alignment)
|
| 46 |
+
|
| 47 |
+
for num_sms in generate_num_sms():
|
| 48 |
+
set_num_sms(num_sms)
|
| 49 |
+
|
| 50 |
+
pos_to_expert, pos_to_token, pos_to_token_topk, token_topk_to_pos, expert_start, expert_end, num_tokens_per_expert, num_tokens_per_expert_list = func()
|
| 51 |
+
assert num_tokens_per_expert.tolist() == num_tokens_per_expert_list
|
| 52 |
+
start = 0
|
| 53 |
+
|
| 54 |
+
# Check `pos_to_expert`, `num_tokens_per_expert`, `expert_start`, `expert_end` correctness
|
| 55 |
+
for i in range(num_experts):
|
| 56 |
+
assert start == expert_start[i].item()
|
| 57 |
+
s = pos_to_expert[start:start + num_tokens_per_expert_list[i]]
|
| 58 |
+
assert (s == i).int().sum().item() == (topk_idx == i).int().sum().item()
|
| 59 |
+
s = (s == i) + (s == -1)
|
| 60 |
+
assert s.int().sum().item() == s.numel()
|
| 61 |
+
start += num_tokens_per_expert_list[i]
|
| 62 |
+
assert start == expert_end[i].item()
|
| 63 |
+
|
| 64 |
+
non_negative_mask = pos_to_expert >= 0
|
| 65 |
+
|
| 66 |
+
if non_negative_mask.any():
|
| 67 |
+
t_values = pos_to_token_topk[non_negative_mask]
|
| 68 |
+
token_indices = t_values // num_topk
|
| 69 |
+
topk_indices = t_values % num_topk
|
| 70 |
+
expected_indices = torch.arange(pos_to_token_topk.numel(), device='cuda')[non_negative_mask]
|
| 71 |
+
actual_indices = token_topk_to_pos[token_indices, topk_indices]
|
| 72 |
+
assert torch.equal(actual_indices, expected_indices)
|
| 73 |
+
assert torch.equal(topk_idx[token_indices, topk_indices], pos_to_expert[non_negative_mask])
|
| 74 |
+
assert torch.equal(pos_to_token_topk[non_negative_mask] // num_topk, pos_to_token[non_negative_mask])
|
| 75 |
+
|
| 76 |
+
negative_mask = pos_to_expert < 0
|
| 77 |
+
assert torch.equal(negative_mask, pos_to_token < 0)
|
| 78 |
+
assert torch.equal(negative_mask, pos_to_token_topk < 0)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@pytest.mark.benchmark
|
| 82 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 83 |
+
def test_get_fused_mapping_benchmark(benchmark_timer, benchmark_record, params):
|
| 84 |
+
alignment = params['alignment']
|
| 85 |
+
|
| 86 |
+
topk_idx, num_tokens = generate_test_data(params)
|
| 87 |
+
num_experts = params['num_experts']
|
| 88 |
+
|
| 89 |
+
func = lambda: tile_kernels.moe.get_fused_mapping(topk_idx, num_experts, 0, alignment)
|
| 90 |
+
|
| 91 |
+
t_us = benchmark_timer(func)
|
| 92 |
+
result = func()
|
| 93 |
+
num_bytes = count_bytes(topk_idx, *result[:7])
|
| 94 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 95 |
+
|
| 96 |
+
params.pop('num_send_tokens')
|
| 97 |
+
benchmark_record(
|
| 98 |
+
kernel='get_fused_mapping',
|
| 99 |
+
operation='fwd',
|
| 100 |
+
params={'num_tokens': num_tokens, **params},
|
| 101 |
+
time_us=t_us,
|
| 102 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 103 |
+
)
|
tile_kernels_src/tests/moe/test_group_count.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import tile_kernels
|
| 7 |
+
from tile_kernels.config import set_num_sms
|
| 8 |
+
from tile_kernels.testing.generator import generate_topk_idx, generate_moe_params, generate_num_sms
|
| 9 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 10 |
+
from tile_kernels.torch import group_count as torch_group_count
|
| 11 |
+
from tile_kernels.testing.bench import make_param_id
|
| 12 |
+
|
| 13 |
+
# Disable TileLang prints
|
| 14 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def generate_test_data(params):
|
| 18 |
+
topk_idx = generate_topk_idx(params)
|
| 19 |
+
num_tokens = topk_idx.shape[0]
|
| 20 |
+
|
| 21 |
+
return (topk_idx, num_tokens)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.mark.parametrize('params', list(generate_moe_params(is_benchmark=False)), ids=make_param_id)
|
| 25 |
+
def test_group_count(params):
|
| 26 |
+
topk_idx, num_tokens = generate_test_data(params)
|
| 27 |
+
num_experts = params['num_experts']
|
| 28 |
+
|
| 29 |
+
# Test correctness
|
| 30 |
+
count_ref = torch_group_count(topk_idx, num_experts)
|
| 31 |
+
|
| 32 |
+
for num_sms in generate_num_sms():
|
| 33 |
+
set_num_sms(num_sms)
|
| 34 |
+
count = tile_kernels.moe.group_count(topk_idx, num_experts)
|
| 35 |
+
assert_equal(count, count_ref)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@pytest.mark.benchmark
|
| 39 |
+
@pytest.mark.parametrize('params', list(generate_moe_params(is_benchmark=True)), ids=make_param_id)
|
| 40 |
+
def test_group_count_benchmark(benchmark_timer, benchmark_record, params):
|
| 41 |
+
topk_idx, num_tokens = generate_test_data(params)
|
| 42 |
+
num_experts = params['num_experts']
|
| 43 |
+
|
| 44 |
+
t_us = benchmark_timer(lambda: tile_kernels.moe.group_count(topk_idx, num_experts))
|
| 45 |
+
num_bytes = count_bytes(topk_idx)
|
| 46 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 47 |
+
|
| 48 |
+
params.pop('num_send_tokens')
|
| 49 |
+
benchmark_record(
|
| 50 |
+
kernel='group_count',
|
| 51 |
+
operation='fwd',
|
| 52 |
+
params={'num_tokens': num_tokens, **params},
|
| 53 |
+
time_us=t_us,
|
| 54 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 55 |
+
)
|
tile_kernels_src/tests/moe/test_inplace_unique_group_indices.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import tile_kernels
|
| 7 |
+
from tile_kernels.torch import inplace_unique_group_indices as torch_inplace_unique_group_indices
|
| 8 |
+
from tile_kernels.config import set_num_sms
|
| 9 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 10 |
+
from tile_kernels.testing.generator import generate_moe_params, generate_topk_idx, generate_num_sms
|
| 11 |
+
from tile_kernels.testing.bench import make_param_id
|
| 12 |
+
|
| 13 |
+
# Disable TileLang prints
|
| 14 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def generate_test_data(params):
|
| 18 |
+
num_experts = params['num_experts']
|
| 19 |
+
num_ep_ranks = params['num_ep_ranks']
|
| 20 |
+
num_groups = params['num_groups']
|
| 21 |
+
|
| 22 |
+
topk_idx = generate_topk_idx(params)
|
| 23 |
+
num_tokens = topk_idx.shape[0]
|
| 24 |
+
_group_indices = topk_idx // (num_experts * num_ep_ranks // num_groups)
|
| 25 |
+
|
| 26 |
+
return (_group_indices, num_tokens)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 30 |
+
return [
|
| 31 |
+
{**moe, 'num_groups': num_groups}
|
| 32 |
+
for moe in generate_moe_params(is_benchmark=is_benchmark)
|
| 33 |
+
for num_groups in (8, 16, 72) if moe['num_experts'] * moe['num_ep_ranks'] % num_groups == 0
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 38 |
+
def test_inplace_unique_group_indices(params):
|
| 39 |
+
_group_indices, num_tokens = generate_test_data(params)
|
| 40 |
+
num_groups = params['num_groups']
|
| 41 |
+
|
| 42 |
+
func = lambda group_indices: tile_kernels.moe.inplace_unique_group_indices(group_indices, num_groups)
|
| 43 |
+
func_ref = lambda group_indices: torch_inplace_unique_group_indices(group_indices, num_groups)
|
| 44 |
+
|
| 45 |
+
group_indices_ref = _group_indices.clone()
|
| 46 |
+
func_ref(group_indices_ref)
|
| 47 |
+
|
| 48 |
+
for num_sms in generate_num_sms():
|
| 49 |
+
set_num_sms(num_sms)
|
| 50 |
+
group_indices = _group_indices.clone()
|
| 51 |
+
func(group_indices)
|
| 52 |
+
assert_equal(group_indices, group_indices_ref)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@pytest.mark.benchmark
|
| 56 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 57 |
+
def test_inplace_unique_group_indices_benchmark(benchmark_timer, benchmark_record, params):
|
| 58 |
+
_group_indices, num_tokens = generate_test_data(params)
|
| 59 |
+
num_groups = params['num_groups']
|
| 60 |
+
|
| 61 |
+
func = lambda group_indices: tile_kernels.moe.inplace_unique_group_indices(group_indices, num_groups)
|
| 62 |
+
|
| 63 |
+
group_indices = _group_indices.clone()
|
| 64 |
+
func(group_indices)
|
| 65 |
+
|
| 66 |
+
num_bytes = count_bytes(group_indices)
|
| 67 |
+
num_bytes += torch.count_nonzero(group_indices != _group_indices).item() * 4
|
| 68 |
+
|
| 69 |
+
t_us = benchmark_timer(lambda: func(_group_indices.clone()))
|
| 70 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 71 |
+
|
| 72 |
+
params.pop('num_send_tokens')
|
| 73 |
+
benchmark_record(
|
| 74 |
+
kernel='inplace_unique_group_indices',
|
| 75 |
+
operation='fwd',
|
| 76 |
+
params={'num_tokens': num_tokens, **params},
|
| 77 |
+
time_us=t_us,
|
| 78 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 79 |
+
)
|
tile_kernels_src/tests/moe/test_mask_indices_by_tp.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import tile_kernels
|
| 7 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 8 |
+
from tile_kernels.testing.generator import generate_moe_params, generate_topk_idx
|
| 9 |
+
from tile_kernels.torch import mask_indices_by_tp as torch_mask_indices_by_tp
|
| 10 |
+
from tile_kernels.testing.bench import make_param_id
|
| 11 |
+
|
| 12 |
+
# Disable TileLang prints
|
| 13 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def generate_test_data(params):
|
| 17 |
+
num_experts = params['num_experts']
|
| 18 |
+
num_ep_ranks = params['num_ep_ranks']
|
| 19 |
+
num_tp_ranks = params['num_tp_ranks']
|
| 20 |
+
|
| 21 |
+
topk_idx = generate_topk_idx(params)
|
| 22 |
+
num_tokens = topk_idx.shape[0]
|
| 23 |
+
tp_rank = torch.randint(0, num_tp_ranks, (1,)).item()
|
| 24 |
+
n = num_experts * num_ep_ranks
|
| 25 |
+
|
| 26 |
+
return (topk_idx, num_tokens, tp_rank, n)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 30 |
+
return [
|
| 31 |
+
{**moe, 'num_tp_ranks': num_tp_ranks}
|
| 32 |
+
for moe in generate_moe_params(is_benchmark=is_benchmark)
|
| 33 |
+
for num_tp_ranks in (2, 4, 8)
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 38 |
+
def test_mask_indices_by_tp(params):
|
| 39 |
+
topk_idx, num_tokens, tp_rank, n = generate_test_data(params)
|
| 40 |
+
num_ep_ranks = params['num_ep_ranks']
|
| 41 |
+
num_tp_ranks = params['num_tp_ranks']
|
| 42 |
+
|
| 43 |
+
masked_indices = tile_kernels.moe.mask_indices_by_tp(topk_idx, n, num_ep_ranks, tp_rank, num_tp_ranks)
|
| 44 |
+
|
| 45 |
+
# Test correctness: torch reference
|
| 46 |
+
masked_ref = torch_mask_indices_by_tp(topk_idx, n, num_ep_ranks, tp_rank, num_tp_ranks)
|
| 47 |
+
assert_equal(masked_indices, masked_ref)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@pytest.mark.benchmark
|
| 51 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 52 |
+
def test_mask_indices_by_tp_benchmark(benchmark_timer, benchmark_record, params):
|
| 53 |
+
topk_idx, num_tokens, tp_rank, n = generate_test_data(params)
|
| 54 |
+
num_ep_ranks = params['num_ep_ranks']
|
| 55 |
+
num_tp_ranks = params['num_tp_ranks']
|
| 56 |
+
|
| 57 |
+
masked_indices = tile_kernels.moe.mask_indices_by_tp(topk_idx, n, num_ep_ranks, tp_rank, num_tp_ranks)
|
| 58 |
+
|
| 59 |
+
t_us = benchmark_timer(lambda: tile_kernels.moe.mask_indices_by_tp(topk_idx, n, num_ep_ranks, tp_rank, num_tp_ranks))
|
| 60 |
+
num_bytes = count_bytes(topk_idx, masked_indices)
|
| 61 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 62 |
+
|
| 63 |
+
params.pop('num_send_tokens')
|
| 64 |
+
benchmark_record(
|
| 65 |
+
kernel='mask_indices_by_tp',
|
| 66 |
+
operation='fwd',
|
| 67 |
+
params={'num_tokens': num_tokens, **params, 'tp_rank': tp_rank},
|
| 68 |
+
time_us=t_us,
|
| 69 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 70 |
+
)
|
tile_kernels_src/tests/moe/test_normalize_weight.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import tile_kernels
|
| 7 |
+
from tile_kernels.testing.generator import generate_topk_idx, generate_moe_params
|
| 8 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 9 |
+
from tile_kernels.torch import normalize_weight as torch_normalize_weight
|
| 10 |
+
from tile_kernels.testing.bench import make_param_id
|
| 11 |
+
|
| 12 |
+
# Disable TileLang prints
|
| 13 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def generate_test_data(params):
|
| 17 |
+
num_topk = params['num_topk']
|
| 18 |
+
|
| 19 |
+
topk_idx = generate_topk_idx(params)
|
| 20 |
+
num_tokens = topk_idx.shape[0]
|
| 21 |
+
topk_weights = torch.rand((num_tokens, num_topk), dtype=torch.float32, device='cuda')
|
| 22 |
+
|
| 23 |
+
return (topk_weights, num_tokens)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@pytest.mark.parametrize('params', list(generate_moe_params(is_benchmark=False)), ids=make_param_id)
|
| 27 |
+
def test_normalize_weight(params):
|
| 28 |
+
(topk_weights, _) = generate_test_data(params)
|
| 29 |
+
|
| 30 |
+
denominator, normalized_weights = tile_kernels.moe.normalize_weight(topk_weights)
|
| 31 |
+
|
| 32 |
+
# Test correctness: torch reference
|
| 33 |
+
denom_ref, norm_ref = torch_normalize_weight(topk_weights)
|
| 34 |
+
assert_equal(denominator, denom_ref)
|
| 35 |
+
assert_equal(normalized_weights, norm_ref)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@pytest.mark.benchmark
|
| 39 |
+
@pytest.mark.parametrize('params', list(generate_moe_params(is_benchmark=True)), ids=make_param_id)
|
| 40 |
+
def test_normalize_weight_benchmark(benchmark_timer, benchmark_record, params):
|
| 41 |
+
topk_weights, num_tokens = generate_test_data(params)
|
| 42 |
+
num_topk = params['num_topk']
|
| 43 |
+
|
| 44 |
+
denominator, normalized_weights = tile_kernels.moe.normalize_weight(topk_weights)
|
| 45 |
+
|
| 46 |
+
t_us = benchmark_timer(lambda: tile_kernels.moe.normalize_weight(topk_weights))
|
| 47 |
+
num_bytes = count_bytes(topk_weights, denominator, normalized_weights)
|
| 48 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 49 |
+
|
| 50 |
+
params.pop('num_send_tokens')
|
| 51 |
+
benchmark_record(
|
| 52 |
+
kernel='normalize_weight',
|
| 53 |
+
operation='fwd',
|
| 54 |
+
params={'num_tokens': num_tokens, **params, 'num_topk': num_topk},
|
| 55 |
+
time_us=t_us,
|
| 56 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 57 |
+
)
|
tile_kernels_src/tests/moe/test_reduce_fused.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import tile_kernels
|
| 7 |
+
from tile_kernels.testing.bench import dtype_to_str, make_param_id
|
| 8 |
+
from tile_kernels.testing.generator import generate_topk_idx, generate_hidden_sizes, generate_moe_params
|
| 9 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 10 |
+
|
| 11 |
+
# Disable TileLang prints
|
| 12 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def generate_test_data(params):
|
| 16 |
+
hidden = params['hidden']
|
| 17 |
+
with_weights = params['with_weights']
|
| 18 |
+
in_dtype = params['in_dtype']
|
| 19 |
+
out_dtype = params['out_dtype']
|
| 20 |
+
with_sf = params['with_sf']
|
| 21 |
+
num_experts = params['num_experts']
|
| 22 |
+
num_ep_ranks = params['num_ep_ranks']
|
| 23 |
+
num_topk = params['num_topk']
|
| 24 |
+
|
| 25 |
+
topk_idx = generate_topk_idx(params)
|
| 26 |
+
num_tokens = topk_idx.shape[0]
|
| 27 |
+
num_expanded_tokens = num_tokens * num_topk
|
| 28 |
+
expanded = torch.randn((num_expanded_tokens, hidden), dtype=in_dtype, device='cuda')
|
| 29 |
+
_, _, _, token_topk_to_pos, _, _, _, _ = tile_kernels.moe.get_fused_mapping(topk_idx, num_experts, 0, 1)
|
| 30 |
+
|
| 31 |
+
topk_weights = torch.rand((num_tokens, num_topk), dtype=torch.float32, device='cuda') if with_weights else None
|
| 32 |
+
if out_dtype == torch.float8_e4m3fn:
|
| 33 |
+
sf = torch.randn((1,), dtype=torch.float32, device='cuda')
|
| 34 |
+
else:
|
| 35 |
+
sf = None
|
| 36 |
+
if with_sf:
|
| 37 |
+
x_sf = torch.randn((num_expanded_tokens,), dtype=torch.float32, device='cuda')
|
| 38 |
+
else:
|
| 39 |
+
x_sf = None
|
| 40 |
+
fp8_format = 'e4m3' if out_dtype == torch.float8_e4m3fn else ''
|
| 41 |
+
|
| 42 |
+
x_input = (expanded, x_sf) if x_sf is not None else expanded
|
| 43 |
+
|
| 44 |
+
return (expanded, token_topk_to_pos, topk_weights, sf, x_sf, fp8_format, x_input, num_tokens)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 48 |
+
params = [
|
| 49 |
+
{**moe, 'hidden': hidden, 'with_weights': with_weights,
|
| 50 |
+
'in_dtype': in_dtype, 'out_dtype': out_dtype, 'with_sf': with_sf}
|
| 51 |
+
for moe in generate_moe_params(is_benchmark=is_benchmark)
|
| 52 |
+
for hidden in generate_hidden_sizes(256)
|
| 53 |
+
for with_weights in (True, False)
|
| 54 |
+
for in_dtype in (torch.float32, torch.bfloat16)
|
| 55 |
+
for out_dtype in (in_dtype, torch.float8_e4m3fn)
|
| 56 |
+
for with_sf in (True, False)
|
| 57 |
+
]
|
| 58 |
+
if is_benchmark:
|
| 59 |
+
params = [p for p in params if p['num_topk'] == 6 and p['with_weights']]
|
| 60 |
+
return params
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 64 |
+
def test_reduce_fused(params):
|
| 65 |
+
(expanded, token_topk_to_pos, topk_weights, sf, x_sf, fp8_format, x_input,
|
| 66 |
+
_) = generate_test_data(params)
|
| 67 |
+
|
| 68 |
+
# Test correctness: tile_kernels kernel
|
| 69 |
+
func = lambda: tile_kernels.moe.reduce_fused(
|
| 70 |
+
x_input, topk_weights, token_topk_to_pos, fp8_format, sf, None
|
| 71 |
+
)
|
| 72 |
+
r_tk = func()
|
| 73 |
+
|
| 74 |
+
# Test correctness: torch reference
|
| 75 |
+
r_ref = tile_kernels.torch.reduce_fused(
|
| 76 |
+
x_input, topk_weights, token_topk_to_pos, fp8_format, sf
|
| 77 |
+
)
|
| 78 |
+
assert_equal(r_tk, r_ref)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@pytest.mark.benchmark
|
| 82 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 83 |
+
def test_reduce_fused_benchmark(benchmark_timer, benchmark_record, params):
|
| 84 |
+
hidden = params['hidden']
|
| 85 |
+
out_dtype = params['out_dtype']
|
| 86 |
+
|
| 87 |
+
(expanded, token_topk_to_pos, topk_weights, sf, x_sf, fp8_format, x_input,
|
| 88 |
+
num_tokens) = generate_test_data(params)
|
| 89 |
+
in_dtype = params['in_dtype']
|
| 90 |
+
|
| 91 |
+
func = lambda: tile_kernels.moe.reduce_fused(
|
| 92 |
+
x_input, topk_weights, token_topk_to_pos, fp8_format, sf, None
|
| 93 |
+
)
|
| 94 |
+
r_tk = func()
|
| 95 |
+
|
| 96 |
+
num_bytes = count_bytes(token_topk_to_pos, x_sf, r_tk)
|
| 97 |
+
num_bytes += torch.count_nonzero(token_topk_to_pos != -1).item() * hidden * (torch.finfo(in_dtype).bits // 8)
|
| 98 |
+
if topk_weights is not None:
|
| 99 |
+
num_bytes += count_bytes(topk_weights)
|
| 100 |
+
|
| 101 |
+
t_us = benchmark_timer(func)
|
| 102 |
+
|
| 103 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 104 |
+
|
| 105 |
+
params.pop('num_send_tokens')
|
| 106 |
+
benchmark_record(
|
| 107 |
+
kernel='reduce_fused',
|
| 108 |
+
operation='fwd',
|
| 109 |
+
params={'num_tokens': num_tokens, **params, 'in_dtype': dtype_to_str(in_dtype), 'out_dtype': dtype_to_str(out_dtype)},
|
| 110 |
+
time_us=t_us,
|
| 111 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 112 |
+
)
|
tile_kernels_src/tests/moe/test_top2_sum_gate.py
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
import tile_kernels
|
| 8 |
+
from tile_kernels.moe.scoring import ScoringFunc
|
| 9 |
+
from tile_kernels.testing.generator import generate_num_tokens
|
| 10 |
+
from tile_kernels.testing.numeric import count_bytes, assert_equal
|
| 11 |
+
from tile_kernels.testing.bench import make_param_id
|
| 12 |
+
|
| 13 |
+
from tile_kernels.torch import topk_sum_and_topk_group_idx as torch_topk_sum_and_topk_group_idx
|
| 14 |
+
from tile_kernels.torch import top2_sum_gate as torch_top2_sum_gate
|
| 15 |
+
|
| 16 |
+
# Disable TileLang prints
|
| 17 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_CONFIGS = [
|
| 21 |
+
(0, 0, 72, 1, 6),
|
| 22 |
+
(0, 0, 32, 2, 6),
|
| 23 |
+
(0, 0, 64, 2, 6),
|
| 24 |
+
(0, 0, 96, 2, 6),
|
| 25 |
+
(0, 0, 16, 2, 6),
|
| 26 |
+
(0, 0, 36, 2, 6),
|
| 27 |
+
(0, 0, 108, 2, 6),
|
| 28 |
+
(0, 0, 128, 2, 6),
|
| 29 |
+
(0, 0, 144, 2, 6),
|
| 30 |
+
(8, 8, 256, 2, 8),
|
| 31 |
+
(8, 4, 256, 2, 8),
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 36 |
+
params = [
|
| 37 |
+
{
|
| 38 |
+
'num_groups': num_groups,
|
| 39 |
+
'num_topk_groups': num_topk_groups,
|
| 40 |
+
'num_routed_experts': num_routed_experts,
|
| 41 |
+
'num_shared_experts': num_shared_experts,
|
| 42 |
+
'num_topk': num_topk,
|
| 43 |
+
}
|
| 44 |
+
for num_groups, num_topk_groups, num_routed_experts, num_shared_experts, num_topk in _CONFIGS
|
| 45 |
+
]
|
| 46 |
+
if is_benchmark:
|
| 47 |
+
scoring_funcs = [sf for sf in ScoringFunc if sf != ScoringFunc.IDENTITY]
|
| 48 |
+
params = [
|
| 49 |
+
{**p, 'scoring_func': sf}
|
| 50 |
+
for p in params
|
| 51 |
+
for sf in scoring_funcs
|
| 52 |
+
]
|
| 53 |
+
return params
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 57 |
+
def test_top2_sum_gate(params):
|
| 58 |
+
num_groups = params['num_groups']
|
| 59 |
+
num_topk_groups = params['num_topk_groups']
|
| 60 |
+
num_routed_experts = params['num_routed_experts']
|
| 61 |
+
num_shared_experts = params['num_shared_experts']
|
| 62 |
+
num_topk = params['num_topk']
|
| 63 |
+
|
| 64 |
+
num_extra_experts = 32 # Only enabled for `use_shared_as_routed`
|
| 65 |
+
num_group_sum_topk = 2
|
| 66 |
+
routed_scaling_factor = 1.5
|
| 67 |
+
num_ep_ranks, num_tp_ranks = 4, 2
|
| 68 |
+
ep_rank = 0
|
| 69 |
+
assert num_routed_experts % num_ep_ranks == 0 and (num_routed_experts + num_extra_experts) % num_ep_ranks == 0
|
| 70 |
+
|
| 71 |
+
def get_group_masked_scores(scores: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:
|
| 72 |
+
scores.add_(bias.unsqueeze(0))
|
| 73 |
+
if num_topk_groups != num_groups:
|
| 74 |
+
group_idx = torch_topk_sum_and_topk_group_idx(scores.view(num_tokens, num_groups, num_routed_experts // num_groups), num_group_sum_topk, num_topk_groups)
|
| 75 |
+
group_mask = scores.new_ones(num_tokens, num_groups, dtype=torch.bool).scatter_(1, group_idx, False)
|
| 76 |
+
score_mask = group_mask.unsqueeze(-1).expand(num_tokens, num_groups, num_routed_experts // num_groups).reshape(scores.size(0), num_routed_experts)
|
| 77 |
+
scores = scores.masked_fill(score_mask, float('-inf'))
|
| 78 |
+
return scores
|
| 79 |
+
|
| 80 |
+
def get_scores(logits: torch.Tensor, scoring_func: ScoringFunc) -> torch.Tensor:
|
| 81 |
+
if scoring_func == ScoringFunc.SIGMOID:
|
| 82 |
+
return logits.sigmoid()
|
| 83 |
+
elif scoring_func == ScoringFunc.SOFTMAX:
|
| 84 |
+
return logits.softmax(dim=-1)
|
| 85 |
+
elif scoring_func == ScoringFunc.SQRTSOFTPLUS:
|
| 86 |
+
return F.softplus(logits).sqrt()
|
| 87 |
+
else:
|
| 88 |
+
raise ValueError(f'Unknown scoring function: {scoring_func}')
|
| 89 |
+
|
| 90 |
+
def construct_input(scoring_func: ScoringFunc):
|
| 91 |
+
while True:
|
| 92 |
+
logits = torch.randn((num_tokens + num_padded_tokens, num_routed_experts), dtype=torch.float, device='cuda')
|
| 93 |
+
bias = torch.randn(num_routed_experts, dtype=torch.float, device='cuda')
|
| 94 |
+
scores = get_scores(logits[:num_tokens], scoring_func)
|
| 95 |
+
|
| 96 |
+
# NOTES: We expect the top-k group to be stable, and since the internal kernel uses low-precision operations,
|
| 97 |
+
# the generated data needs to have a sufficient gap between the k-th largest and
|
| 98 |
+
# the (k+1)-th largest values to ensure that the selected top-k groups are definitive
|
| 99 |
+
if num_topk_groups != num_groups:
|
| 100 |
+
# NOTES: softmax has different behavior than other functions, so we need to handle it separately
|
| 101 |
+
if scoring_func != ScoringFunc.SOFTMAX:
|
| 102 |
+
scores_ref = scores + bias.unsqueeze(0)
|
| 103 |
+
else:
|
| 104 |
+
scores_ref = logits[:num_tokens] + bias.unsqueeze(0)
|
| 105 |
+
|
| 106 |
+
group_scores_ref = scores_ref.view(num_tokens, num_groups, num_routed_experts // num_groups).topk(num_group_sum_topk, dim=-1, sorted=False).values.sum(-1)
|
| 107 |
+
group_scores_ref, _ = group_scores_ref.sort(dim=-1, descending=True)
|
| 108 |
+
not_equal = group_scores_ref[:, num_topk_groups - 1] - group_scores_ref[:, num_topk_groups] > 1e-6
|
| 109 |
+
if not torch.all(not_equal):
|
| 110 |
+
continue
|
| 111 |
+
|
| 112 |
+
scores = get_group_masked_scores(scores, bias)
|
| 113 |
+
topk_weights_ref, _ = torch.topk(scores, k=num_topk + 1, dim=-1, sorted=True)
|
| 114 |
+
|
| 115 |
+
# NOTES: We expect the top-k results to be stable, and since the internal kernel uses low-precision operations,
|
| 116 |
+
# the generated data needs to have a sufficient gap between the top-k values.
|
| 117 |
+
not_equal = topk_weights_ref[:, : num_topk - 1] - topk_weights_ref[:, 1:num_topk] > 2e-6
|
| 118 |
+
if torch.all(not_equal):
|
| 119 |
+
break
|
| 120 |
+
return logits, bias
|
| 121 |
+
|
| 122 |
+
# noinspection PyShadowingNames
|
| 123 |
+
def get_kwargs(use_shared_as_routed: bool, num_extra_experts: int, num_tokens: int, num_padded_tokens: int, fix_routing: bool):
|
| 124 |
+
mask = None
|
| 125 |
+
if num_padded_tokens > 0:
|
| 126 |
+
mask = torch.ones(num_tokens + num_padded_tokens, dtype=torch.bool, device='cuda')
|
| 127 |
+
mask[-num_padded_tokens:] = False
|
| 128 |
+
|
| 129 |
+
to_physical_map = None
|
| 130 |
+
logical_count = None
|
| 131 |
+
fix_routing_mask = None
|
| 132 |
+
unmapped_topk_idx = torch.zeros((num_tokens + num_padded_tokens, num_topk), dtype=torch.int64, device='cuda')
|
| 133 |
+
|
| 134 |
+
# Test to physical map
|
| 135 |
+
if use_shared_as_routed:
|
| 136 |
+
assert num_shared_experts <= num_extra_experts
|
| 137 |
+
to_physical_map = torch.arange(0, num_routed_experts + num_shared_experts, dtype=torch.int, device='cuda')
|
| 138 |
+
to_physical_map = to_physical_map.view(-1, 1).expand(-1, num_extra_experts + 1).contiguous()
|
| 139 |
+
logical_count = torch.ones((num_routed_experts + num_shared_experts,), dtype=torch.int, device='cuda')
|
| 140 |
+
|
| 141 |
+
# Test fix routing mask
|
| 142 |
+
if fix_routing:
|
| 143 |
+
fix_routing_mask = torch.ones((num_tokens + num_padded_tokens,), dtype=torch.bool, device='cuda')
|
| 144 |
+
# NOTES: Use separate generator to generate the same value for same (num_tokens, num_topk)
|
| 145 |
+
unmapped_topk_idx_generator = torch.Generator(device='cuda').manual_seed(42)
|
| 146 |
+
unmapped_topk_idx = torch.randint(
|
| 147 |
+
0,
|
| 148 |
+
num_routed_experts,
|
| 149 |
+
(num_tokens + num_padded_tokens, num_topk),
|
| 150 |
+
generator=unmapped_topk_idx_generator,
|
| 151 |
+
dtype=torch.int64,
|
| 152 |
+
device='cuda',
|
| 153 |
+
)
|
| 154 |
+
return dict(
|
| 155 |
+
mask=mask,
|
| 156 |
+
fix_routing_mask=fix_routing_mask,
|
| 157 |
+
to_physical_map=to_physical_map,
|
| 158 |
+
logical_count=logical_count,
|
| 159 |
+
unmapped_topk_idx=unmapped_topk_idx,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
# Correctness test
|
| 163 |
+
use_shared_as_routed_valid = num_topk % num_shared_experts == 0 and num_routed_experts % (num_topk // num_shared_experts) == 0
|
| 164 |
+
for num_tokens in generate_num_tokens():
|
| 165 |
+
for num_padded_tokens in (0, 10):
|
| 166 |
+
for tp_rank in range(0, num_tp_ranks):
|
| 167 |
+
for use_shared_as_routed in (False, True) if use_shared_as_routed_valid else (False,):
|
| 168 |
+
for scoring_func in ScoringFunc:
|
| 169 |
+
if scoring_func == ScoringFunc.IDENTITY:
|
| 170 |
+
continue
|
| 171 |
+
for fix_routing in (False, True):
|
| 172 |
+
logits, bias = construct_input(scoring_func)
|
| 173 |
+
args = (
|
| 174 |
+
logits,
|
| 175 |
+
bias,
|
| 176 |
+
num_topk,
|
| 177 |
+
num_topk_groups,
|
| 178 |
+
num_groups,
|
| 179 |
+
use_shared_as_routed,
|
| 180 |
+
num_shared_experts,
|
| 181 |
+
routed_scaling_factor,
|
| 182 |
+
ep_rank,
|
| 183 |
+
num_ep_ranks,
|
| 184 |
+
tp_rank,
|
| 185 |
+
num_tp_ranks,
|
| 186 |
+
str(scoring_func),
|
| 187 |
+
)
|
| 188 |
+
kwargs = get_kwargs(use_shared_as_routed, num_extra_experts, num_tokens, num_padded_tokens, fix_routing)
|
| 189 |
+
kwargs_ref = get_kwargs(use_shared_as_routed, num_extra_experts, num_tokens, num_padded_tokens, fix_routing)
|
| 190 |
+
|
| 191 |
+
topk_idx, topk_weights= tile_kernels.moe.top2_sum_gate(*args, **kwargs)
|
| 192 |
+
topk_idx_ref, topk_weights_ref = torch_top2_sum_gate(*args, **kwargs_ref)
|
| 193 |
+
|
| 194 |
+
unmapped_topk_idx = kwargs['unmapped_topk_idx']
|
| 195 |
+
unmapped_topk_idx_ref = kwargs_ref['unmapped_topk_idx']
|
| 196 |
+
|
| 197 |
+
sorted_topk_idx, _ = topk_idx.sort(dim=1)
|
| 198 |
+
sorted_topk_idx_ref, _ = topk_idx_ref.sort(dim=1)
|
| 199 |
+
|
| 200 |
+
sorted_unmapped_topk_idx = unmapped_topk_idx.sort(dim=1)[0]
|
| 201 |
+
sorted_unmapped_topk_idx_ref = unmapped_topk_idx_ref.sort(dim=1)[0]
|
| 202 |
+
|
| 203 |
+
sorted_topk_weights, _ = topk_weights.sort(dim=1)
|
| 204 |
+
sorted_topk_weights_ref, _ = topk_weights_ref.sort(dim=1)
|
| 205 |
+
|
| 206 |
+
assert_equal(sorted_topk_idx, sorted_topk_idx_ref)
|
| 207 |
+
assert_equal(sorted_unmapped_topk_idx, sorted_unmapped_topk_idx_ref)
|
| 208 |
+
assert torch.allclose(sorted_topk_weights, sorted_topk_weights_ref), (
|
| 209 |
+
f'{sorted_topk_weights=}\n'
|
| 210 |
+
f'{sorted_topk_weights_ref=}\n'
|
| 211 |
+
f'{scoring_func=}, {num_groups=}, {num_topk_groups=}, {num_routed_experts=}, {num_shared_experts=}, {num_topk=}, {fix_routing=}\n'
|
| 212 |
+
f'Different topk weights: \n'
|
| 213 |
+
f'{[(sorted_topk_weights[i], sorted_topk_weights_ref[i]) for i in range(topk_weights.size(0)) if not torch.equal(sorted_topk_weights[i], sorted_topk_weights_ref[i])]}'
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
# Check sort stability
|
| 217 |
+
tp_rank = 0
|
| 218 |
+
logits = torch.zeros((num_tokens + num_padded_tokens, num_routed_experts), dtype=torch.float, device='cuda')
|
| 219 |
+
bias = torch.zeros(num_routed_experts, dtype=torch.float, device='cuda')
|
| 220 |
+
args = (
|
| 221 |
+
logits,
|
| 222 |
+
bias,
|
| 223 |
+
num_topk,
|
| 224 |
+
num_topk_groups,
|
| 225 |
+
num_groups,
|
| 226 |
+
use_shared_as_routed,
|
| 227 |
+
num_shared_experts,
|
| 228 |
+
routed_scaling_factor,
|
| 229 |
+
ep_rank,
|
| 230 |
+
num_ep_ranks,
|
| 231 |
+
tp_rank,
|
| 232 |
+
num_tp_ranks,
|
| 233 |
+
str(ScoringFunc.SIGMOID),
|
| 234 |
+
)
|
| 235 |
+
fix_routing = False
|
| 236 |
+
kwargs = get_kwargs(use_shared_as_routed, num_extra_experts, num_tokens, num_padded_tokens, fix_routing)
|
| 237 |
+
topk_idx, topk_weights = tile_kernels.moe.top2_sum_gate(*args, **kwargs)
|
| 238 |
+
num_experts_on_rank = min(num_routed_experts // num_ep_ranks, num_topk)
|
| 239 |
+
assert torch.all(
|
| 240 |
+
topk_idx[:num_tokens, :num_experts_on_rank] == torch.arange(0, num_experts_on_rank, dtype=topk_idx.dtype, device=topk_idx.device)
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def generate_benchmark_test_case(params):
|
| 245 |
+
num_groups = params['num_groups']
|
| 246 |
+
num_topk_groups = params['num_topk_groups']
|
| 247 |
+
num_routed_experts = params['num_routed_experts']
|
| 248 |
+
num_shared_experts = params['num_shared_experts']
|
| 249 |
+
num_topk = params['num_topk']
|
| 250 |
+
|
| 251 |
+
num_extra_experts = 32
|
| 252 |
+
num_group_sum_topk = 2
|
| 253 |
+
routed_scaling_factor = 1.5
|
| 254 |
+
num_ep_ranks, num_tp_ranks = 4, 2
|
| 255 |
+
ep_rank = 0
|
| 256 |
+
|
| 257 |
+
use_shared_as_routed_valid = num_topk % num_shared_experts == 0 and num_routed_experts % (num_topk // num_shared_experts) == 0
|
| 258 |
+
use_shared_as_routed = use_shared_as_routed_valid
|
| 259 |
+
|
| 260 |
+
num_tokens, num_padded_tokens = 32, 4
|
| 261 |
+
tp_rank = num_tp_ranks - 1
|
| 262 |
+
fix_routing = False
|
| 263 |
+
|
| 264 |
+
logits = torch.randn((num_tokens + num_padded_tokens, num_routed_experts), dtype=torch.float, device='cuda')
|
| 265 |
+
bias = torch.randn(num_routed_experts, dtype=torch.float, device='cuda')
|
| 266 |
+
|
| 267 |
+
# noinspection PyShadowingNames
|
| 268 |
+
def get_kwargs(use_shared_as_routed, num_extra_experts, num_tokens, num_padded_tokens, fix_routing):
|
| 269 |
+
mask = None
|
| 270 |
+
if num_padded_tokens > 0:
|
| 271 |
+
mask = torch.ones(num_tokens + num_padded_tokens, dtype=torch.bool, device='cuda')
|
| 272 |
+
mask[-num_padded_tokens:] = False
|
| 273 |
+
|
| 274 |
+
to_physical_map = None
|
| 275 |
+
logical_count = None
|
| 276 |
+
fix_routing_mask = None
|
| 277 |
+
unmapped_topk_idx = torch.zeros((num_tokens + num_padded_tokens, num_topk), dtype=torch.int64, device='cuda')
|
| 278 |
+
|
| 279 |
+
if use_shared_as_routed:
|
| 280 |
+
assert num_shared_experts <= num_extra_experts
|
| 281 |
+
to_physical_map = torch.arange(0, num_routed_experts + num_shared_experts, dtype=torch.int, device='cuda')
|
| 282 |
+
to_physical_map = to_physical_map.view(-1, 1).expand(-1, num_extra_experts + 1).contiguous()
|
| 283 |
+
logical_count = torch.ones((num_routed_experts + num_shared_experts,), dtype=torch.int, device='cuda')
|
| 284 |
+
|
| 285 |
+
if fix_routing:
|
| 286 |
+
fix_routing_mask = torch.ones((num_tokens + num_padded_tokens,), dtype=torch.bool, device='cuda')
|
| 287 |
+
unmapped_topk_idx_generator = torch.Generator(device='cuda').manual_seed(42)
|
| 288 |
+
unmapped_topk_idx = torch.randint(
|
| 289 |
+
0,
|
| 290 |
+
num_routed_experts,
|
| 291 |
+
(num_tokens + num_padded_tokens, num_topk),
|
| 292 |
+
generator=unmapped_topk_idx_generator,
|
| 293 |
+
dtype=torch.int64,
|
| 294 |
+
device='cuda',
|
| 295 |
+
)
|
| 296 |
+
return dict(
|
| 297 |
+
mask=mask,
|
| 298 |
+
fix_routing_mask=fix_routing_mask,
|
| 299 |
+
to_physical_map=to_physical_map,
|
| 300 |
+
logical_count=logical_count,
|
| 301 |
+
unmapped_topk_idx=unmapped_topk_idx,
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
kwargs = get_kwargs(use_shared_as_routed, num_extra_experts, num_tokens, num_padded_tokens, fix_routing)
|
| 305 |
+
|
| 306 |
+
return {
|
| 307 |
+
'logits': logits,
|
| 308 |
+
'bias': bias,
|
| 309 |
+
'num_topk': num_topk,
|
| 310 |
+
'num_topk_groups': num_topk_groups,
|
| 311 |
+
'num_groups': num_groups,
|
| 312 |
+
'use_shared_as_routed_valid': use_shared_as_routed_valid,
|
| 313 |
+
'num_shared_experts': num_shared_experts,
|
| 314 |
+
'routed_scaling_factor': routed_scaling_factor,
|
| 315 |
+
'ep_rank': ep_rank,
|
| 316 |
+
'num_ep_ranks': num_ep_ranks,
|
| 317 |
+
'tp_rank': tp_rank,
|
| 318 |
+
'num_tp_ranks': num_tp_ranks,
|
| 319 |
+
'kwargs': kwargs,
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
@pytest.mark.benchmark
|
| 324 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 325 |
+
def test_top2_sum_gate_benchmark(benchmark_timer, benchmark_record, params):
|
| 326 |
+
scoring_func = params['scoring_func']
|
| 327 |
+
|
| 328 |
+
tc = generate_benchmark_test_case(params)
|
| 329 |
+
logits = tc['logits']
|
| 330 |
+
bias = tc['bias']
|
| 331 |
+
kwargs = tc['kwargs']
|
| 332 |
+
|
| 333 |
+
args = (
|
| 334 |
+
logits,
|
| 335 |
+
bias,
|
| 336 |
+
tc['num_topk'],
|
| 337 |
+
tc['num_topk_groups'],
|
| 338 |
+
tc['num_groups'],
|
| 339 |
+
tc['use_shared_as_routed_valid'],
|
| 340 |
+
tc['num_shared_experts'],
|
| 341 |
+
tc['routed_scaling_factor'],
|
| 342 |
+
tc['ep_rank'],
|
| 343 |
+
tc['num_ep_ranks'],
|
| 344 |
+
tc['tp_rank'],
|
| 345 |
+
tc['num_tp_ranks'],
|
| 346 |
+
str(scoring_func),
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
t_us = benchmark_timer(lambda: tile_kernels.moe.top2_sum_gate(*args, **kwargs))
|
| 350 |
+
num_bytes = count_bytes(logits, bias)
|
| 351 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 352 |
+
|
| 353 |
+
benchmark_record(
|
| 354 |
+
kernel='top2_sum_gate',
|
| 355 |
+
operation='fwd',
|
| 356 |
+
params={**params, 'scoring_func': str(scoring_func)},
|
| 357 |
+
time_us=t_us,
|
| 358 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 359 |
+
)
|
tile_kernels_src/tests/moe/test_topk_gate.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import tile_kernels
|
| 6 |
+
from tile_kernels.testing.generator import generate_num_tokens
|
| 7 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 8 |
+
from tile_kernels.testing.bench import make_param_id
|
| 9 |
+
from tile_kernels.torch import stable_topk as torch_stable_topk
|
| 10 |
+
# Disable TileLang prints
|
| 11 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
_EXPERT_CONFIGS = [
|
| 15 |
+
(72, 6),
|
| 16 |
+
(32, 6),
|
| 17 |
+
(64, 6),
|
| 18 |
+
(96, 6),
|
| 19 |
+
(16, 6),
|
| 20 |
+
(36, 6),
|
| 21 |
+
(108, 6),
|
| 22 |
+
(128, 6),
|
| 23 |
+
(144, 6),
|
| 24 |
+
(256, 8),
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def generate_test_data(params):
|
| 29 |
+
num_tokens = params['num_tokens']
|
| 30 |
+
num_experts = params['num_experts']
|
| 31 |
+
scores = torch.randn((num_tokens, num_experts), dtype=torch.float, device='cuda')
|
| 32 |
+
return scores
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 36 |
+
return [
|
| 37 |
+
{
|
| 38 |
+
'num_tokens': num_tokens,
|
| 39 |
+
'num_experts': num_experts,
|
| 40 |
+
'num_topk': num_topk,
|
| 41 |
+
}
|
| 42 |
+
for num_tokens in generate_num_tokens(is_benchmark=is_benchmark)
|
| 43 |
+
for num_experts, num_topk in _EXPERT_CONFIGS
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 48 |
+
def test_topk_gate(params):
|
| 49 |
+
scores = generate_test_data(params)
|
| 50 |
+
num_topk = params['num_topk']
|
| 51 |
+
|
| 52 |
+
topk_idx_ref = torch_stable_topk(scores, num_topk)
|
| 53 |
+
topk_idx = tile_kernels.moe.topk_gate(scores, num_topk)
|
| 54 |
+
assert_equal(topk_idx, topk_idx_ref)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@pytest.mark.benchmark
|
| 58 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 59 |
+
def test_topk_gate_benchmark(benchmark_timer, benchmark_record, params):
|
| 60 |
+
scores = generate_test_data(params)
|
| 61 |
+
num_topk = params['num_topk']
|
| 62 |
+
|
| 63 |
+
topk_idx = tile_kernels.moe.topk_gate(scores, num_topk)
|
| 64 |
+
|
| 65 |
+
t_us = benchmark_timer(lambda: tile_kernels.moe.topk_gate(scores, num_topk))
|
| 66 |
+
num_bytes = count_bytes(scores, topk_idx)
|
| 67 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 68 |
+
|
| 69 |
+
benchmark_record(
|
| 70 |
+
kernel='topk_gate',
|
| 71 |
+
operation='fwd',
|
| 72 |
+
params=params,
|
| 73 |
+
time_us=t_us,
|
| 74 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 75 |
+
)
|
tile_kernels_src/tests/moe/test_topk_sum_and_topk_idx.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import tile_kernels
|
| 7 |
+
from tile_kernels.testing.generator import generate_num_tokens
|
| 8 |
+
from tile_kernels.testing.numeric import count_bytes, assert_equal
|
| 9 |
+
from tile_kernels.testing.bench import make_param_id
|
| 10 |
+
|
| 11 |
+
from tile_kernels.torch import topk_sum_and_topk_group_idx as torch_topk_sum_and_topk_group_idx
|
| 12 |
+
|
| 13 |
+
# Disable TileLang prints
|
| 14 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def torch_stable_topk(scores: torch.Tensor, num_topk: int):
|
| 18 |
+
_, sorted_indices = torch.sort(scores, dim=1, descending=True, stable=True)
|
| 19 |
+
return sorted_indices[:, :num_topk].contiguous()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def generate_test_data(params):
|
| 23 |
+
num_tokens = params['num_tokens']
|
| 24 |
+
num_experts = params['num_experts']
|
| 25 |
+
num_groups = params['num_groups']
|
| 26 |
+
|
| 27 |
+
num_experts_per_group = num_experts // num_groups
|
| 28 |
+
scores = torch.randn((num_tokens, num_groups, num_experts_per_group), dtype=torch.float, device='cuda')
|
| 29 |
+
|
| 30 |
+
return (scores,)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 34 |
+
return [
|
| 35 |
+
{
|
| 36 |
+
'num_tokens': num_tokens,
|
| 37 |
+
'num_experts': num_experts,
|
| 38 |
+
'num_groups': num_groups,
|
| 39 |
+
'num_group_sum_topk': num_group_sum_topk,
|
| 40 |
+
'num_topk_groups': num_topk_groups,
|
| 41 |
+
}
|
| 42 |
+
for num_tokens in generate_num_tokens(is_benchmark=is_benchmark)
|
| 43 |
+
for num_experts in (72, 256)
|
| 44 |
+
for num_groups in (4, 8, 12, 16)
|
| 45 |
+
if num_experts % num_groups == 0
|
| 46 |
+
for num_group_sum_topk in (1, 2)
|
| 47 |
+
for num_topk_groups in (2, 4)
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 52 |
+
def test_topk_sum_and_topk_group_idx(params):
|
| 53 |
+
(scores,) = generate_test_data(params)
|
| 54 |
+
num_group_sum_topk = params['num_group_sum_topk']
|
| 55 |
+
num_topk_groups = params['num_topk_groups']
|
| 56 |
+
|
| 57 |
+
func = lambda: tile_kernels.moe.topk_sum_and_topk_group_idx(scores, num_group_sum_topk, num_topk_groups)
|
| 58 |
+
|
| 59 |
+
group_idx_ref = torch_topk_sum_and_topk_group_idx(scores, num_group_sum_topk, num_topk_groups)
|
| 60 |
+
group_idx = func()
|
| 61 |
+
|
| 62 |
+
assert_equal(group_idx, group_idx_ref)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@pytest.mark.benchmark
|
| 66 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 67 |
+
def test_topk_sum_and_topk_group_idx_benchmark(benchmark_timer, benchmark_record, params):
|
| 68 |
+
(scores,) = generate_test_data(params)
|
| 69 |
+
num_group_sum_topk = params['num_group_sum_topk']
|
| 70 |
+
num_topk_groups = params['num_topk_groups']
|
| 71 |
+
|
| 72 |
+
func = lambda: tile_kernels.moe.topk_sum_and_topk_group_idx(scores, num_group_sum_topk, num_topk_groups)
|
| 73 |
+
|
| 74 |
+
group_idx = func()
|
| 75 |
+
|
| 76 |
+
t_us = benchmark_timer(func)
|
| 77 |
+
num_bytes = count_bytes(scores, group_idx)
|
| 78 |
+
bandwidth_gbs = num_bytes / t_us / 1e3
|
| 79 |
+
|
| 80 |
+
benchmark_record(
|
| 81 |
+
kernel='topk_sum_and_topk_group_idx',
|
| 82 |
+
operation='fwd',
|
| 83 |
+
params=params,
|
| 84 |
+
time_us=t_us,
|
| 85 |
+
bandwidth_gbs=bandwidth_gbs,
|
| 86 |
+
)
|
tile_kernels_src/tests/pytest_benchmark_plugin.py
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Benchmark & GPU memory profiling pytest plugin for tile_kernels.
|
| 2 |
+
|
| 3 |
+
CLI options, markers, fixtures, and regression reporting for kernel
|
| 4 |
+
benchmarks and GPU memory profiling.
|
| 5 |
+
|
| 6 |
+
This file is deliberately NOT named ``conftest.py`` — it is loaded via
|
| 7 |
+
``pytest_plugins`` in the root ``conftest.py``. A non-conftest name
|
| 8 |
+
prevents pluggy's duplicate-registration error.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import math
|
| 13 |
+
import os
|
| 14 |
+
import threading
|
| 15 |
+
|
| 16 |
+
import pytest
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
from tile_kernels.testing.bench import make_param_key
|
| 20 |
+
|
| 21 |
+
# Baseline file, co-located with this plugin
|
| 22 |
+
_BASELINES_PATH = os.path.join(os.path.dirname(__file__), 'benchmark_baselines.jsonl')
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# Prefix stripped from pytest node IDs to form stable, short keys
|
| 26 |
+
_TILE_KERNELS_PREFIX = os.path.join('tests', '')
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# ---------------------------------------------------------------------------
|
| 30 |
+
# CLI options
|
| 31 |
+
# ---------------------------------------------------------------------------
|
| 32 |
+
|
| 33 |
+
def pytest_addoption(parser):
|
| 34 |
+
parser.addoption(
|
| 35 |
+
'--run-benchmark',
|
| 36 |
+
action='store_true',
|
| 37 |
+
default=False,
|
| 38 |
+
help='Run benchmark tests (skipped by default)',
|
| 39 |
+
)
|
| 40 |
+
parser.addoption(
|
| 41 |
+
'--benchmark-output',
|
| 42 |
+
default=None,
|
| 43 |
+
help='Path to write benchmark results as JSONL (one JSON object per line)',
|
| 44 |
+
)
|
| 45 |
+
parser.addoption(
|
| 46 |
+
'--benchmark-regression-threshold',
|
| 47 |
+
default=0.15,
|
| 48 |
+
type=float,
|
| 49 |
+
help='Fraction of slowdown that triggers a regression warning (default: 0.15 = 15%%)',
|
| 50 |
+
)
|
| 51 |
+
parser.addoption(
|
| 52 |
+
'--benchmark-verbose',
|
| 53 |
+
action='store_true',
|
| 54 |
+
default=False,
|
| 55 |
+
help='Show extras columns (e.g., speedup, …) in the benchmark regression report',
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# ---------------------------------------------------------------------------
|
| 60 |
+
# Marker registration & GPU binding
|
| 61 |
+
# ---------------------------------------------------------------------------
|
| 62 |
+
|
| 63 |
+
def pytest_configure(config):
|
| 64 |
+
config.addinivalue_line('markers', 'benchmark: mark test as benchmark (skip by default)')
|
| 65 |
+
# Bind each xdist worker to a GPU via CUDA_VISIBLE_DEVICES and restrict
|
| 66 |
+
# per-process GPU memory so that concurrent workers don't OOM.
|
| 67 |
+
worker_id = os.environ.get('PYTEST_XDIST_WORKER', None)
|
| 68 |
+
if worker_id is not None:
|
| 69 |
+
gpu_id = int(worker_id.replace('gw', ''))
|
| 70 |
+
num_gpus = torch.cuda.device_count()
|
| 71 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_id % num_gpus)
|
| 72 |
+
|
| 73 |
+
# Restrict each worker's GPU memory to (total - 10 GB) / workers_per_gpu.
|
| 74 |
+
# PYTEST_XDIST_WORKER_COUNT is set by pytest-xdist automatically.
|
| 75 |
+
total_workers = int(os.environ.get('PYTEST_XDIST_WORKER_COUNT', '1'))
|
| 76 |
+
workers_per_gpu = math.ceil(total_workers / num_gpus)
|
| 77 |
+
_reserve_bytes = 10 * (1024 ** 3) # 10 GB reserved for system / frameworks
|
| 78 |
+
total_mem = torch.cuda.mem_get_info(0)[1]
|
| 79 |
+
usable_mem = max(total_mem - _reserve_bytes, 0)
|
| 80 |
+
mem_per_worker = usable_mem / workers_per_gpu
|
| 81 |
+
fraction = mem_per_worker / total_mem
|
| 82 |
+
fraction = max(min(fraction, 1.0), 0.0)
|
| 83 |
+
torch.cuda.set_per_process_memory_fraction(fraction)
|
| 84 |
+
|
| 85 |
+
# Shared state for collecting benchmark results across this session
|
| 86 |
+
config._benchmark_results = []
|
| 87 |
+
config._benchmark_results_lock = threading.Lock()
|
| 88 |
+
|
| 89 |
+
# Disable warnings during benchmark setting
|
| 90 |
+
if config.getoption('--run-benchmark', default=None):
|
| 91 |
+
config.option.disable_warnings = True
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def pytest_collection_modifyitems(config, items):
|
| 95 |
+
if not config.getoption('--run-benchmark'):
|
| 96 |
+
# Without --run-benchmark, skip all benchmark tests
|
| 97 |
+
skip_bench = pytest.mark.skip(reason='need --run-benchmark to run')
|
| 98 |
+
for item in items:
|
| 99 |
+
if 'benchmark' in item.keywords:
|
| 100 |
+
item.add_marker(skip_bench)
|
| 101 |
+
# With --run-benchmark, benchmark tests run alongside correctness tests
|
| 102 |
+
# (e.g. `pytest kernel.py --run-benchmark`).
|
| 103 |
+
# Use `-m benchmark` explicitly if you want ONLY benchmarks.
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# ---------------------------------------------------------------------------
|
| 108 |
+
# Regression detection & exit code
|
| 109 |
+
# ---------------------------------------------------------------------------
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _detect_regressions(config):
|
| 113 |
+
"""Check benchmark results against baselines and return regressions.
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
A tuple ``(results, baselines, regressions, improvements, missing)``
|
| 117 |
+
or ``None`` if no results were collected.
|
| 118 |
+
"""
|
| 119 |
+
results = getattr(config, '_benchmark_results', [])
|
| 120 |
+
if not results:
|
| 121 |
+
output_path = config.getoption('--benchmark-output', default=None)
|
| 122 |
+
if output_path and os.path.exists(output_path):
|
| 123 |
+
with open(output_path) as f:
|
| 124 |
+
results = [json.loads(line) for line in f if line.strip()]
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
threshold = config.getoption('--benchmark-regression-threshold')
|
| 128 |
+
baselines = _load_baselines()
|
| 129 |
+
|
| 130 |
+
regressions = []
|
| 131 |
+
improvements = []
|
| 132 |
+
missing = []
|
| 133 |
+
|
| 134 |
+
for rec in results:
|
| 135 |
+
key = _make_key(rec)
|
| 136 |
+
if key not in baselines:
|
| 137 |
+
missing.append((key, rec['time_us']))
|
| 138 |
+
continue
|
| 139 |
+
baseline_us = baselines[key]['time_us']
|
| 140 |
+
current_us = rec['time_us']
|
| 141 |
+
ratio = current_us / baseline_us
|
| 142 |
+
if ratio > 1.0 + threshold:
|
| 143 |
+
regressions.append((key, baseline_us, current_us, ratio))
|
| 144 |
+
elif ratio < 1.0 - threshold:
|
| 145 |
+
improvements.append((key, baseline_us, current_us, ratio))
|
| 146 |
+
|
| 147 |
+
return results, baselines, regressions, improvements, missing
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def pytest_sessionfinish(session, exitstatus):
|
| 151 |
+
"""Set non-zero exit code when benchmark regressions are detected.
|
| 152 |
+
|
| 153 |
+
Runs before ``pytest_terminal_summary``, so regression detection is
|
| 154 |
+
performed here and stashed on ``config`` for the terminal report.
|
| 155 |
+
"""
|
| 156 |
+
result = _detect_regressions(session.config)
|
| 157 |
+
if result is None:
|
| 158 |
+
return
|
| 159 |
+
results, baselines, regressions, improvements, missing = result
|
| 160 |
+
# Stash for pytest_terminal_summary
|
| 161 |
+
session.config._benchmark_detection = result
|
| 162 |
+
if (regressions or missing) and exitstatus == 0:
|
| 163 |
+
session.exitstatus = 1
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# ---------------------------------------------------------------------------
|
| 167 |
+
# Terminal summary: regression report
|
| 168 |
+
# ---------------------------------------------------------------------------
|
| 169 |
+
|
| 170 |
+
def pytest_terminal_summary(terminalreporter, config):
|
| 171 |
+
"""Print a benchmark regression report at the end of the pytest session."""
|
| 172 |
+
# Use pre-computed results from pytest_sessionfinish if available,
|
| 173 |
+
# otherwise compute now
|
| 174 |
+
detection = getattr(config, '_benchmark_detection', None)
|
| 175 |
+
if detection is None:
|
| 176 |
+
detection = _detect_regressions(config)
|
| 177 |
+
if detection is None:
|
| 178 |
+
# No benchmark results — nothing to report
|
| 179 |
+
return
|
| 180 |
+
|
| 181 |
+
results, baselines, regressions, improvements, missing = detection
|
| 182 |
+
threshold = config.getoption('--benchmark-regression-threshold')
|
| 183 |
+
verbose = config.getoption('--benchmark-verbose')
|
| 184 |
+
|
| 185 |
+
tr = terminalreporter
|
| 186 |
+
tr.section('Benchmark Regression Report')
|
| 187 |
+
|
| 188 |
+
if baselines:
|
| 189 |
+
# Collect extras column names when verbose
|
| 190 |
+
extras_keys = []
|
| 191 |
+
if verbose:
|
| 192 |
+
extras_keys = _collect_extras_keys(results, baselines)
|
| 193 |
+
|
| 194 |
+
# Compute dynamic Kernel column width
|
| 195 |
+
matched_keys = [
|
| 196 |
+
_make_key(r) for r in results if _make_key(r) in baselines
|
| 197 |
+
]
|
| 198 |
+
kw = max((len(k) for k in matched_keys), default=20) + 2
|
| 199 |
+
|
| 200 |
+
# Extras column widths: fit header label or widest value
|
| 201 |
+
ek_widths = {}
|
| 202 |
+
for ek in extras_keys:
|
| 203 |
+
cur_label = ek + '(cur)'
|
| 204 |
+
ref_label = ek + '(ref)'
|
| 205 |
+
w = max(len(cur_label), len(ref_label), 8)
|
| 206 |
+
for rec in results:
|
| 207 |
+
rk = _make_key(rec)
|
| 208 |
+
if rk not in baselines:
|
| 209 |
+
continue
|
| 210 |
+
for src in (rec, baselines[rk]):
|
| 211 |
+
v = (src.get('extras') or {}).get(ek)
|
| 212 |
+
w = max(w, len(_fmt_extra(v)))
|
| 213 |
+
ek_widths[ek] = w
|
| 214 |
+
|
| 215 |
+
# Header
|
| 216 |
+
hdr = (
|
| 217 |
+
f"{'Kernel':<{kw}} {'Latency':>11} {'Bandwidth':>11} {'Ratio':>8} {'Stat':>4}"
|
| 218 |
+
)
|
| 219 |
+
for ek in extras_keys:
|
| 220 |
+
w = ek_widths[ek]
|
| 221 |
+
hdr += f" {(ek + '(cur)'):>{w}} {(ek + '(ref)'):>{w}}"
|
| 222 |
+
tr.write_line(hdr)
|
| 223 |
+
tr.write_line('-' * len(hdr))
|
| 224 |
+
|
| 225 |
+
for rec in results:
|
| 226 |
+
key = _make_key(rec)
|
| 227 |
+
if key not in baselines:
|
| 228 |
+
continue
|
| 229 |
+
baseline_rec = baselines[key]
|
| 230 |
+
baseline_us = baseline_rec['time_us']
|
| 231 |
+
current_us = rec['time_us']
|
| 232 |
+
ratio = current_us / baseline_us
|
| 233 |
+
if ratio > 1.0 + threshold:
|
| 234 |
+
status = '--'
|
| 235 |
+
elif ratio < 1.0 - threshold:
|
| 236 |
+
status = '++'
|
| 237 |
+
else:
|
| 238 |
+
status = '='
|
| 239 |
+
cur_bw = rec['bandwidth_gbs']
|
| 240 |
+
line = (
|
| 241 |
+
f'{key:<{kw}} {current_us:>8.1f} us {_fmt_bw(cur_bw):>11} '
|
| 242 |
+
f'{ratio:>7.2f}x {status:>4}'
|
| 243 |
+
)
|
| 244 |
+
for ek in extras_keys:
|
| 245 |
+
w = ek_widths[ek]
|
| 246 |
+
cur_v = (rec.get('extras') or {}).get(ek)
|
| 247 |
+
ref_v = (baseline_rec.get('extras') or {}).get(ek)
|
| 248 |
+
line += f' {_fmt_extra(cur_v):>{w}} {_fmt_extra(ref_v):>{w}}'
|
| 249 |
+
tr.write_line(line)
|
| 250 |
+
else:
|
| 251 |
+
tr.write_line('No baseline file found — skipping regression comparison.')
|
| 252 |
+
tr.write_line(f' (looked at: {_BASELINES_PATH})')
|
| 253 |
+
|
| 254 |
+
# New benchmarks without baselines
|
| 255 |
+
if missing:
|
| 256 |
+
new_recs = [r for r in results if _make_key(r) not in baselines]
|
| 257 |
+
tr.write_line('')
|
| 258 |
+
|
| 259 |
+
# Dynamic column widths
|
| 260 |
+
new_keys = [_make_key(r) for r in new_recs]
|
| 261 |
+
nkw = max((len(k) for k in new_keys), default=20) + 2
|
| 262 |
+
|
| 263 |
+
# Bandwidth column width for new-benchmarks table
|
| 264 |
+
new_bw_col_w = 9
|
| 265 |
+
for r in new_recs:
|
| 266 |
+
v = r.get('bandwidth_gbs', None)
|
| 267 |
+
new_bw_col_w = max(new_bw_col_w, len(_fmt_bw(v)))
|
| 268 |
+
|
| 269 |
+
new_extras_keys = []
|
| 270 |
+
new_ek_widths = {}
|
| 271 |
+
if verbose:
|
| 272 |
+
ek_set = set()
|
| 273 |
+
for r in new_recs:
|
| 274 |
+
ek_set.update((r.get('extras') or {}).keys())
|
| 275 |
+
new_extras_keys = sorted(ek_set)
|
| 276 |
+
for ek in new_extras_keys:
|
| 277 |
+
w = len(ek)
|
| 278 |
+
for r in new_recs:
|
| 279 |
+
v = (r.get('extras') or {}).get(ek)
|
| 280 |
+
w = max(w, len(_fmt_extra(v)))
|
| 281 |
+
new_ek_widths[ek] = max(w, 8)
|
| 282 |
+
|
| 283 |
+
# Header
|
| 284 |
+
nhdr = f"{'Kernel':<{nkw}} {'Current':>11} {'Bandwidth':>{new_bw_col_w}}"
|
| 285 |
+
for ek in new_extras_keys:
|
| 286 |
+
nhdr += f' {ek:>{new_ek_widths[ek]}}'
|
| 287 |
+
tr.write_line(nhdr)
|
| 288 |
+
tr.write_line('-' * len(nhdr))
|
| 289 |
+
|
| 290 |
+
for r in new_recs:
|
| 291 |
+
key = _make_key(r)
|
| 292 |
+
bw = r.get('bandwidth_gbs', None)
|
| 293 |
+
line = f"{key:<{nkw}} {r['time_us']:>8.1f} us {_fmt_bw(bw):>{new_bw_col_w}}"
|
| 294 |
+
for ek in new_extras_keys:
|
| 295 |
+
w = new_ek_widths[ek]
|
| 296 |
+
v = (r.get('extras') or {}).get(ek)
|
| 297 |
+
line += f' {_fmt_extra(v):>{w}}'
|
| 298 |
+
tr.write_line(line)
|
| 299 |
+
|
| 300 |
+
# Summary
|
| 301 |
+
matched = sum(1 for r in results if baselines and _make_key(r) in baselines)
|
| 302 |
+
tr.write_line('')
|
| 303 |
+
tr.write_line(
|
| 304 |
+
f'Total: {len(results)} benchmarks, {matched} with baselines, '
|
| 305 |
+
f'{len(missing)} missing, '
|
| 306 |
+
f'{len(regressions)} regressions, {len(improvements)} improvements '
|
| 307 |
+
f'(threshold: {threshold:.0%})'
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
if regressions:
|
| 311 |
+
tr.write_line('')
|
| 312 |
+
tr.write_line('!! REGRESSIONS DETECTED !!')
|
| 313 |
+
for key, baseline_us, current_us, ratio in regressions:
|
| 314 |
+
tr.write_line(
|
| 315 |
+
f' {key}: {current_us:.1f} us vs baseline {baseline_us:.1f} us '
|
| 316 |
+
f'({ratio:.2f}x slower)'
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _fmt_extra(v):
|
| 322 |
+
"""Format an extras value for display."""
|
| 323 |
+
if v is None:
|
| 324 |
+
return '-'
|
| 325 |
+
if isinstance(v, float):
|
| 326 |
+
return f'{v:.2f}'
|
| 327 |
+
return str(v)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _fmt_bw(v):
|
| 331 |
+
"""Format a bandwidth_gbs value for display (e.g. '1234.56 GB/s')."""
|
| 332 |
+
if v is None:
|
| 333 |
+
return '-'
|
| 334 |
+
return f'{v:6.1f} GB/s'
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def _collect_extras_keys(results, baselines):
|
| 338 |
+
"""Return a sorted list of extras keys across results and baselines,
|
| 339 |
+
excluding bandwidth_gbs (reported as a dedicated column)."""
|
| 340 |
+
keys = set()
|
| 341 |
+
for rec in results:
|
| 342 |
+
key = _make_key(rec)
|
| 343 |
+
if key not in baselines:
|
| 344 |
+
continue
|
| 345 |
+
for e in (rec.get('extras') or {}, (baselines[key].get('extras') or {})):
|
| 346 |
+
keys.update(e.keys())
|
| 347 |
+
return sorted(keys)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
# ---------------------------------------------------------------------------
|
| 351 |
+
# Fixtures
|
| 352 |
+
# ---------------------------------------------------------------------------
|
| 353 |
+
|
| 354 |
+
# Lock for concurrent JSONL writes from xdist workers
|
| 355 |
+
_jsonl_write_lock = threading.Lock()
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@pytest.fixture
|
| 359 |
+
def benchmark_record(request):
|
| 360 |
+
"""Record a benchmark result for regression tracking.
|
| 361 |
+
|
| 362 |
+
Prints a human-readable summary, appends a JSONL record to
|
| 363 |
+
``--benchmark-output`` (if given), collects the result for the terminal
|
| 364 |
+
regression report, and emits a pytest warning on regressions.
|
| 365 |
+
|
| 366 |
+
JSONL schema::
|
| 367 |
+
|
| 368 |
+
{
|
| 369 |
+
"kernel": str,
|
| 370 |
+
"operation": str,
|
| 371 |
+
"params": dict,
|
| 372 |
+
"time_us": float,
|
| 373 |
+
"bandwidth_gbs": float | None,
|
| 374 |
+
"extras": dict | None,
|
| 375 |
+
}
|
| 376 |
+
"""
|
| 377 |
+
output_path = request.config.getoption('--benchmark-output')
|
| 378 |
+
|
| 379 |
+
def _record(*, kernel, operation, params, time_us, bandwidth_gbs=None, extras=None):
|
| 380 |
+
# Build a unique key: kernel/operation[k1=v1,k2=v2]
|
| 381 |
+
# Keys are sorted for deterministic ordering
|
| 382 |
+
if params:
|
| 383 |
+
param_str = make_param_key(params)
|
| 384 |
+
key = f'{kernel}/{operation}[{param_str}]'
|
| 385 |
+
else:
|
| 386 |
+
key = f'{kernel}/{operation}'
|
| 387 |
+
|
| 388 |
+
# Human-readable print
|
| 389 |
+
parts = [f' BENCH {key}: {time_us:.1f} us']
|
| 390 |
+
if bandwidth_gbs is not None:
|
| 391 |
+
parts.append(f', bandwidth_gbs={bandwidth_gbs:.2f}')
|
| 392 |
+
if extras:
|
| 393 |
+
for ek, ev in extras.items():
|
| 394 |
+
if isinstance(ev, float):
|
| 395 |
+
parts.append(f', {ek}={ev:.2f}')
|
| 396 |
+
else:
|
| 397 |
+
parts.append(f', {ek}={ev}')
|
| 398 |
+
print(''.join(parts))
|
| 399 |
+
|
| 400 |
+
# Write JSONL
|
| 401 |
+
record = {
|
| 402 |
+
'kernel': kernel,
|
| 403 |
+
'operation': operation,
|
| 404 |
+
'params': dict(sorted(params.items())) if params else params,
|
| 405 |
+
'time_us': round(time_us, 2),
|
| 406 |
+
}
|
| 407 |
+
if bandwidth_gbs is not None:
|
| 408 |
+
record['bandwidth_gbs'] = round(bandwidth_gbs, 4)
|
| 409 |
+
if extras:
|
| 410 |
+
record['extras'] = {
|
| 411 |
+
k: round(v, 4) if isinstance(v, float) else v
|
| 412 |
+
for k, v in extras.items()
|
| 413 |
+
}
|
| 414 |
+
if output_path:
|
| 415 |
+
line = json.dumps(record, ensure_ascii=False)
|
| 416 |
+
with _jsonl_write_lock:
|
| 417 |
+
with open(output_path, 'a') as f:
|
| 418 |
+
f.write(line + '\n')
|
| 419 |
+
|
| 420 |
+
# Collect for terminal summary
|
| 421 |
+
with request.config._benchmark_results_lock:
|
| 422 |
+
request.config._benchmark_results.append(record)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
return _record
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
@pytest.fixture
|
| 429 |
+
def benchmark_timer():
|
| 430 |
+
"""Return a callable that measures kernel execution time in microseconds.
|
| 431 |
+
|
| 432 |
+
Wraps ``tilelang.profiler.bench.do_bench`` with CUPTI backend by default.
|
| 433 |
+
Keyword arguments are forwarded to ``do_bench``, allowing per-test
|
| 434 |
+
overrides (e.g. ``benchmark_timer(fn, rep=30)``).
|
| 435 |
+
|
| 436 |
+
Returns:
|
| 437 |
+
A callable ``(fn, **overrides) -> float`` returning time in
|
| 438 |
+
microseconds.
|
| 439 |
+
"""
|
| 440 |
+
from tilelang.profiler.bench import do_bench
|
| 441 |
+
|
| 442 |
+
def _timer(fn, **overrides):
|
| 443 |
+
kwargs = dict(backend='cupti', warmup=0, rep=30)
|
| 444 |
+
kwargs.update(overrides)
|
| 445 |
+
return do_bench(fn, **kwargs) * 1e3 # ms → us
|
| 446 |
+
|
| 447 |
+
return _timer
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def _make_key(rec):
|
| 451 |
+
"""Build a baseline-compatible key from a benchmark record."""
|
| 452 |
+
kernel, operation = rec['kernel'], rec['operation']
|
| 453 |
+
params = rec.get('params')
|
| 454 |
+
if params:
|
| 455 |
+
param_str = make_param_key(params)
|
| 456 |
+
return f'{kernel}/{operation}[{param_str}]'
|
| 457 |
+
return f'{kernel}/{operation}'
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def _load_baselines():
|
| 461 |
+
"""Load the baseline JSONL file into a ``{key: record}`` dict.
|
| 462 |
+
|
| 463 |
+
Returns ``None`` if the file does not exist.
|
| 464 |
+
"""
|
| 465 |
+
if not os.path.exists(_BASELINES_PATH):
|
| 466 |
+
return {}
|
| 467 |
+
baselines = {}
|
| 468 |
+
with open(_BASELINES_PATH) as f:
|
| 469 |
+
for line in f:
|
| 470 |
+
line = line.strip()
|
| 471 |
+
if not line:
|
| 472 |
+
continue
|
| 473 |
+
rec = json.loads(line)
|
| 474 |
+
baselines[_make_key(rec)] = rec
|
| 475 |
+
return baselines
|
| 476 |
+
|
| 477 |
+
|
tile_kernels_src/tests/pytest_random_plugin.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def pytest_addoption(parser):
|
| 8 |
+
parser.addoption('--seed', type=int, default=0)
|
| 9 |
+
|
| 10 |
+
@pytest.fixture(autouse=True)
|
| 11 |
+
def seed(request):
|
| 12 |
+
base = request.config.getoption('--seed')
|
| 13 |
+
node_hash = int(hashlib.sha256(
|
| 14 |
+
request.node.nodeid.encode()
|
| 15 |
+
).hexdigest(), 16) % (2**31)
|
| 16 |
+
seed = base + node_hash
|
| 17 |
+
torch.manual_seed(seed)
|
| 18 |
+
return seed
|
tile_kernels_src/tests/quant/test_cast_back.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
import tile_kernels
|
| 6 |
+
from tile_kernels.testing.bench import dtype_to_str, make_param_id
|
| 7 |
+
from tile_kernels.testing.generator import generate_hidden_sizes, generate_num_tokens
|
| 8 |
+
from tile_kernels.testing.numeric import assert_equal, calc_diff, count_bytes
|
| 9 |
+
|
| 10 |
+
# Disable TileLang prints
|
| 11 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def generate_test_data_per_token(params):
|
| 15 |
+
num_tokens = params['num_tokens']
|
| 16 |
+
hidden = params['hidden']
|
| 17 |
+
fmt = params['fmt']
|
| 18 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 19 |
+
round_sf = params['round_sf']
|
| 20 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 21 |
+
num_per_channels = params['num_per_channels']
|
| 22 |
+
out_dtype = params['out_dtype']
|
| 23 |
+
|
| 24 |
+
x = torch.randn((num_tokens, hidden), dtype=out_dtype, device='cuda')
|
| 25 |
+
x_fp8, x_sf = tile_kernels.quant.per_token_cast(
|
| 26 |
+
x, fmt, num_per_channels=num_per_channels,
|
| 27 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf,
|
| 28 |
+
round_sf=round_sf,
|
| 29 |
+
use_packed_ue8m0=use_packed_ue8m0,
|
| 30 |
+
)
|
| 31 |
+
out_dtype_str = dtype_to_str(out_dtype)
|
| 32 |
+
func = lambda: tile_kernels.quant.per_token_cast_back((x_fp8, x_sf), out_dtype_str, num_per_channels=num_per_channels)
|
| 33 |
+
|
| 34 |
+
return (x, x_fp8, x_sf, out_dtype_str, func)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def generate_test_data(params):
|
| 38 |
+
num_tokens = params['num_tokens']
|
| 39 |
+
hidden = params['hidden']
|
| 40 |
+
round_sf = params['round_sf']
|
| 41 |
+
fmt = params['fmt']
|
| 42 |
+
out_dtype = params['out_dtype']
|
| 43 |
+
num_per_tokens = params['num_per_tokens']
|
| 44 |
+
num_per_channels = params['num_per_channels']
|
| 45 |
+
|
| 46 |
+
x = torch.randn((num_tokens, hidden), dtype=out_dtype, device='cuda')
|
| 47 |
+
x_casted, x_sf = tile_kernels.torch.cast(x, fmt, (num_per_tokens, num_per_channels), round_sf=round_sf)
|
| 48 |
+
out_dtype_str = dtype_to_str(out_dtype)
|
| 49 |
+
func = lambda: tile_kernels.quant.cast_back(
|
| 50 |
+
(x_casted, x_sf), out_dtype_str, (num_per_tokens, num_per_channels)
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
return (x, x_casted, x_sf, out_dtype_str, func)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def generate_test_params_per_token(is_benchmark: bool) -> list[dict]:
|
| 57 |
+
return [
|
| 58 |
+
{
|
| 59 |
+
'num_tokens': num_tokens,
|
| 60 |
+
'hidden': hidden_size,
|
| 61 |
+
'fmt': fmt,
|
| 62 |
+
'use_tma_aligned_col_major_sf': use_tma_aligned_col_major_sf,
|
| 63 |
+
'round_sf': round_sf,
|
| 64 |
+
'use_packed_ue8m0': use_packed_ue8m0,
|
| 65 |
+
'num_per_channels': num_per_channels,
|
| 66 |
+
'out_dtype': out_dtype,
|
| 67 |
+
}
|
| 68 |
+
for num_tokens in generate_num_tokens(is_benchmark=is_benchmark)
|
| 69 |
+
for hidden_size in generate_hidden_sizes()
|
| 70 |
+
for fmt in ('e2m1', 'e4m3')
|
| 71 |
+
for use_tma_aligned_col_major_sf, round_sf, use_packed_ue8m0 in [(False, True, False), (True, True, True)]
|
| 72 |
+
for num_per_channels in (128, hidden_size)
|
| 73 |
+
for out_dtype in (torch.float32, torch.bfloat16)
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 78 |
+
return [
|
| 79 |
+
{
|
| 80 |
+
'num_tokens': num_tokens,
|
| 81 |
+
'hidden': hidden_size,
|
| 82 |
+
'round_sf': round_sf,
|
| 83 |
+
'fmt': fmt,
|
| 84 |
+
'out_dtype': out_dtype,
|
| 85 |
+
'num_per_tokens': num_per_tokens,
|
| 86 |
+
'num_per_channels': num_per_channels,
|
| 87 |
+
}
|
| 88 |
+
for num_tokens in generate_num_tokens(is_benchmark=is_benchmark)
|
| 89 |
+
for hidden_size in generate_hidden_sizes()
|
| 90 |
+
for round_sf in (False, True)
|
| 91 |
+
for fmt in ('e4m3',)
|
| 92 |
+
for out_dtype in (torch.bfloat16, torch.float32)
|
| 93 |
+
for num_per_tokens, num_per_channels in ((128, 1), (128, 128))
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@pytest.mark.parametrize('params', generate_test_params_per_token(is_benchmark=False), ids=make_param_id)
|
| 98 |
+
def test_cast_back_per_token(params):
|
| 99 |
+
hidden = params['hidden']
|
| 100 |
+
fmt = params['fmt']
|
| 101 |
+
num_per_channels = params['num_per_channels']
|
| 102 |
+
|
| 103 |
+
# Test correctness
|
| 104 |
+
x, x_fp8, x_sf, out_dtype_str, func = generate_test_data_per_token(params)
|
| 105 |
+
x_fp8_bf16 = func()
|
| 106 |
+
x_fp8_bf16_ref = tile_kernels.torch.cast_back((x_fp8, x_sf), out_dtype_str, (1, num_per_channels))
|
| 107 |
+
|
| 108 |
+
diff = calc_diff(x, x_fp8_bf16)
|
| 109 |
+
assert diff < (2e-2 if fmt == 'e2m1' else 1e-3), f'{x}, {x_fp8_bf16}, {fmt=}, {hidden=}, {num_per_channels=}, {diff=}'
|
| 110 |
+
|
| 111 |
+
assert_equal(x_fp8_bf16, x_fp8_bf16_ref)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@pytest.mark.benchmark
|
| 115 |
+
@pytest.mark.parametrize('params', generate_test_params_per_token(is_benchmark=True), ids=make_param_id)
|
| 116 |
+
def test_cast_back_per_token_benchmark(benchmark_timer, benchmark_record, params):
|
| 117 |
+
x, x_fp8, x_sf, out_dtype_str, func = generate_test_data_per_token(params)
|
| 118 |
+
|
| 119 |
+
t_us = benchmark_timer(func)
|
| 120 |
+
num_bytes = count_bytes(x, x_fp8, x_sf)
|
| 121 |
+
|
| 122 |
+
benchmark_record(
|
| 123 |
+
kernel='cast_back_per_token',
|
| 124 |
+
operation='fwd',
|
| 125 |
+
params={**params, 'out_dtype': out_dtype_str},
|
| 126 |
+
time_us=t_us,
|
| 127 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 132 |
+
def test_cast_back(params):
|
| 133 |
+
num_per_tokens = params['num_per_tokens']
|
| 134 |
+
num_per_channels = params['num_per_channels']
|
| 135 |
+
|
| 136 |
+
_, x_casted, x_sf, out_dtype_str, func = generate_test_data(params)
|
| 137 |
+
x_casted_back = func()
|
| 138 |
+
x_casted_back_ref = tile_kernels.torch.cast_back((x_casted, x_sf), out_dtype_str, (num_per_tokens, num_per_channels))
|
| 139 |
+
|
| 140 |
+
assert_equal(x_casted_back, x_casted_back_ref)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@pytest.mark.benchmark
|
| 144 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 145 |
+
def test_cast_back_benchmark(benchmark_timer, benchmark_record, params):
|
| 146 |
+
x, x_casted, x_sf, out_dtype_str, func = generate_test_data(params)
|
| 147 |
+
|
| 148 |
+
t_us = benchmark_timer(func)
|
| 149 |
+
num_bytes = count_bytes(x, x_casted, x_sf)
|
| 150 |
+
|
| 151 |
+
benchmark_record(
|
| 152 |
+
kernel='cast_back',
|
| 153 |
+
operation='fwd',
|
| 154 |
+
params={**params, 'out_dtype': out_dtype_str},
|
| 155 |
+
time_us=t_us,
|
| 156 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 157 |
+
)
|
tile_kernels_src/tests/quant/test_cast_back_e5m6.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
import tile_kernels
|
| 6 |
+
from tile_kernels.testing.bench import dtype_to_str, make_param_id
|
| 7 |
+
from tile_kernels.testing.generator import generate_hidden_sizes, generate_num_tokens, generate_e5m6_inputs
|
| 8 |
+
from tile_kernels.testing.numeric import assert_equal, calc_diff, count_bytes
|
| 9 |
+
from tile_kernels.torch import cast_back_from_e5m6
|
| 10 |
+
|
| 11 |
+
# Disable TileLang prints
|
| 12 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def generate_test_data(params):
|
| 16 |
+
x = params['x']
|
| 17 |
+
hidden = params['hidden']
|
| 18 |
+
num_per_channels = params['num_per_channels']
|
| 19 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 20 |
+
round_sf = params['round_sf']
|
| 21 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 22 |
+
out_dtype = params['out_dtype']
|
| 23 |
+
|
| 24 |
+
x_e5m6, x_sf = tile_kernels.quant.per_token_cast(
|
| 25 |
+
x, 'e5m6', num_per_channels=num_per_channels,
|
| 26 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf,
|
| 27 |
+
round_sf=round_sf,
|
| 28 |
+
use_packed_ue8m0=use_packed_ue8m0,
|
| 29 |
+
)
|
| 30 |
+
out_dtype_str = dtype_to_str(out_dtype)
|
| 31 |
+
func = lambda: tile_kernels.quant.cast_back((x_e5m6, x_sf), out_dtype_str, (1, hidden), x_special_fmt='e5m6')
|
| 32 |
+
torch_ref_func = lambda: cast_back_from_e5m6((x_e5m6, x_sf), out_dtype_str, (1, hidden))
|
| 33 |
+
|
| 34 |
+
return (x_e5m6, x_sf, out_dtype_str, func, torch_ref_func)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 38 |
+
return [
|
| 39 |
+
{
|
| 40 |
+
'num_tokens': num_tokens,
|
| 41 |
+
'hidden': hidden_size,
|
| 42 |
+
'num_per_channels': num_per_channels,
|
| 43 |
+
'use_tma_aligned_col_major_sf': use_tma_aligned_col_major_sf,
|
| 44 |
+
'round_sf': round_sf,
|
| 45 |
+
'use_packed_ue8m0': use_packed_ue8m0,
|
| 46 |
+
'out_dtype': out_dtype,
|
| 47 |
+
}
|
| 48 |
+
for num_tokens in generate_num_tokens(is_benchmark=is_benchmark)
|
| 49 |
+
for hidden_size in generate_hidden_sizes()
|
| 50 |
+
for num_per_channels in (hidden_size, )
|
| 51 |
+
for use_tma_aligned_col_major_sf, round_sf, use_packed_ue8m0 in [(False, True, False), (True, True, True)]
|
| 52 |
+
for out_dtype in (torch.bfloat16, torch.float32)
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 57 |
+
def test_cast_back_e5m6(params):
|
| 58 |
+
num_tokens = params['num_tokens']
|
| 59 |
+
hidden = params['hidden']
|
| 60 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 61 |
+
round_sf = params['round_sf']
|
| 62 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 63 |
+
out_dtype = params['out_dtype']
|
| 64 |
+
num_per_channels = params['num_per_channels']
|
| 65 |
+
|
| 66 |
+
for x, is_special in generate_e5m6_inputs(num_tokens, hidden, out_dtype):
|
| 67 |
+
x_e5m6, x_sf, out_dtype_str, func, torch_ref_func = generate_test_data({
|
| 68 |
+
'x': x,
|
| 69 |
+
'hidden': hidden,
|
| 70 |
+
'num_per_channels': num_per_channels,
|
| 71 |
+
'use_tma_aligned_col_major_sf': use_tma_aligned_col_major_sf,
|
| 72 |
+
'round_sf': round_sf,
|
| 73 |
+
'use_packed_ue8m0': use_packed_ue8m0,
|
| 74 |
+
'out_dtype': out_dtype,
|
| 75 |
+
})
|
| 76 |
+
x_back = func()
|
| 77 |
+
|
| 78 |
+
# Check accuracy vs original input
|
| 79 |
+
diff = calc_diff(x, x_back)
|
| 80 |
+
threshold = 5e-6 if is_special else 1e-4
|
| 81 |
+
assert diff < threshold, f'{hidden=}, {round_sf=}, {out_dtype_str=}, {diff=}'
|
| 82 |
+
|
| 83 |
+
# Check against torch/cast reference (always runs)
|
| 84 |
+
x_back_ref = torch_ref_func()
|
| 85 |
+
assert_equal(x_back, x_back_ref)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@pytest.mark.benchmark
|
| 89 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 90 |
+
def test_cast_back_e5m6_benchmark(benchmark_timer, benchmark_record, params):
|
| 91 |
+
hidden = params['hidden']
|
| 92 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 93 |
+
out_dtype = params['out_dtype']
|
| 94 |
+
|
| 95 |
+
num_per_channels = hidden
|
| 96 |
+
for x, is_special in generate_e5m6_inputs(params['num_tokens'], hidden, out_dtype):
|
| 97 |
+
if is_special:
|
| 98 |
+
continue
|
| 99 |
+
|
| 100 |
+
x_e5m6, x_sf, out_dtype_str, func, torch_ref_func = generate_test_data({
|
| 101 |
+
'x': x,
|
| 102 |
+
'hidden': hidden,
|
| 103 |
+
'num_per_channels': num_per_channels,
|
| 104 |
+
'use_tma_aligned_col_major_sf': use_tma_aligned_col_major_sf,
|
| 105 |
+
'round_sf': params['round_sf'],
|
| 106 |
+
'use_packed_ue8m0': params['use_packed_ue8m0'],
|
| 107 |
+
'out_dtype': out_dtype,
|
| 108 |
+
})
|
| 109 |
+
x_back = func()
|
| 110 |
+
|
| 111 |
+
t_us = benchmark_timer(func)
|
| 112 |
+
num_bytes = count_bytes(x_e5m6, x_sf, x_back)
|
| 113 |
+
|
| 114 |
+
benchmark_record(
|
| 115 |
+
kernel='cast_back_e5m6',
|
| 116 |
+
operation='fwd',
|
| 117 |
+
params={**params, 'num_per_channels': num_per_channels, 'out_dtype': out_dtype_str},
|
| 118 |
+
time_us=t_us,
|
| 119 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 120 |
+
)
|
tile_kernels_src/tests/quant/test_per_block_cast.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
import tile_kernels
|
| 6 |
+
from tile_kernels.testing.bench import dtype_to_str, make_param_id
|
| 7 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes, check_bias
|
| 8 |
+
from tile_kernels.testing.generator import generate_hidden_sizes, generate_num_tokens
|
| 9 |
+
from tile_kernels.testing.quant import clear_unused_sf
|
| 10 |
+
|
| 11 |
+
# Disable TileLang prints
|
| 12 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def generate_test_data(params):
|
| 16 |
+
num_tokens = params['num_tokens']
|
| 17 |
+
hidden = params['hidden']
|
| 18 |
+
in_dtype = params['in_dtype']
|
| 19 |
+
fmt = params['fmt']
|
| 20 |
+
block_size = params['block_size']
|
| 21 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 22 |
+
round_sf = params['round_sf']
|
| 23 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 24 |
+
|
| 25 |
+
x = torch.randn((num_tokens, hidden), dtype=in_dtype, device='cuda')
|
| 26 |
+
base_args = dict(
|
| 27 |
+
x=x, fmt=fmt, block_size=block_size,
|
| 28 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf,
|
| 29 |
+
round_sf=round_sf,
|
| 30 |
+
use_packed_ue8m0=use_packed_ue8m0,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
return (x, base_args)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 37 |
+
return [
|
| 38 |
+
{
|
| 39 |
+
'num_tokens': num_tokens,
|
| 40 |
+
'hidden': hidden_size,
|
| 41 |
+
'in_dtype': in_dtype,
|
| 42 |
+
'fmt': fmt,
|
| 43 |
+
'use_tma_aligned_col_major_sf': use_tma_aligned_col_major_sf,
|
| 44 |
+
'round_sf': round_sf,
|
| 45 |
+
'use_packed_ue8m0': use_packed_ue8m0,
|
| 46 |
+
'block_size': block_size,
|
| 47 |
+
}
|
| 48 |
+
for num_tokens in generate_num_tokens(is_benchmark=is_benchmark)
|
| 49 |
+
for hidden_size in generate_hidden_sizes()
|
| 50 |
+
for in_dtype in (torch.bfloat16, torch.float32)
|
| 51 |
+
for fmt in ('e4m3', 'e2m1')
|
| 52 |
+
for use_tma_aligned_col_major_sf, round_sf, use_packed_ue8m0 in [(False, True, False), (True, True, True)]
|
| 53 |
+
for block_size in ((128, 128), (32, 32))
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 58 |
+
def test_per_block_cast(params):
|
| 59 |
+
hidden = params['hidden']
|
| 60 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 61 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 62 |
+
block_size = params['block_size']
|
| 63 |
+
|
| 64 |
+
x, base_args = generate_test_data(params)
|
| 65 |
+
|
| 66 |
+
# Test cast
|
| 67 |
+
x_casted, per_block_sf_inv = tile_kernels.quant.per_block_cast(**base_args)
|
| 68 |
+
x_casted_ref, per_block_sf_inv_ref = tile_kernels.torch.cast(**base_args)
|
| 69 |
+
x_casted_back = tile_kernels.torch.cast_back((x_casted, per_block_sf_inv), 'fp32', block_size)
|
| 70 |
+
if use_packed_ue8m0:
|
| 71 |
+
per_block_sf_inv = clear_unused_sf(per_block_sf_inv, hidden, block_size[1])
|
| 72 |
+
per_block_sf_inv_ref = clear_unused_sf(per_block_sf_inv_ref, hidden, block_size[1])
|
| 73 |
+
assert_equal(per_block_sf_inv, per_block_sf_inv_ref)
|
| 74 |
+
assert_equal(x_casted, x_casted_ref)
|
| 75 |
+
|
| 76 |
+
# Check bias
|
| 77 |
+
check_bias(x_casted_back, x)
|
| 78 |
+
|
| 79 |
+
# Test cast only mode
|
| 80 |
+
if not use_tma_aligned_col_major_sf:
|
| 81 |
+
# TMA aligned or packed ue8m0 sf is used for FP8/FP4 GEMM, not for other cast
|
| 82 |
+
x_casted = tile_kernels.quant.per_block_cast_with_precomputed_sf(**base_args, sf=per_block_sf_inv)
|
| 83 |
+
x_casted_ref = tile_kernels.torch.cast(**base_args, sf=per_block_sf_inv)
|
| 84 |
+
assert_equal(x_casted, x_casted_ref)
|
| 85 |
+
|
| 86 |
+
# Test sf only mode
|
| 87 |
+
twice_per_block_sf_inv = tile_kernels.quant.per_block_cast_with_sf_only(**base_args)
|
| 88 |
+
if use_packed_ue8m0:
|
| 89 |
+
twice_per_block_sf_inv = clear_unused_sf(twice_per_block_sf_inv, hidden, block_size[1])
|
| 90 |
+
assert_equal(twice_per_block_sf_inv, per_block_sf_inv_ref)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@pytest.mark.benchmark
|
| 94 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 95 |
+
def test_per_block_cast_benchmark(benchmark_timer, benchmark_record, params):
|
| 96 |
+
x, args = generate_test_data(params)
|
| 97 |
+
|
| 98 |
+
x_casted, per_block_sf_inv = tile_kernels.quant.per_block_cast(**args)
|
| 99 |
+
|
| 100 |
+
t_us = benchmark_timer(lambda: tile_kernels.quant.per_block_cast(**args))
|
| 101 |
+
num_bytes = count_bytes(x, x_casted, per_block_sf_inv)
|
| 102 |
+
|
| 103 |
+
params['in_dtype'] = dtype_to_str(params['in_dtype'])
|
| 104 |
+
benchmark_record(
|
| 105 |
+
kernel='per_block_cast',
|
| 106 |
+
operation='fwd',
|
| 107 |
+
params=params,
|
| 108 |
+
time_us=t_us,
|
| 109 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 110 |
+
)
|
tile_kernels_src/tests/quant/test_per_block_cast_lossless.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
import tile_kernels
|
| 7 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 8 |
+
from tile_kernels.testing.generator import generate_hidden_sizes, generate_num_tokens, generate_rand_float
|
| 9 |
+
from tile_kernels.testing.bench import make_param_id
|
| 10 |
+
|
| 11 |
+
# Disable TileLang prints
|
| 12 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def clamp_abs_ratio(t: torch.Tensor, max_ratio: float = 2**9):
|
| 16 |
+
if t.numel() == 0:
|
| 17 |
+
return t
|
| 18 |
+
floor_val = t.abs().max() / max_ratio
|
| 19 |
+
t = torch.sign(t) * torch.max(t.abs(), floor_val)
|
| 20 |
+
return t
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def generate_test_data(params):
|
| 24 |
+
num_tokens = params['num_tokens']
|
| 25 |
+
hidden = params['hidden']
|
| 26 |
+
in_use_tma_aligned_col_major_sf = params['in_use_tma_aligned_col_major_sf']
|
| 27 |
+
in_round_sf = params['in_round_sf']
|
| 28 |
+
in_use_packed_ue8m0 = params['in_use_packed_ue8m0']
|
| 29 |
+
out_use_tma_aligned_col_major_sf = params['out_use_tma_aligned_col_major_sf']
|
| 30 |
+
out_round_sf = params['out_round_sf']
|
| 31 |
+
out_use_packed_ue8m0 = params['out_use_packed_ue8m0']
|
| 32 |
+
in_sf_block_m = params['in_sf_block'][0]
|
| 33 |
+
in_sf_block_k = params['in_sf_block'][1]
|
| 34 |
+
out_sf_block_m = params['out_sf_block'][0]
|
| 35 |
+
out_sf_block_k = params['out_sf_block'][1]
|
| 36 |
+
|
| 37 |
+
x = generate_rand_float((num_tokens, hidden))
|
| 38 |
+
x = clamp_abs_ratio(x)
|
| 39 |
+
x_fp4 = tile_kernels.torch.cast(
|
| 40 |
+
x, 'e2m1', (in_sf_block_m, in_sf_block_k),
|
| 41 |
+
use_tma_aligned_col_major_sf=in_use_tma_aligned_col_major_sf,
|
| 42 |
+
round_sf=in_round_sf,
|
| 43 |
+
use_packed_ue8m0=in_use_packed_ue8m0,
|
| 44 |
+
)
|
| 45 |
+
cast_func = lambda: tile_kernels.quant.per_block_cast_lossless(
|
| 46 |
+
x_fp4, 'e4m3',
|
| 47 |
+
x_block_size=(in_sf_block_m, in_sf_block_k),
|
| 48 |
+
out_block_size=(out_sf_block_m, out_sf_block_k),
|
| 49 |
+
use_tma_aligned_col_major_sf=out_use_tma_aligned_col_major_sf,
|
| 50 |
+
round_sf=out_round_sf,
|
| 51 |
+
use_packed_ue8m0=out_use_packed_ue8m0,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
return (x, x_fp4, cast_func)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 58 |
+
params = [
|
| 59 |
+
{
|
| 60 |
+
'num_tokens': num_tokens,
|
| 61 |
+
'hidden': hidden_size,
|
| 62 |
+
'in_use_tma_aligned_col_major_sf': in_use_tma_aligned_col_major_sf,
|
| 63 |
+
'in_round_sf': in_round_sf,
|
| 64 |
+
'in_use_packed_ue8m0': in_use_packed_ue8m0,
|
| 65 |
+
'out_use_tma_aligned_col_major_sf': out_use_tma_aligned_col_major_sf,
|
| 66 |
+
'out_round_sf': out_round_sf,
|
| 67 |
+
'out_use_packed_ue8m0': out_use_packed_ue8m0,
|
| 68 |
+
'out_sf_block': (out_sf_block_m, out_sf_block_k),
|
| 69 |
+
'in_sf_block': (in_sf_block_m, in_sf_block_k),
|
| 70 |
+
}
|
| 71 |
+
for num_tokens in generate_num_tokens(is_benchmark=is_benchmark)
|
| 72 |
+
for hidden_size in generate_hidden_sizes()
|
| 73 |
+
for in_use_tma_aligned_col_major_sf, in_round_sf, in_use_packed_ue8m0 in [(False, True, False), (True, True, True)]
|
| 74 |
+
for out_use_tma_aligned_col_major_sf, out_round_sf, out_use_packed_ue8m0 in [(False, True, False), (True, True, True)]
|
| 75 |
+
for out_sf_block_m, out_sf_block_k in ((1, 128), (32, 32), (128, 128))
|
| 76 |
+
for in_sf_block_m, in_sf_block_k in ((1, 32),)
|
| 77 |
+
if out_sf_block_m % in_sf_block_m == 0 and out_sf_block_k % in_sf_block_k == 0
|
| 78 |
+
]
|
| 79 |
+
return params
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 83 |
+
def test_per_block_cast_lossless(params):
|
| 84 |
+
out_sf_block = params['out_sf_block']
|
| 85 |
+
in_sf_block = params['in_sf_block']
|
| 86 |
+
|
| 87 |
+
out_sf_block_m, out_sf_block_k = out_sf_block
|
| 88 |
+
in_sf_block_m, in_sf_block_k = in_sf_block
|
| 89 |
+
|
| 90 |
+
# Test Correctness
|
| 91 |
+
_, x_fp4, cast_func = generate_test_data(params)
|
| 92 |
+
x_fp8 = cast_func()
|
| 93 |
+
|
| 94 |
+
x_fp8_fp32_ref = tile_kernels.torch.cast_back(x_fp4, 'fp32', (in_sf_block_m, in_sf_block_k))
|
| 95 |
+
x_fp8_fp32 = tile_kernels.torch.cast_back(x_fp8, 'fp32', (out_sf_block_m, out_sf_block_k))
|
| 96 |
+
assert_equal(x_fp8_fp32, x_fp8_fp32_ref)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@pytest.mark.benchmark
|
| 100 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 101 |
+
def test_per_block_cast_lossless_benchmark(benchmark_timer, benchmark_record, params):
|
| 102 |
+
_, x_fp4, cast_func = generate_test_data(params)
|
| 103 |
+
|
| 104 |
+
x_fp8 = cast_func()
|
| 105 |
+
|
| 106 |
+
t_us = benchmark_timer(cast_func)
|
| 107 |
+
num_bytes = count_bytes(x_fp4, x_fp8)
|
| 108 |
+
benchmark_record(
|
| 109 |
+
kernel='per_block_cast_lossless',
|
| 110 |
+
operation='fwd',
|
| 111 |
+
params=params,
|
| 112 |
+
time_us=t_us,
|
| 113 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 114 |
+
)
|
tile_kernels_src/tests/quant/test_per_channel_cast.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
import tile_kernels
|
| 6 |
+
from tile_kernels.testing.bench import dtype_to_str, make_param_id
|
| 7 |
+
from tile_kernels.testing.generator import generate_hidden_sizes, generate_num_tokens
|
| 8 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes, check_bias
|
| 9 |
+
|
| 10 |
+
# Disable TileLang prints
|
| 11 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def generate_test_data(params):
|
| 15 |
+
num_tokens = params['num_tokens']
|
| 16 |
+
hidden = params['hidden']
|
| 17 |
+
dtype = params['dtype']
|
| 18 |
+
x = torch.randn((num_tokens, hidden), dtype=dtype, device='cuda')
|
| 19 |
+
return x
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 23 |
+
return [
|
| 24 |
+
{
|
| 25 |
+
'num_per_tokens': num_per_tokens,
|
| 26 |
+
'num_tokens': num_tokens,
|
| 27 |
+
'hidden': hidden_size,
|
| 28 |
+
'round_sf': round_sf,
|
| 29 |
+
'dtype': dtype,
|
| 30 |
+
}
|
| 31 |
+
for num_per_tokens in (128,)
|
| 32 |
+
for num_tokens in generate_num_tokens(128, is_benchmark=is_benchmark)
|
| 33 |
+
for hidden_size in generate_hidden_sizes()
|
| 34 |
+
for round_sf in (False, True)
|
| 35 |
+
for dtype in (torch.bfloat16,)
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 40 |
+
def test_per_channel_cast(params):
|
| 41 |
+
num_per_tokens = params['num_per_tokens']
|
| 42 |
+
round_sf = params['round_sf']
|
| 43 |
+
|
| 44 |
+
x = generate_test_data(params)
|
| 45 |
+
x_fp8, per_channel_sf_inv = tile_kernels.quant.per_channel_cast(x, 'e4m3', num_per_tokens, round_sf)
|
| 46 |
+
x_fp8_ref, per_channel_sf_inv_ref = tile_kernels.torch.cast(x, 'e4m3', block_size=(num_per_tokens, 1), round_sf=round_sf)
|
| 47 |
+
|
| 48 |
+
assert_equal(x_fp8, x_fp8_ref)
|
| 49 |
+
assert_equal(per_channel_sf_inv, per_channel_sf_inv_ref)
|
| 50 |
+
|
| 51 |
+
# Check bias
|
| 52 |
+
x_casted_back = tile_kernels.torch.cast_back((x_fp8_ref, per_channel_sf_inv_ref), 'fp32', (num_per_tokens, 1))
|
| 53 |
+
check_bias(x_casted_back, x)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@pytest.mark.benchmark
|
| 57 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 58 |
+
def test_per_channel_cast_benchmark(benchmark_timer, benchmark_record, params):
|
| 59 |
+
num_per_tokens = params['num_per_tokens']
|
| 60 |
+
round_sf = params['round_sf']
|
| 61 |
+
dtype = params['dtype']
|
| 62 |
+
|
| 63 |
+
x = generate_test_data(params)
|
| 64 |
+
x_fp8, per_channel_sf_inv = tile_kernels.quant.per_channel_cast(x, 'e4m3', num_per_tokens, round_sf)
|
| 65 |
+
|
| 66 |
+
t_us = benchmark_timer(lambda: tile_kernels.quant.per_channel_cast(x, 'e4m3', num_per_tokens, round_sf))
|
| 67 |
+
num_bytes = count_bytes(x, x_fp8, per_channel_sf_inv)
|
| 68 |
+
|
| 69 |
+
benchmark_record(
|
| 70 |
+
kernel='per_channel_cast',
|
| 71 |
+
operation='fwd',
|
| 72 |
+
params={**params, 'dtype': dtype_to_str(dtype)},
|
| 73 |
+
time_us=t_us,
|
| 74 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 75 |
+
)
|
tile_kernels_src/tests/quant/test_per_channel_cast_and_transpose.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
import tile_kernels
|
| 6 |
+
from tile_kernels.testing.bench import dtype_to_str, make_param_id
|
| 7 |
+
from tile_kernels.testing.generator import generate_hidden_sizes, generate_num_tokens
|
| 8 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 9 |
+
|
| 10 |
+
# Disable TileLang prints
|
| 11 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def generate_test_data(params):
|
| 15 |
+
num_tokens = params['num_tokens']
|
| 16 |
+
hidden = params['hidden']
|
| 17 |
+
dtype = params['dtype']
|
| 18 |
+
|
| 19 |
+
x = torch.randn((num_tokens, hidden), dtype=dtype, device='cuda')
|
| 20 |
+
|
| 21 |
+
return x
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 25 |
+
return [
|
| 26 |
+
{
|
| 27 |
+
'num_tokens': num_tokens,
|
| 28 |
+
'hidden': hidden_size,
|
| 29 |
+
'round_sf': round_sf,
|
| 30 |
+
'dtype': dtype,
|
| 31 |
+
'num_per_channels': num_per_channels,
|
| 32 |
+
}
|
| 33 |
+
for num_tokens in generate_num_tokens(128, is_benchmark=is_benchmark)
|
| 34 |
+
for hidden_size in generate_hidden_sizes()
|
| 35 |
+
for round_sf in (True, False)
|
| 36 |
+
for dtype in (torch.bfloat16,)
|
| 37 |
+
for num_per_channels in (32, 128)
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 42 |
+
def test_per_channel_cast_and_transpose(params):
|
| 43 |
+
round_sf = params['round_sf']
|
| 44 |
+
num_per_channels = params['num_per_channels']
|
| 45 |
+
|
| 46 |
+
x = generate_test_data(params)
|
| 47 |
+
|
| 48 |
+
x_fp8, x_sf = tile_kernels.quant.per_channel_cast_and_transpose(x, 'e4m3', num_per_channels, round_sf)
|
| 49 |
+
x_fp8_ref, x_sf_ref = tile_kernels.torch.cast(x, 'e4m3', block_size=(num_per_channels, 1), round_sf=round_sf)
|
| 50 |
+
x_fp8_ref = x_fp8_ref.T.contiguous()
|
| 51 |
+
assert_equal(x_fp8, x_fp8_ref)
|
| 52 |
+
assert_equal(x_sf, x_sf_ref)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@pytest.mark.benchmark
|
| 56 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 57 |
+
def test_per_channel_cast_and_transpose_benchmark(benchmark_timer, benchmark_record, params):
|
| 58 |
+
round_sf = params['round_sf']
|
| 59 |
+
num_per_channels = params['num_per_channels']
|
| 60 |
+
|
| 61 |
+
x = generate_test_data(params)
|
| 62 |
+
|
| 63 |
+
x_fp8, x_sf = tile_kernels.quant.per_channel_cast_and_transpose(x, 'e4m3', num_per_channels, round_sf)
|
| 64 |
+
num_bytes = count_bytes(x, x_fp8, x_sf)
|
| 65 |
+
|
| 66 |
+
t_us = benchmark_timer(
|
| 67 |
+
lambda: tile_kernels.quant.per_channel_cast_and_transpose(x, 'e4m3', num_per_channels, round_sf)
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
params['dtype'] = dtype_to_str(x.dtype)
|
| 71 |
+
benchmark_record(
|
| 72 |
+
kernel='per_channel_cast_and_transpose',
|
| 73 |
+
operation='fwd',
|
| 74 |
+
params=params,
|
| 75 |
+
time_us=t_us,
|
| 76 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 77 |
+
)
|
tile_kernels_src/tests/quant/test_per_channel_cast_fused.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import os
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
import tile_kernels
|
| 7 |
+
from tile_kernels.testing.generator import generate_topk_idx, generate_hidden_sizes, generate_moe_params
|
| 8 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 9 |
+
from tile_kernels.testing.bench import make_param_id
|
| 10 |
+
from tile_kernels.torch.per_channel_cast_fused import per_channel_cast_fused as torch_ref_per_channel_cast_fused
|
| 11 |
+
|
| 12 |
+
# Disable TileLang prints
|
| 13 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def generate_test_data(params):
|
| 17 |
+
num_send_tokens = params['num_send_tokens']
|
| 18 |
+
num_topk = params['num_topk']
|
| 19 |
+
num_experts = params['num_experts']
|
| 20 |
+
hidden = params['hidden']
|
| 21 |
+
num_per_tokens = params['num_per_tokens']
|
| 22 |
+
num_per_channels = params['num_per_channels']
|
| 23 |
+
is_fused_cast_back = params['is_fused_cast_back']
|
| 24 |
+
round_sf = params['round_sf']
|
| 25 |
+
|
| 26 |
+
pos_to_token = None
|
| 27 |
+
if num_topk > 0:
|
| 28 |
+
topk_idx = generate_topk_idx(params)
|
| 29 |
+
num_tokens = topk_idx.shape[0]
|
| 30 |
+
_, pos_to_token, _, token_topk_to_pos, _, _, _, _ = (
|
| 31 |
+
tile_kernels.moe.get_fused_mapping(topk_idx, num_experts, 0, 128)
|
| 32 |
+
)
|
| 33 |
+
x = torch.randn((num_tokens, hidden), dtype=torch.bfloat16, device='cuda')
|
| 34 |
+
x = tile_kernels.moe.expand_to_fused(x, token_topk_to_pos, pos_to_token)
|
| 35 |
+
else:
|
| 36 |
+
num_tokens = num_send_tokens
|
| 37 |
+
x = torch.randn((num_tokens, hidden), dtype=torch.bfloat16, device='cuda')
|
| 38 |
+
|
| 39 |
+
if is_fused_cast_back:
|
| 40 |
+
x = tile_kernels.quant.per_token_cast(x, 'e4m3', num_per_channels)
|
| 41 |
+
|
| 42 |
+
func = lambda: tile_kernels.quant.per_channel_cast_fused(
|
| 43 |
+
x, 'e4m3', num_per_tokens=num_per_tokens, round_sf=round_sf,
|
| 44 |
+
num_per_channels=num_per_channels if is_fused_cast_back else None,
|
| 45 |
+
pos_to_token=pos_to_token,
|
| 46 |
+
)
|
| 47 |
+
func_ref = lambda: torch_ref_per_channel_cast_fused(x, num_per_tokens, num_per_channels, round_sf, pos_to_token)
|
| 48 |
+
|
| 49 |
+
return (x, num_tokens, pos_to_token, func, func_ref)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 53 |
+
params = [
|
| 54 |
+
{
|
| 55 |
+
**moe,
|
| 56 |
+
'hidden': hidden_size,
|
| 57 |
+
'num_per_tokens': num_per_tokens,
|
| 58 |
+
'num_per_channels': num_per_channels,
|
| 59 |
+
'is_fused_cast_back': is_fused_cast_back,
|
| 60 |
+
'round_sf': round_sf,
|
| 61 |
+
}
|
| 62 |
+
for moe in itertools.chain(
|
| 63 |
+
iter([{'num_send_tokens': 4096, 'num_topk': 0, 'num_experts': 0, 'num_ep_ranks': 0}]),
|
| 64 |
+
generate_moe_params(),
|
| 65 |
+
)
|
| 66 |
+
for hidden_size in generate_hidden_sizes(128)
|
| 67 |
+
for num_per_tokens, num_per_channels in [(128, 128)]
|
| 68 |
+
for is_fused_cast_back in (False, True)
|
| 69 |
+
for round_sf in (False, True)
|
| 70 |
+
]
|
| 71 |
+
if is_benchmark:
|
| 72 |
+
params = [p for p in params if p['num_topk'] in (0, 6)]
|
| 73 |
+
return params
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 77 |
+
def test_per_channel_cast_fused(params):
|
| 78 |
+
_, _, _, func, func_ref = generate_test_data(params)
|
| 79 |
+
|
| 80 |
+
x_fp8, x_fp8_sf = func()
|
| 81 |
+
x_fp8_ref, x_fp8_sf_ref = func_ref()
|
| 82 |
+
|
| 83 |
+
assert_equal(x_fp8, x_fp8_ref)
|
| 84 |
+
assert_equal(x_fp8_sf, x_fp8_sf_ref)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@pytest.mark.benchmark
|
| 88 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 89 |
+
def test_per_channel_cast_fused_benchmark(benchmark_timer, benchmark_record, params):
|
| 90 |
+
x, num_tokens, pos_to_token, func, func_ref = generate_test_data(params)
|
| 91 |
+
|
| 92 |
+
x_fp8, x_fp8_sf = func()
|
| 93 |
+
|
| 94 |
+
t_us = benchmark_timer(func)
|
| 95 |
+
num_bytes = count_bytes(x, pos_to_token, x_fp8, x_fp8_sf)
|
| 96 |
+
|
| 97 |
+
params.pop('num_send_tokens')
|
| 98 |
+
benchmark_record(
|
| 99 |
+
kernel='per_channel_cast_fused',
|
| 100 |
+
operation='fwd',
|
| 101 |
+
params={'num_tokens': num_tokens, **params},
|
| 102 |
+
time_us=t_us,
|
| 103 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 104 |
+
)
|
tile_kernels_src/tests/quant/test_per_token_cast.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
import tile_kernels
|
| 6 |
+
from tile_kernels.testing.bench import dtype_to_str, make_param_id
|
| 7 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes, check_bias
|
| 8 |
+
from tile_kernels.testing.generator import generate_hidden_sizes, generate_num_tokens
|
| 9 |
+
from tile_kernels.testing.quant import clear_unused_sf
|
| 10 |
+
|
| 11 |
+
# Disable TileLang prints
|
| 12 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def generate_test_data(params):
|
| 16 |
+
num_tokens = params['num_tokens']
|
| 17 |
+
hidden = params['hidden']
|
| 18 |
+
in_dtype = params['in_dtype']
|
| 19 |
+
fmt = params['fmt']
|
| 20 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 21 |
+
round_sf = params['round_sf']
|
| 22 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 23 |
+
x_block_size = params.get('x_block_size')
|
| 24 |
+
|
| 25 |
+
in_with_sf_factor = in_dtype in (torch.float8_e4m3fn, torch.int8)
|
| 26 |
+
|
| 27 |
+
if in_with_sf_factor:
|
| 28 |
+
x = torch.randn((num_tokens, hidden), dtype=torch.bfloat16, device='cuda')
|
| 29 |
+
original_x = x
|
| 30 |
+
in_fmt = 'e4m3' if in_dtype == torch.float8_e4m3fn else 'e2m1'
|
| 31 |
+
x = tile_kernels.torch.cast(
|
| 32 |
+
x, in_fmt, x_block_size,
|
| 33 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf,
|
| 34 |
+
round_sf=round_sf,
|
| 35 |
+
use_packed_ue8m0=use_packed_ue8m0,
|
| 36 |
+
)
|
| 37 |
+
else:
|
| 38 |
+
x = torch.randn((num_tokens, hidden), dtype=in_dtype, device='cuda')
|
| 39 |
+
original_x = x
|
| 40 |
+
|
| 41 |
+
base_args = dict(
|
| 42 |
+
x=x, fmt=fmt, x_block_size=x_block_size,
|
| 43 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf,
|
| 44 |
+
round_sf=round_sf,
|
| 45 |
+
use_packed_ue8m0=use_packed_ue8m0,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
return (x, original_x, base_args, in_with_sf_factor)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 52 |
+
params = [
|
| 53 |
+
{
|
| 54 |
+
'num_tokens': num_tokens,
|
| 55 |
+
'hidden': hidden_size,
|
| 56 |
+
'use_tma_aligned_col_major_sf': use_tma_aligned_col_major_sf,
|
| 57 |
+
'round_sf': round_sf,
|
| 58 |
+
'use_packed_ue8m0': use_packed_ue8m0,
|
| 59 |
+
'in_dtype': in_dtype,
|
| 60 |
+
'num_per_channels': num_per_channels,
|
| 61 |
+
'x_block_size': x_block_size,
|
| 62 |
+
'fmt': fmt,
|
| 63 |
+
}
|
| 64 |
+
for num_tokens in generate_num_tokens(is_benchmark=is_benchmark)
|
| 65 |
+
for hidden_size in generate_hidden_sizes()
|
| 66 |
+
for use_tma_aligned_col_major_sf, round_sf, use_packed_ue8m0 in [(False, True, False), (True, True, True)]
|
| 67 |
+
for in_dtype in (torch.float32, torch.bfloat16, torch.float8_e4m3fn, torch.int8)
|
| 68 |
+
for num_per_channels in ((32, 128) if in_dtype in (torch.float8_e4m3fn, torch.int8) else (32, 64, 128, hidden_size))
|
| 69 |
+
for x_block_size in (((128, 128), (32, 32)) if in_dtype in (torch.float8_e4m3fn, torch.int8) else (None,))
|
| 70 |
+
for fmt in ('e4m3', 'e2m1')
|
| 71 |
+
]
|
| 72 |
+
if is_benchmark:
|
| 73 |
+
params = [p for p in params if p['use_packed_ue8m0']]
|
| 74 |
+
return params
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 78 |
+
def test_per_token_cast(params):
|
| 79 |
+
num_tokens = params['num_tokens']
|
| 80 |
+
hidden = params['hidden']
|
| 81 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 82 |
+
round_sf = params['round_sf']
|
| 83 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 84 |
+
in_dtype = params['in_dtype']
|
| 85 |
+
num_per_channels = params['num_per_channels']
|
| 86 |
+
x_block_size = params.get('x_block_size')
|
| 87 |
+
fmt = params['fmt']
|
| 88 |
+
|
| 89 |
+
in_with_sf_factor = in_dtype in (torch.float8_e4m3fn, torch.int8)
|
| 90 |
+
# Test correctness
|
| 91 |
+
x, original_x, base_args, in_with_sf_factor = generate_test_data(params)
|
| 92 |
+
func = lambda: tile_kernels.quant.per_token_cast(
|
| 93 |
+
**base_args,
|
| 94 |
+
num_per_channels=num_per_channels,
|
| 95 |
+
)
|
| 96 |
+
func_ref = lambda: tile_kernels.torch.cast(
|
| 97 |
+
**base_args,
|
| 98 |
+
block_size=(1, num_per_channels),
|
| 99 |
+
)
|
| 100 |
+
x_casted, x_sf = func()
|
| 101 |
+
x_casted_ref, x_sf_ref = func_ref()
|
| 102 |
+
x_casted_back = tile_kernels.torch.cast_back((x_casted, x_sf), 'fp32', (1, num_per_channels))
|
| 103 |
+
|
| 104 |
+
if use_packed_ue8m0:
|
| 105 |
+
x_sf = clear_unused_sf(x_sf, hidden, num_per_channels)
|
| 106 |
+
x_sf_ref = clear_unused_sf(x_sf_ref, hidden, num_per_channels)
|
| 107 |
+
|
| 108 |
+
assert_equal(x_casted, x_casted_ref)
|
| 109 |
+
assert_equal(x_sf, x_sf_ref)
|
| 110 |
+
|
| 111 |
+
# Check bias
|
| 112 |
+
check_bias(x_casted_back, original_x)
|
| 113 |
+
|
| 114 |
+
# Test non-contiguous input (stride(0) != hidden)
|
| 115 |
+
if not in_with_sf_factor and fmt == 'e4m3' and not use_packed_ue8m0 and num_tokens > 0:
|
| 116 |
+
x_non_contiguous = torch.randn((num_tokens, hidden * 2), dtype=in_dtype, device='cuda')[:, :hidden]
|
| 117 |
+
x_non_contiguous.copy_(original_x)
|
| 118 |
+
x_non_contiguous_casted, x_non_contiguous_sf = tile_kernels.quant.per_token_cast(
|
| 119 |
+
x=x_non_contiguous, fmt=fmt, x_block_size=x_block_size,
|
| 120 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf,
|
| 121 |
+
round_sf=round_sf, use_packed_ue8m0=use_packed_ue8m0,
|
| 122 |
+
num_per_channels=num_per_channels,
|
| 123 |
+
)
|
| 124 |
+
assert_equal(x_non_contiguous_casted, x_casted)
|
| 125 |
+
assert_equal(x_non_contiguous_sf, x_sf)
|
| 126 |
+
|
| 127 |
+
if not in_with_sf_factor and num_per_channels != hidden:
|
| 128 |
+
# Test cast only mode
|
| 129 |
+
if not use_tma_aligned_col_major_sf:
|
| 130 |
+
# TMA aligned or packed ue8m0 sf is used for FP8/FP4 GEMM, not for other cast
|
| 131 |
+
x_casted = tile_kernels.quant.per_token_cast_with_precomputed_sf(
|
| 132 |
+
**base_args, num_per_channels=num_per_channels, sf=x_sf
|
| 133 |
+
)
|
| 134 |
+
x_casted_ref = tile_kernels.torch.cast(**base_args, block_size=(1, num_per_channels), sf=x_sf)
|
| 135 |
+
assert_equal(x_casted, x_casted_ref)
|
| 136 |
+
|
| 137 |
+
# Test sf only mode
|
| 138 |
+
twice_sf_inv = tile_kernels.quant.per_token_cast_with_sf_only(**base_args, num_per_channels=num_per_channels)
|
| 139 |
+
if use_packed_ue8m0:
|
| 140 |
+
twice_sf_inv = clear_unused_sf(twice_sf_inv, hidden, num_per_channels)
|
| 141 |
+
assert_equal(twice_sf_inv, x_sf)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@pytest.mark.benchmark
|
| 145 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 146 |
+
def test_per_token_cast_benchmark(benchmark_timer, benchmark_record, params):
|
| 147 |
+
in_dtype = params['in_dtype']
|
| 148 |
+
num_per_channels = params['num_per_channels']
|
| 149 |
+
|
| 150 |
+
x, _, base_args, _ = generate_test_data(params)
|
| 151 |
+
func = lambda: tile_kernels.quant.per_token_cast(
|
| 152 |
+
**base_args,
|
| 153 |
+
num_per_channels=num_per_channels,
|
| 154 |
+
)
|
| 155 |
+
x_casted, x_sf = func()
|
| 156 |
+
|
| 157 |
+
t_us = benchmark_timer(func)
|
| 158 |
+
num_bytes = count_bytes(x, x_casted, x_sf)
|
| 159 |
+
|
| 160 |
+
benchmark_record(
|
| 161 |
+
kernel='per_token_cast',
|
| 162 |
+
operation='fwd',
|
| 163 |
+
params={**params, 'in_dtype': dtype_to_str(in_dtype)},
|
| 164 |
+
time_us=t_us,
|
| 165 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 166 |
+
)
|
tile_kernels_src/tests/quant/test_per_token_cast_to_e5m6.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
import tile_kernels
|
| 6 |
+
from tile_kernels.testing import clear_unused_sf
|
| 7 |
+
from tile_kernels.testing.bench import dtype_to_str, make_param_id
|
| 8 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 9 |
+
from tile_kernels.testing.generator import generate_hidden_sizes, generate_num_tokens, generate_e5m6_inputs
|
| 10 |
+
from tile_kernels.torch import cast_to_e5m6
|
| 11 |
+
|
| 12 |
+
# Disable TileLang prints
|
| 13 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def generate_test_data(params):
|
| 17 |
+
x = params['x']
|
| 18 |
+
num_per_channels = params['num_per_channels']
|
| 19 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 20 |
+
round_sf = params['round_sf']
|
| 21 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 22 |
+
|
| 23 |
+
func = lambda: tile_kernels.quant.per_token_cast(
|
| 24 |
+
x, 'e5m6', num_per_channels=num_per_channels,
|
| 25 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf,
|
| 26 |
+
round_sf=round_sf,
|
| 27 |
+
use_packed_ue8m0=use_packed_ue8m0,
|
| 28 |
+
)
|
| 29 |
+
torch_func_ref = lambda: cast_to_e5m6(
|
| 30 |
+
x, num_per_channels=num_per_channels,
|
| 31 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf,
|
| 32 |
+
round_sf=round_sf,
|
| 33 |
+
use_packed_ue8m0=use_packed_ue8m0,
|
| 34 |
+
)
|
| 35 |
+
return (func, torch_func_ref)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 39 |
+
return [
|
| 40 |
+
{
|
| 41 |
+
'num_tokens': num_tokens,
|
| 42 |
+
'hidden': hidden_size,
|
| 43 |
+
'use_tma_aligned_col_major_sf': use_tma_aligned_col_major_sf,
|
| 44 |
+
'round_sf': round_sf,
|
| 45 |
+
'use_packed_ue8m0': use_packed_ue8m0,
|
| 46 |
+
'in_dtype': in_dtype,
|
| 47 |
+
}
|
| 48 |
+
for num_tokens in generate_num_tokens(is_benchmark=is_benchmark)
|
| 49 |
+
for hidden_size in generate_hidden_sizes()
|
| 50 |
+
for use_tma_aligned_col_major_sf, round_sf, use_packed_ue8m0 in [(False, True, False), (True, True, True)]
|
| 51 |
+
for in_dtype in (torch.bfloat16, torch.float32)
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 56 |
+
def test_per_token_cast_to_e5m6(params):
|
| 57 |
+
num_tokens = params['num_tokens']
|
| 58 |
+
hidden = params['hidden']
|
| 59 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 60 |
+
round_sf = params['round_sf']
|
| 61 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 62 |
+
in_dtype = params['in_dtype']
|
| 63 |
+
|
| 64 |
+
num_per_channels = hidden
|
| 65 |
+
for x, is_special in generate_e5m6_inputs(num_tokens, hidden, in_dtype):
|
| 66 |
+
# Test correctness
|
| 67 |
+
func, torch_func_ref = generate_test_data({
|
| 68 |
+
'x': x,
|
| 69 |
+
'num_per_channels': num_per_channels,
|
| 70 |
+
'use_tma_aligned_col_major_sf': use_tma_aligned_col_major_sf,
|
| 71 |
+
'round_sf': round_sf,
|
| 72 |
+
'use_packed_ue8m0': use_packed_ue8m0,
|
| 73 |
+
})
|
| 74 |
+
|
| 75 |
+
x_fp8, x_sf = func()
|
| 76 |
+
x_fp8_ref, x_sf_ref = torch_func_ref()
|
| 77 |
+
|
| 78 |
+
if use_packed_ue8m0:
|
| 79 |
+
x_sf = clear_unused_sf(x_sf, hidden, num_per_channels)
|
| 80 |
+
x_sf_ref = clear_unused_sf(x_sf_ref, hidden, num_per_channels)
|
| 81 |
+
|
| 82 |
+
assert_equal(x_fp8, x_fp8_ref)
|
| 83 |
+
assert_equal(x_sf, x_sf_ref)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@pytest.mark.benchmark
|
| 87 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 88 |
+
def test_per_token_cast_to_e5m6_benchmark(benchmark_timer, benchmark_record, params):
|
| 89 |
+
hidden = params['hidden']
|
| 90 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 91 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 92 |
+
in_dtype = params['in_dtype']
|
| 93 |
+
|
| 94 |
+
num_per_channels = hidden
|
| 95 |
+
for x, is_special in generate_e5m6_inputs(params['num_tokens'], hidden, in_dtype):
|
| 96 |
+
if is_special:
|
| 97 |
+
continue
|
| 98 |
+
|
| 99 |
+
func, torch_func_ref = generate_test_data({
|
| 100 |
+
'x': x,
|
| 101 |
+
'num_per_channels': num_per_channels,
|
| 102 |
+
'use_tma_aligned_col_major_sf': use_tma_aligned_col_major_sf,
|
| 103 |
+
'round_sf': params['round_sf'],
|
| 104 |
+
'use_packed_ue8m0': use_packed_ue8m0,
|
| 105 |
+
})
|
| 106 |
+
|
| 107 |
+
x_fp8, x_sf = func()
|
| 108 |
+
|
| 109 |
+
t_us = benchmark_timer(func)
|
| 110 |
+
num_bytes = count_bytes(x, x_fp8, x_sf)
|
| 111 |
+
|
| 112 |
+
benchmark_record(
|
| 113 |
+
kernel='per_token_cast_to_e5m6',
|
| 114 |
+
operation='fwd',
|
| 115 |
+
params={**params, 'num_per_channels': num_per_channels, 'in_dtype': dtype_to_str(in_dtype)},
|
| 116 |
+
time_us=t_us,
|
| 117 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 118 |
+
)
|
tile_kernels_src/tests/quant/test_swiglu_backward_and_per_token_cast.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
import tile_kernels
|
| 6 |
+
from tile_kernels.testing.generator import generate_topk_idx, generate_hidden_sizes, generate_moe_params
|
| 7 |
+
from tile_kernels.testing.numeric import assert_equal, calc_diff, count_bytes
|
| 8 |
+
from tile_kernels.testing.bench import make_param_id
|
| 9 |
+
|
| 10 |
+
# Disable TileLang prints
|
| 11 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def generate_test_data(params):
|
| 15 |
+
num_topk = params['num_topk']
|
| 16 |
+
num_experts = params['num_experts']
|
| 17 |
+
hidden = params['hidden']
|
| 18 |
+
num_per_channels = params['num_per_channels']
|
| 19 |
+
|
| 20 |
+
topk_idx = generate_topk_idx(params)
|
| 21 |
+
num_tokens = topk_idx.shape[0]
|
| 22 |
+
topk_weights = torch.rand((num_tokens, num_topk), dtype=torch.float32, device='cuda')
|
| 23 |
+
x = torch.randn((num_tokens, hidden * 2), dtype=torch.bfloat16, device='cuda')
|
| 24 |
+
_, pos_to_token, pos_to_token_topk, token_topk_to_pos, _, _, _, _ = tile_kernels.moe.get_fused_mapping(
|
| 25 |
+
topk_idx, num_experts, 0, num_per_channels
|
| 26 |
+
)
|
| 27 |
+
x_expand = tile_kernels.moe.expand_to_fused(x, token_topk_to_pos, pos_to_token)
|
| 28 |
+
x = tile_kernels.quant.per_token_cast(x_expand, 'e4m3', num_per_channels=num_per_channels)
|
| 29 |
+
num_expand_tokens = x_expand.size(0)
|
| 30 |
+
weighted_act_x_grad = torch.randn((num_expand_tokens, hidden), dtype=torch.bfloat16, device='cuda')
|
| 31 |
+
|
| 32 |
+
return (x, num_tokens, topk_weights, pos_to_token_topk, token_topk_to_pos, weighted_act_x_grad)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 36 |
+
params = [
|
| 37 |
+
{
|
| 38 |
+
'num_send_tokens': moe['num_send_tokens'],
|
| 39 |
+
'num_topk': moe['num_topk'],
|
| 40 |
+
'num_experts': moe['num_experts'],
|
| 41 |
+
'num_ep_ranks': moe['num_ep_ranks'],
|
| 42 |
+
'hidden': hidden_size,
|
| 43 |
+
'num_per_channels': num_per_channels,
|
| 44 |
+
'round_sf': round_sf,
|
| 45 |
+
'swiglu_clamp_value': swiglu_clamp_value,
|
| 46 |
+
}
|
| 47 |
+
for moe in generate_moe_params(is_benchmark)
|
| 48 |
+
for hidden_size in generate_hidden_sizes(256)
|
| 49 |
+
for num_per_channels in (32, 128)
|
| 50 |
+
for round_sf in (False, True)
|
| 51 |
+
for swiglu_clamp_value in (None, 10.0, 0.5)
|
| 52 |
+
]
|
| 53 |
+
if is_benchmark:
|
| 54 |
+
params = [p for p in params if p['swiglu_clamp_value'] in (None, 0.5) and p['round_sf']]
|
| 55 |
+
return params
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 59 |
+
def test_swiglu_backward_and_per_token_cast(params):
|
| 60 |
+
num_per_channels = params['num_per_channels']
|
| 61 |
+
round_sf = params['round_sf']
|
| 62 |
+
swiglu_clamp_value = params['swiglu_clamp_value']
|
| 63 |
+
|
| 64 |
+
x, num_tokens, topk_weights, pos_to_token_topk, token_topk_to_pos, weighted_act_x_grad = generate_test_data(params)
|
| 65 |
+
|
| 66 |
+
func = lambda: tile_kernels.quant.swiglu_backward_and_per_token_cast(
|
| 67 |
+
x,
|
| 68 |
+
weighted_act_x_grad,
|
| 69 |
+
topk_weights,
|
| 70 |
+
pos_to_token_topk,
|
| 71 |
+
token_topk_to_pos,
|
| 72 |
+
num_per_channels=num_per_channels,
|
| 73 |
+
round_sf=round_sf,
|
| 74 |
+
swiglu_clamp_value=swiglu_clamp_value,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
def func_ref():
|
| 78 |
+
out, x_grad_full, weight_grad = tile_kernels.torch.swiglu_backward(
|
| 79 |
+
x,
|
| 80 |
+
weighted_act_x_grad,
|
| 81 |
+
topk_weights,
|
| 82 |
+
pos_to_token_topk,
|
| 83 |
+
token_topk_to_pos,
|
| 84 |
+
num_per_channels=num_per_channels,
|
| 85 |
+
swiglu_clamp_value=swiglu_clamp_value,
|
| 86 |
+
)
|
| 87 |
+
x_grad_fp8_full, x_grad_fp8_sf = tile_kernels.torch.cast(
|
| 88 |
+
x_grad_full, 'e4m3', block_size=(1, num_per_channels), round_sf=round_sf
|
| 89 |
+
)
|
| 90 |
+
return (
|
| 91 |
+
out.to(weighted_act_x_grad.dtype),
|
| 92 |
+
(x_grad_fp8_full, x_grad_fp8_sf),
|
| 93 |
+
x_grad_full.to(weighted_act_x_grad.dtype),
|
| 94 |
+
weight_grad,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
weighted_act_x, x_grad_fp8, x_grad, topk_weights_grad = func()
|
| 98 |
+
weighted_act_x_ref, x_grad_fp8_ref, x_grad_ref, topk_weights_grad_ref = func_ref()
|
| 99 |
+
|
| 100 |
+
assert_equal(weighted_act_x, weighted_act_x_ref)
|
| 101 |
+
assert_equal(x_grad, x_grad_ref)
|
| 102 |
+
assert_equal(x_grad_fp8[0], x_grad_fp8_ref[0])
|
| 103 |
+
assert_equal(x_grad_fp8[1], x_grad_fp8_ref[1])
|
| 104 |
+
torch.testing.assert_close(topk_weights_grad, topk_weights_grad_ref, atol=1e-4, rtol=1e-4)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@pytest.mark.benchmark
|
| 108 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 109 |
+
def test_swiglu_backward_and_per_token_cast_benchmark(benchmark_timer, benchmark_record, params):
|
| 110 |
+
num_per_channels = params['num_per_channels']
|
| 111 |
+
round_sf = params['round_sf']
|
| 112 |
+
swiglu_clamp_value = params['swiglu_clamp_value']
|
| 113 |
+
|
| 114 |
+
x, num_tokens, topk_weights, pos_to_token_topk, token_topk_to_pos, weighted_act_x_grad = generate_test_data(params)
|
| 115 |
+
|
| 116 |
+
func = lambda: tile_kernels.quant.swiglu_backward_and_per_token_cast(
|
| 117 |
+
x,
|
| 118 |
+
weighted_act_x_grad,
|
| 119 |
+
topk_weights,
|
| 120 |
+
pos_to_token_topk,
|
| 121 |
+
token_topk_to_pos,
|
| 122 |
+
num_per_channels=num_per_channels,
|
| 123 |
+
round_sf=round_sf,
|
| 124 |
+
swiglu_clamp_value=swiglu_clamp_value,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
weighted_act_x, x_grad_fp8, x_grad, topk_weights_grad = func()
|
| 128 |
+
|
| 129 |
+
t_us = benchmark_timer(func)
|
| 130 |
+
num_bytes = count_bytes(
|
| 131 |
+
x,
|
| 132 |
+
weighted_act_x_grad,
|
| 133 |
+
topk_weights,
|
| 134 |
+
pos_to_token_topk,
|
| 135 |
+
token_topk_to_pos,
|
| 136 |
+
weighted_act_x,
|
| 137 |
+
x_grad_fp8,
|
| 138 |
+
x_grad,
|
| 139 |
+
topk_weights_grad,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
params.pop('num_send_tokens')
|
| 143 |
+
benchmark_record(
|
| 144 |
+
kernel='swiglu_backward_and_per_token_cast',
|
| 145 |
+
operation='fwd',
|
| 146 |
+
params={'num_tokens': num_tokens, **params},
|
| 147 |
+
time_us=t_us,
|
| 148 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 149 |
+
)
|
tile_kernels_src/tests/quant/test_swiglu_forward_and_per_channel_cast_and_transpose.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
import tile_kernels
|
| 6 |
+
from tile_kernels.testing.generator import generate_hidden_sizes, generate_num_tokens
|
| 7 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 8 |
+
from tile_kernels.testing.bench import make_param_id
|
| 9 |
+
|
| 10 |
+
# Disable TileLang prints
|
| 11 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def generate_test_data(params):
|
| 15 |
+
num_tokens = params['num_tokens']
|
| 16 |
+
hidden = params['hidden']
|
| 17 |
+
dtype = torch.bfloat16
|
| 18 |
+
x = torch.randn((num_tokens, hidden * 2), dtype=dtype, device='cuda')
|
| 19 |
+
return x
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 23 |
+
params = [
|
| 24 |
+
{
|
| 25 |
+
'num_tokens': num_tokens,
|
| 26 |
+
'hidden': hidden_size,
|
| 27 |
+
'num_per_tokens': num_per_tokens,
|
| 28 |
+
'without_transpose': without_transpose,
|
| 29 |
+
'round_sf': round_sf,
|
| 30 |
+
'swiglu_clamp_value': swiglu_clamp_value,
|
| 31 |
+
}
|
| 32 |
+
for num_tokens in generate_num_tokens(128, is_benchmark=is_benchmark)
|
| 33 |
+
for hidden_size in generate_hidden_sizes()
|
| 34 |
+
for num_per_tokens in (32, 128)
|
| 35 |
+
for without_transpose in (True, False)
|
| 36 |
+
for round_sf in (True, False)
|
| 37 |
+
for swiglu_clamp_value in (None, 10.0, 0.5)
|
| 38 |
+
]
|
| 39 |
+
if is_benchmark:
|
| 40 |
+
params = [p for p in params if p['swiglu_clamp_value'] in (None, 0.5)]
|
| 41 |
+
return params
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 45 |
+
def test_swiglu_forward_and_per_channel_cast_and_transpose(params):
|
| 46 |
+
num_per_tokens = params['num_per_tokens']
|
| 47 |
+
without_transpose = params['without_transpose']
|
| 48 |
+
round_sf = params['round_sf']
|
| 49 |
+
swiglu_clamp_value = params['swiglu_clamp_value']
|
| 50 |
+
|
| 51 |
+
x = generate_test_data(params)
|
| 52 |
+
|
| 53 |
+
func = lambda: tile_kernels.quant.swiglu_forward_and_per_channel_cast_and_transpose(
|
| 54 |
+
x,
|
| 55 |
+
'e4m3',
|
| 56 |
+
num_per_tokens=num_per_tokens,
|
| 57 |
+
round_sf=round_sf,
|
| 58 |
+
without_transpose=without_transpose,
|
| 59 |
+
swiglu_clamp_value=swiglu_clamp_value,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def func_ref():
|
| 63 |
+
act_out = tile_kernels.torch.swiglu_forward(
|
| 64 |
+
x,
|
| 65 |
+
swiglu_clamp_value=swiglu_clamp_value,
|
| 66 |
+
).bfloat16()
|
| 67 |
+
x_fp8_ref, x_sf_ref = tile_kernels.torch.cast(
|
| 68 |
+
act_out,
|
| 69 |
+
'e4m3',
|
| 70 |
+
block_size=(num_per_tokens, 1),
|
| 71 |
+
round_sf=round_sf,
|
| 72 |
+
)
|
| 73 |
+
if not without_transpose:
|
| 74 |
+
x_fp8_ref = x_fp8_ref.T.contiguous()
|
| 75 |
+
return x_fp8_ref, x_sf_ref
|
| 76 |
+
|
| 77 |
+
x_fp8, x_sf = func()
|
| 78 |
+
x_fp8_ref, x_sf_ref = func_ref()
|
| 79 |
+
|
| 80 |
+
assert_equal(x_sf, x_sf_ref)
|
| 81 |
+
assert_equal(x_fp8, x_fp8_ref)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@pytest.mark.benchmark
|
| 85 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 86 |
+
def test_swiglu_forward_and_per_channel_cast_and_transpose_benchmark(benchmark_timer, benchmark_record, params):
|
| 87 |
+
num_per_tokens = params['num_per_tokens']
|
| 88 |
+
without_transpose = params['without_transpose']
|
| 89 |
+
round_sf = params['round_sf']
|
| 90 |
+
swiglu_clamp_value = params['swiglu_clamp_value']
|
| 91 |
+
|
| 92 |
+
x = generate_test_data(params)
|
| 93 |
+
|
| 94 |
+
func = lambda: tile_kernels.quant.swiglu_forward_and_per_channel_cast_and_transpose(
|
| 95 |
+
x,
|
| 96 |
+
'e4m3',
|
| 97 |
+
num_per_tokens=num_per_tokens,
|
| 98 |
+
round_sf=round_sf,
|
| 99 |
+
without_transpose=without_transpose,
|
| 100 |
+
swiglu_clamp_value=swiglu_clamp_value,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
x_fp8, x_sf = func()
|
| 104 |
+
num_bytes = count_bytes(x, x_fp8, x_sf)
|
| 105 |
+
|
| 106 |
+
t_us = benchmark_timer(func)
|
| 107 |
+
|
| 108 |
+
benchmark_record(
|
| 109 |
+
kernel='swiglu_forward_and_per_channel_cast_and_transpose',
|
| 110 |
+
operation='fwd',
|
| 111 |
+
params=params,
|
| 112 |
+
time_us=t_us,
|
| 113 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 114 |
+
)
|
tile_kernels_src/tests/quant/test_swiglu_forward_and_per_token_cast.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pytest
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
import tile_kernels
|
| 6 |
+
from tile_kernels.testing import clear_unused_sf
|
| 7 |
+
from tile_kernels.torch import swiglu_forward, cast
|
| 8 |
+
from tile_kernels.config import set_num_sms
|
| 9 |
+
from tile_kernels.testing.generator import generate_topk_idx, generate_hidden_sizes, generate_moe_params, generate_num_sms
|
| 10 |
+
from tile_kernels.testing.numeric import assert_equal, count_bytes
|
| 11 |
+
from tile_kernels.testing.bench import make_param_id
|
| 12 |
+
|
| 13 |
+
# Disable TileLang prints
|
| 14 |
+
os.environ['TILELANG_PRINT_ON_COMPILATION'] = '0'
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def generate_test_data(params):
|
| 18 |
+
num_topk = params['num_topk']
|
| 19 |
+
num_experts = params['num_experts']
|
| 20 |
+
hidden = params['hidden']
|
| 21 |
+
|
| 22 |
+
topk_idx = generate_topk_idx(params)
|
| 23 |
+
num_tokens = topk_idx.shape[0]
|
| 24 |
+
alignment = 16
|
| 25 |
+
pos_to_expert, pos_to_token, pos_to_token_topk, token_topk_to_pos, _, _, _, _ = tile_kernels.moe.get_fused_mapping(topk_idx, num_experts, 0, alignment)
|
| 26 |
+
post_weights = torch.randn((num_tokens, num_topk), dtype=torch.float32, device='cuda')
|
| 27 |
+
x = torch.randn((num_tokens, hidden * 2), dtype=torch.bfloat16, device='cuda')
|
| 28 |
+
x = tile_kernels.moe.expand_to_fused(x, token_topk_to_pos, pos_to_token)
|
| 29 |
+
_clamped_count = torch.zeros(3, dtype=torch.int64, device='cuda')
|
| 30 |
+
|
| 31 |
+
return (x, num_tokens, pos_to_expert, pos_to_token_topk, post_weights, _clamped_count)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def generate_test_params(is_benchmark: bool) -> list[dict]:
|
| 35 |
+
params = [
|
| 36 |
+
{
|
| 37 |
+
**moe,
|
| 38 |
+
'hidden': hidden_size,
|
| 39 |
+
'enable_pos_to_expert': enable_pos_to_expert,
|
| 40 |
+
'with_weights': with_weights,
|
| 41 |
+
'num_per_channels': num_per_channels,
|
| 42 |
+
'use_tma_aligned_col_major_sf': use_tma_aligned_col_major_sf,
|
| 43 |
+
'round_sf': round_sf,
|
| 44 |
+
'use_packed_ue8m0': use_packed_ue8m0,
|
| 45 |
+
'swiglu_clamp_value': swiglu_clamp_value,
|
| 46 |
+
}
|
| 47 |
+
for moe in generate_moe_params(is_benchmark)
|
| 48 |
+
for hidden_size in [h // 2 for h in generate_hidden_sizes(256)]
|
| 49 |
+
for enable_pos_to_expert in (True, False)
|
| 50 |
+
for with_weights in (True, False)
|
| 51 |
+
for num_per_channels in (128, hidden_size)
|
| 52 |
+
for use_tma_aligned_col_major_sf, round_sf, use_packed_ue8m0 in [(False, True, False), (True, True, True)]
|
| 53 |
+
if not ((use_packed_ue8m0 and with_weights) or (use_tma_aligned_col_major_sf and num_per_channels == hidden_size))
|
| 54 |
+
for swiglu_clamp_value in (None, 10.0, 0.5)
|
| 55 |
+
]
|
| 56 |
+
if is_benchmark:
|
| 57 |
+
params = [p for p in params if p['swiglu_clamp_value'] in (0.5, None) and p['use_tma_aligned_col_major_sf'] and p['round_sf']]
|
| 58 |
+
return params
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=False), ids=make_param_id)
|
| 62 |
+
def test_swiglu_forward_and_per_token_cast(params):
|
| 63 |
+
hidden = params['hidden']
|
| 64 |
+
enable_pos_to_expert = params['enable_pos_to_expert']
|
| 65 |
+
with_weights = params['with_weights']
|
| 66 |
+
num_per_channels = params['num_per_channels']
|
| 67 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 68 |
+
round_sf = params['round_sf']
|
| 69 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 70 |
+
swiglu_clamp_value = params['swiglu_clamp_value']
|
| 71 |
+
|
| 72 |
+
x, num_tokens, pos_to_expert, pos_to_token_topk, post_weights, _clamped_count = generate_test_data(params)
|
| 73 |
+
|
| 74 |
+
do_clamp_count = num_per_channels != hidden and swiglu_clamp_value is not None
|
| 75 |
+
clamped_count_ref = _clamped_count.clone() if do_clamp_count else None
|
| 76 |
+
base_args = dict(
|
| 77 |
+
x=x,
|
| 78 |
+
fmt='e4m3',
|
| 79 |
+
pos_to_expert=pos_to_expert if enable_pos_to_expert else None,
|
| 80 |
+
swiglu_clamp_value=swiglu_clamp_value
|
| 81 |
+
)
|
| 82 |
+
kernel_args = dict(
|
| 83 |
+
**base_args,
|
| 84 |
+
num_per_channels=num_per_channels,
|
| 85 |
+
pos_to_token_topk=pos_to_token_topk if with_weights else None,
|
| 86 |
+
topk_weights=post_weights if with_weights else None,
|
| 87 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf, round_sf=round_sf,
|
| 88 |
+
use_packed_ue8m0=use_packed_ue8m0,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
def func_ref():
|
| 92 |
+
out = swiglu_forward(
|
| 93 |
+
x,
|
| 94 |
+
pos_to_token_topk if with_weights else None,
|
| 95 |
+
post_weights if with_weights else None,
|
| 96 |
+
swiglu_clamp_value,
|
| 97 |
+
clamped_count_ref,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if enable_pos_to_expert:
|
| 101 |
+
mask = pos_to_expert == -1
|
| 102 |
+
out = out.masked_fill(mask.unsqueeze(-1), 0)
|
| 103 |
+
|
| 104 |
+
result = cast(
|
| 105 |
+
out, 'e4m3', (1, num_per_channels),
|
| 106 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf,
|
| 107 |
+
round_sf=round_sf,
|
| 108 |
+
use_packed_ue8m0=use_packed_ue8m0,
|
| 109 |
+
)
|
| 110 |
+
return result
|
| 111 |
+
|
| 112 |
+
x_fp8_ref, x_sf_ref = func_ref()
|
| 113 |
+
mask = (pos_to_expert == -1).unsqueeze(-1)
|
| 114 |
+
x_fp8_ref_float = x_fp8_ref.float().masked_fill(mask, 0)
|
| 115 |
+
x_sf_ref = x_sf_ref.masked_fill(mask, 0)
|
| 116 |
+
if use_packed_ue8m0:
|
| 117 |
+
x_sf_ref = clear_unused_sf(x_sf_ref, hidden, num_per_channels)
|
| 118 |
+
|
| 119 |
+
for num_sms in generate_num_sms():
|
| 120 |
+
set_num_sms(num_sms)
|
| 121 |
+
clamped_count = _clamped_count.clone() if do_clamp_count else None
|
| 122 |
+
x_fp8, x_sf = tile_kernels.quant.swiglu_forward_and_per_token_cast(
|
| 123 |
+
**kernel_args, clamped_count=clamped_count
|
| 124 |
+
)
|
| 125 |
+
x_fp8_float = x_fp8.float().masked_fill(mask, 0)
|
| 126 |
+
x_sf = x_sf.masked_fill(mask, 0)
|
| 127 |
+
if use_packed_ue8m0:
|
| 128 |
+
x_sf = clear_unused_sf(x_sf, hidden, num_per_channels)
|
| 129 |
+
|
| 130 |
+
assert_equal(x_fp8_float, x_fp8_ref_float)
|
| 131 |
+
assert_equal(x_sf, x_sf_ref)
|
| 132 |
+
if do_clamp_count:
|
| 133 |
+
assert_equal(clamped_count, clamped_count_ref)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@pytest.mark.benchmark
|
| 137 |
+
@pytest.mark.parametrize('params', generate_test_params(is_benchmark=True), ids=make_param_id)
|
| 138 |
+
def test_swiglu_forward_and_per_token_cast_benchmark(benchmark_timer, benchmark_record, params):
|
| 139 |
+
hidden = params['hidden']
|
| 140 |
+
enable_pos_to_expert = params['enable_pos_to_expert']
|
| 141 |
+
with_weights = params['with_weights']
|
| 142 |
+
num_per_channels = params['num_per_channels']
|
| 143 |
+
use_tma_aligned_col_major_sf = params['use_tma_aligned_col_major_sf']
|
| 144 |
+
round_sf = params['round_sf']
|
| 145 |
+
use_packed_ue8m0 = params['use_packed_ue8m0']
|
| 146 |
+
swiglu_clamp_value = params['swiglu_clamp_value']
|
| 147 |
+
|
| 148 |
+
x, num_tokens, pos_to_expert, pos_to_token_topk, post_weights, _clamped_count = generate_test_data(params)
|
| 149 |
+
|
| 150 |
+
do_clamp_count = num_per_channels != hidden and swiglu_clamp_value is not None
|
| 151 |
+
clamped_count = _clamped_count.clone() if do_clamp_count else None
|
| 152 |
+
kernel_args = dict(
|
| 153 |
+
x=x,
|
| 154 |
+
fmt='e4m3',
|
| 155 |
+
pos_to_expert=pos_to_expert if enable_pos_to_expert else None,
|
| 156 |
+
swiglu_clamp_value=swiglu_clamp_value,
|
| 157 |
+
num_per_channels=num_per_channels,
|
| 158 |
+
pos_to_token_topk=pos_to_token_topk if with_weights else None,
|
| 159 |
+
topk_weights=post_weights if with_weights else None,
|
| 160 |
+
use_tma_aligned_col_major_sf=use_tma_aligned_col_major_sf, round_sf=round_sf,
|
| 161 |
+
use_packed_ue8m0=use_packed_ue8m0,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
func = lambda: tile_kernels.quant.swiglu_forward_and_per_token_cast(
|
| 165 |
+
**kernel_args, clamped_count=clamped_count
|
| 166 |
+
)
|
| 167 |
+
x_fp8, x_sf = func()
|
| 168 |
+
|
| 169 |
+
t_us = benchmark_timer(func)
|
| 170 |
+
num_bytes = count_bytes(x, x_fp8, x_sf)
|
| 171 |
+
|
| 172 |
+
params.pop('num_send_tokens')
|
| 173 |
+
benchmark_record(
|
| 174 |
+
kernel='swiglu_forward_and_per_token_cast',
|
| 175 |
+
operation='fwd',
|
| 176 |
+
params={'num_tokens': num_tokens, **params},
|
| 177 |
+
time_us=t_us,
|
| 178 |
+
bandwidth_gbs=num_bytes / t_us / 1e3,
|
| 179 |
+
)
|