trainkernel 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. trainkernel-0.1.0/LICENSE +201 -0
  2. trainkernel-0.1.0/NOTICE +6 -0
  3. trainkernel-0.1.0/PKG-INFO +169 -0
  4. trainkernel-0.1.0/README.md +136 -0
  5. trainkernel-0.1.0/pyproject.toml +45 -0
  6. trainkernel-0.1.0/setup.cfg +4 -0
  7. trainkernel-0.1.0/tests/test_benchmark_integrity.py +89 -0
  8. trainkernel-0.1.0/tests/test_codegen.py +72 -0
  9. trainkernel-0.1.0/tests/test_direct_commits.py +88 -0
  10. trainkernel-0.1.0/tests/test_epilogues_gpu.py +91 -0
  11. trainkernel-0.1.0/tests/test_frontend.py +34 -0
  12. trainkernel-0.1.0/tests/test_gemv.py +34 -0
  13. trainkernel-0.1.0/tests/test_gpu.py +95 -0
  14. trainkernel-0.1.0/tests/test_inplace_training.py +70 -0
  15. trainkernel-0.1.0/tests/test_ir_reference.py +83 -0
  16. trainkernel-0.1.0/tests/test_ir_validation.py +32 -0
  17. trainkernel-0.1.0/tests/test_optimizer_safety.py +71 -0
  18. trainkernel-0.1.0/tests/test_side_epilogues.py +70 -0
  19. trainkernel-0.1.0/tests/test_train_loop.py +62 -0
  20. trainkernel-0.1.0/tests/test_training_api.py +94 -0
  21. trainkernel-0.1.0/tests/test_transpose_pass.py +33 -0
  22. trainkernel-0.1.0/tests/test_wmma.py +85 -0
  23. trainkernel-0.1.0/trainkernel/__init__.py +23 -0
  24. trainkernel-0.1.0/trainkernel/codegen.py +870 -0
  25. trainkernel-0.1.0/trainkernel/frontend.py +320 -0
  26. trainkernel-0.1.0/trainkernel/gemv.py +56 -0
  27. trainkernel-0.1.0/trainkernel/ir.py +63 -0
  28. trainkernel-0.1.0/trainkernel/passes.py +66 -0
  29. trainkernel-0.1.0/trainkernel/py.typed +1 -0
  30. trainkernel-0.1.0/trainkernel/reference.py +53 -0
  31. trainkernel-0.1.0/trainkernel/runtime.py +142 -0
  32. trainkernel-0.1.0/trainkernel/wmma.py +130 -0
  33. trainkernel-0.1.0/trainkernel.egg-info/PKG-INFO +169 -0
  34. trainkernel-0.1.0/trainkernel.egg-info/SOURCES.txt +35 -0
  35. trainkernel-0.1.0/trainkernel.egg-info/dependency_links.txt +1 -0
  36. trainkernel-0.1.0/trainkernel.egg-info/requires.txt +7 -0
  37. trainkernel-0.1.0/trainkernel.egg-info/top_level.txt +1 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ TrainKernel
2
+
3
+ Copyright 2026 Arya Somu.
4
+
5
+ This distribution includes third-party dependencies that remain under their
6
+ respective licenses. See LICENSE for the project license.
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: trainkernel
3
+ Version: 0.1.0
4
+ Summary: Compile a complete static PyTorch training step into one CUDA kernel
5
+ Author: Arya Somu
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/arpjw/trainkernel
8
+ Project-URL: Documentation, https://github.com/arpjw/trainkernel#readme
9
+ Project-URL: Issues, https://github.com/arpjw/trainkernel/issues
10
+ Project-URL: Source, https://github.com/arpjw/trainkernel
11
+ Keywords: pytorch,cuda,compiler,training,gpu
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: GPU :: NVIDIA CUDA
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ License-File: NOTICE
26
+ Requires-Dist: torch>=2.8
27
+ Requires-Dist: ninja>=1.11
28
+ Provides-Extra: dev
29
+ Requires-Dist: build>=1.2; extra == "dev"
30
+ Requires-Dist: pytest>=8; extra == "dev"
31
+ Requires-Dist: twine>=5; extra == "dev"
32
+ Dynamic: license-file
33
+
34
+ # TrainKernel
35
+
36
+ TrainKernel compiles a supported static PyTorch training step into one
37
+ cooperative CUDA megakernel. The generated kernel can include the forward pass,
38
+ loss, gradients, and SGD update, so a captured step has no per-operator Python
39
+ launch overhead.
40
+
41
+ The current backend schedules operators in topological order, uses grid barriers for dependencies, inlines single-consumer pointwise operations, and reuses temporary storage after its last reader. BF16 and FP16 matrix multiplications use WMMA tensor cores. FP32 uses a tiled SIMT implementation for accuracy.
42
+
43
+ This is a scoped v0.1 research release for static functional training on NVIDIA
44
+ SM80 GPUs. It is not a general PyTorch compiler and does not claim universal
45
+ speedups.
46
+
47
+ | A100 workload | TrainKernel | Fastest measured Inductor | TrainKernel / Inductor |
48
+ | --- | ---: | ---: | ---: |
49
+ | tiny online MLP | 15.28 μs | 22.85 μs | **0.669, 1.49x faster** |
50
+ | online MLP | 20.32 μs | 24.24 μs | **0.838, 1.19x faster** |
51
+ | small MLP | 66.04 μs | 22.92 μs | 2.894, slower |
52
+ | medium MLP | 255.32 μs | 42.19 μs | 6.052, slower |
53
+
54
+ These are complete forward, backward, and update steps captured as CUDA Graphs.
55
+ The [held-out report](https://github.com/arpjw/trainkernel/blob/main/results/a100-optimization/README.md) publishes all seeds,
56
+ raw timings, correctness checks, baseline failures, and the two regressions.
57
+
58
+ An independent release run adds a one-hot least-squares classification head.
59
+ Across three seeds, TrainKernel's in-place path measured 13.07 us versus
60
+ 18.63 us for the fastest measured Inductor configuration at the median, or
61
+ 1.43x faster. The [release evidence](https://github.com/arpjw/trainkernel/blob/main/results/release-validation/README.md)
62
+ retains all raw samples and correctness failures. Its cold-cache setup took
63
+ 53.62 seconds and required an estimated 7.82 million updates to amortize, so
64
+ this is a steady-state small-workload result rather than a claim about
65
+ short-lived jobs.
66
+
67
+ ## Install
68
+
69
+ Linux, Python 3.10+, PyTorch 2.8+, an NVIDIA SM80+ GPU, a CUDA toolkit with `nvcc`, and a C++ compiler are required for generated kernel execution. CPU capture and IR checks run without CUDA.
70
+
71
+ ```bash
72
+ python -m pip install trainkernel
73
+ ```
74
+
75
+ For development:
76
+
77
+ ```bash
78
+ python -m venv --system-site-packages .venv
79
+ source .venv/bin/activate
80
+ python -m pip install -e '.[dev]'
81
+ python -m pytest -q
82
+ python -m examples.online_training
83
+ ```
84
+
85
+ The backend targets SM80+, including A100 and H100. Release evidence is A100-only; H100 has not been tested and Hopper TMA/WGMMA paths are not implemented.
86
+
87
+ ## Compile a training step
88
+
89
+ ```python
90
+ import torch
91
+ import trainkernel
92
+
93
+ def train_step(weights, x, target):
94
+ def loss(w):
95
+ return ((torch.relu(x @ w) - target) ** 2).mean()
96
+ gradients, value = torch.func.grad_and_value(loss)(weights)
97
+ return value, gradients, weights - 1e-3 * gradients
98
+
99
+ compiled = trainkernel.compile_training(train_step, (weights, x, target))
100
+ loss, gradients, weights = compiled(weights, x, target)
101
+ ```
102
+
103
+ `compile_training` returns a typed `CompiledTrainingStep`. It verifies that
104
+ gradients match state structure and derives the update mapping, including nested
105
+ state trees. The supplied state must be detached from autograd because the
106
+ training function computes its own gradients. `compiled.capture(...)` creates a
107
+ CUDA Graph after warmup, restores the supplied state after warmup and capture,
108
+ and returns a reusable `CapturedProgram`; replay outputs borrow captured buffers
109
+ with fixed shapes and addresses. See the [100-update example](https://github.com/arpjw/trainkernel/blob/main/examples/online_training.py).
110
+
111
+ Parameters may be nested dictionaries or tuples. Inputs and operations must stay on one device; resolve lazy negative or conjugate input views before compiling. Updated parameters are returned explicitly. The compiler proves direct last-read state commits where safe and stages all other updates transactionally; input mutation and arbitrary aliasing remain unsupported. Different shapes, strides, devices, or dtypes require another compilation.
112
+
113
+ Inspect the compiler without a GPU:
114
+
115
+ ```python
116
+ program, output_tree = trainkernel.capture(train_step, cpu_examples)
117
+ from trainkernel.codegen import generate
118
+ cuda_source = generate(program).source
119
+ ```
120
+
121
+ ## Benchmark
122
+
123
+ ```bash
124
+ bash scripts/run_train_loop_suite.sh results/a100-optimization/heldout
125
+ ```
126
+
127
+ For a clean release-candidate check, including the useful classification-head
128
+ workload and package build:
129
+
130
+ ```bash
131
+ bash scripts/run_release_validation.sh results/release-validation
132
+ ```
133
+
134
+ The [training-loop harness](https://github.com/arpjw/trainkernel/blob/main/benchmarks/train_loop.py) uses FP32 master weights, BF16 compute, FP32 loss, and FP32 SGD updates. It checks every loss, gradient, and updated parameter for 100 steps and separately checks a captured 20-step replay. Timed graphs include state feedback over four resident batches. They compare pure and in-place megakernels, captured eager PyTorch, and default and eager-rounding Inductor variants. CUDA event timings exclude compilation, capture, reset, and warmup, and retain raw samples. Numerical failures remain visible for all baselines. The [methodology](https://github.com/arpjw/trainkernel/blob/main/docs/a100-methodology.md) explains the held-out seeds and fixed tolerance policy; the [result](https://github.com/arpjw/trainkernel/blob/main/results/a100-optimization/README.md) includes both wins and regressions. The older [native-BF16 fixed-step harness](https://github.com/arpjw/trainkernel/blob/main/benchmarks/train_mlp.py) remains available for the historical report.
135
+
136
+ ## Supported subset
137
+
138
+ - FP32, BF16, and FP16 strided tensors with static shapes.
139
+ - Matrix multiplication and `addmm`, broadcast arithmetic, ReLU and its backward, scalar powers, sums and means, dtype casts, fills, and supported storage views.
140
+ - Pure tensor functions, including explicit differentiation through `torch.func.grad_and_value`.
141
+
142
+ Unsupported operations produce an error. There is no silent eager fallback. Attention, dropout/RNG, convolutions, dynamic shapes, arbitrary input mutation, distributed collectives, and asynchronous task-queue scheduling are not implemented.
143
+
144
+ Temporary values use FP32 workspace storage with explicit rounding at low-precision boundaries. Fusion reduces materialization but does not keep an entire model on-chip. The tested larger GEMMs run faster in Inductor; the report keeps those regressions visible.
145
+
146
+ ## Design and evidence
147
+
148
+ See [compiler design](https://github.com/arpjw/trainkernel/blob/main/docs/design.md), [A100 optimization evidence](https://github.com/arpjw/trainkernel/blob/main/results/a100-optimization/README.md), [independent release validation](https://github.com/arpjw/trainkernel/blob/main/results/release-validation/README.md), and [GPU access record](https://github.com/arpjw/trainkernel/blob/main/docs/infrastructure.md). CPU tests validate IR semantics, views, reductions, diagnostics, and arena lifetimes. The independent release suite passed 116 tests that compile and execute generated CUDA, compare training outputs across precisions, and exercise CUDA Graph replay.
149
+
150
+ ## Related work and roadmap
151
+
152
+ Most adjacent public megakernel systems currently focus on inference:
153
+ [HazyResearch Megakernels](https://github.com/HazyResearch/Megakernels) targets
154
+ low-latency Llama inference, [MegaBake](https://github.com/megabake/megabake)
155
+ captures PyTorch inference workloads for SM90, [AutoMegaKernel](https://github.com/RightNow-AI/AutoMegaKernel)
156
+ generates Llama-family inference kernels, and [Mirage Persistent Kernel](https://arxiv.org/abs/2512.22219)
157
+ targets multi-GPU model inference. TrainKernel instead explores compiling the
158
+ stateful forward, loss, backward, and optimizer update of a small training step
159
+ on A100 into one kernel. It does not claim priority for megakernel compilation
160
+ in general.
161
+
162
+ The next engineering priorities are a measured shape-aware dispatcher that can
163
+ delegate GEMM-heavy steps to Inductor, an experimental `torch.compile` backend
164
+ after AOTAutograd, AdamW, and additional real online-learning workloads. These
165
+ are roadmap items, not v0.1 capabilities.
166
+
167
+ ## License
168
+
169
+ Apache License 2.0. See [LICENSE](https://github.com/arpjw/trainkernel/blob/main/LICENSE) and [NOTICE](https://github.com/arpjw/trainkernel/blob/main/NOTICE).
@@ -0,0 +1,136 @@
1
+ # TrainKernel
2
+
3
+ TrainKernel compiles a supported static PyTorch training step into one
4
+ cooperative CUDA megakernel. The generated kernel can include the forward pass,
5
+ loss, gradients, and SGD update, so a captured step has no per-operator Python
6
+ launch overhead.
7
+
8
+ The current backend schedules operators in topological order, uses grid barriers for dependencies, inlines single-consumer pointwise operations, and reuses temporary storage after its last reader. BF16 and FP16 matrix multiplications use WMMA tensor cores. FP32 uses a tiled SIMT implementation for accuracy.
9
+
10
+ This is a scoped v0.1 research release for static functional training on NVIDIA
11
+ SM80 GPUs. It is not a general PyTorch compiler and does not claim universal
12
+ speedups.
13
+
14
+ | A100 workload | TrainKernel | Fastest measured Inductor | TrainKernel / Inductor |
15
+ | --- | ---: | ---: | ---: |
16
+ | tiny online MLP | 15.28 μs | 22.85 μs | **0.669, 1.49x faster** |
17
+ | online MLP | 20.32 μs | 24.24 μs | **0.838, 1.19x faster** |
18
+ | small MLP | 66.04 μs | 22.92 μs | 2.894, slower |
19
+ | medium MLP | 255.32 μs | 42.19 μs | 6.052, slower |
20
+
21
+ These are complete forward, backward, and update steps captured as CUDA Graphs.
22
+ The [held-out report](https://github.com/arpjw/trainkernel/blob/main/results/a100-optimization/README.md) publishes all seeds,
23
+ raw timings, correctness checks, baseline failures, and the two regressions.
24
+
25
+ An independent release run adds a one-hot least-squares classification head.
26
+ Across three seeds, TrainKernel's in-place path measured 13.07 us versus
27
+ 18.63 us for the fastest measured Inductor configuration at the median, or
28
+ 1.43x faster. The [release evidence](https://github.com/arpjw/trainkernel/blob/main/results/release-validation/README.md)
29
+ retains all raw samples and correctness failures. Its cold-cache setup took
30
+ 53.62 seconds and required an estimated 7.82 million updates to amortize, so
31
+ this is a steady-state small-workload result rather than a claim about
32
+ short-lived jobs.
33
+
34
+ ## Install
35
+
36
+ Linux, Python 3.10+, PyTorch 2.8+, an NVIDIA SM80+ GPU, a CUDA toolkit with `nvcc`, and a C++ compiler are required for generated kernel execution. CPU capture and IR checks run without CUDA.
37
+
38
+ ```bash
39
+ python -m pip install trainkernel
40
+ ```
41
+
42
+ For development:
43
+
44
+ ```bash
45
+ python -m venv --system-site-packages .venv
46
+ source .venv/bin/activate
47
+ python -m pip install -e '.[dev]'
48
+ python -m pytest -q
49
+ python -m examples.online_training
50
+ ```
51
+
52
+ The backend targets SM80+, including A100 and H100. Release evidence is A100-only; H100 has not been tested and Hopper TMA/WGMMA paths are not implemented.
53
+
54
+ ## Compile a training step
55
+
56
+ ```python
57
+ import torch
58
+ import trainkernel
59
+
60
+ def train_step(weights, x, target):
61
+ def loss(w):
62
+ return ((torch.relu(x @ w) - target) ** 2).mean()
63
+ gradients, value = torch.func.grad_and_value(loss)(weights)
64
+ return value, gradients, weights - 1e-3 * gradients
65
+
66
+ compiled = trainkernel.compile_training(train_step, (weights, x, target))
67
+ loss, gradients, weights = compiled(weights, x, target)
68
+ ```
69
+
70
+ `compile_training` returns a typed `CompiledTrainingStep`. It verifies that
71
+ gradients match state structure and derives the update mapping, including nested
72
+ state trees. The supplied state must be detached from autograd because the
73
+ training function computes its own gradients. `compiled.capture(...)` creates a
74
+ CUDA Graph after warmup, restores the supplied state after warmup and capture,
75
+ and returns a reusable `CapturedProgram`; replay outputs borrow captured buffers
76
+ with fixed shapes and addresses. See the [100-update example](https://github.com/arpjw/trainkernel/blob/main/examples/online_training.py).
77
+
78
+ Parameters may be nested dictionaries or tuples. Inputs and operations must stay on one device; resolve lazy negative or conjugate input views before compiling. Updated parameters are returned explicitly. The compiler proves direct last-read state commits where safe and stages all other updates transactionally; input mutation and arbitrary aliasing remain unsupported. Different shapes, strides, devices, or dtypes require another compilation.
79
+
80
+ Inspect the compiler without a GPU:
81
+
82
+ ```python
83
+ program, output_tree = trainkernel.capture(train_step, cpu_examples)
84
+ from trainkernel.codegen import generate
85
+ cuda_source = generate(program).source
86
+ ```
87
+
88
+ ## Benchmark
89
+
90
+ ```bash
91
+ bash scripts/run_train_loop_suite.sh results/a100-optimization/heldout
92
+ ```
93
+
94
+ For a clean release-candidate check, including the useful classification-head
95
+ workload and package build:
96
+
97
+ ```bash
98
+ bash scripts/run_release_validation.sh results/release-validation
99
+ ```
100
+
101
+ The [training-loop harness](https://github.com/arpjw/trainkernel/blob/main/benchmarks/train_loop.py) uses FP32 master weights, BF16 compute, FP32 loss, and FP32 SGD updates. It checks every loss, gradient, and updated parameter for 100 steps and separately checks a captured 20-step replay. Timed graphs include state feedback over four resident batches. They compare pure and in-place megakernels, captured eager PyTorch, and default and eager-rounding Inductor variants. CUDA event timings exclude compilation, capture, reset, and warmup, and retain raw samples. Numerical failures remain visible for all baselines. The [methodology](https://github.com/arpjw/trainkernel/blob/main/docs/a100-methodology.md) explains the held-out seeds and fixed tolerance policy; the [result](https://github.com/arpjw/trainkernel/blob/main/results/a100-optimization/README.md) includes both wins and regressions. The older [native-BF16 fixed-step harness](https://github.com/arpjw/trainkernel/blob/main/benchmarks/train_mlp.py) remains available for the historical report.
102
+
103
+ ## Supported subset
104
+
105
+ - FP32, BF16, and FP16 strided tensors with static shapes.
106
+ - Matrix multiplication and `addmm`, broadcast arithmetic, ReLU and its backward, scalar powers, sums and means, dtype casts, fills, and supported storage views.
107
+ - Pure tensor functions, including explicit differentiation through `torch.func.grad_and_value`.
108
+
109
+ Unsupported operations produce an error. There is no silent eager fallback. Attention, dropout/RNG, convolutions, dynamic shapes, arbitrary input mutation, distributed collectives, and asynchronous task-queue scheduling are not implemented.
110
+
111
+ Temporary values use FP32 workspace storage with explicit rounding at low-precision boundaries. Fusion reduces materialization but does not keep an entire model on-chip. The tested larger GEMMs run faster in Inductor; the report keeps those regressions visible.
112
+
113
+ ## Design and evidence
114
+
115
+ See [compiler design](https://github.com/arpjw/trainkernel/blob/main/docs/design.md), [A100 optimization evidence](https://github.com/arpjw/trainkernel/blob/main/results/a100-optimization/README.md), [independent release validation](https://github.com/arpjw/trainkernel/blob/main/results/release-validation/README.md), and [GPU access record](https://github.com/arpjw/trainkernel/blob/main/docs/infrastructure.md). CPU tests validate IR semantics, views, reductions, diagnostics, and arena lifetimes. The independent release suite passed 116 tests that compile and execute generated CUDA, compare training outputs across precisions, and exercise CUDA Graph replay.
116
+
117
+ ## Related work and roadmap
118
+
119
+ Most adjacent public megakernel systems currently focus on inference:
120
+ [HazyResearch Megakernels](https://github.com/HazyResearch/Megakernels) targets
121
+ low-latency Llama inference, [MegaBake](https://github.com/megabake/megabake)
122
+ captures PyTorch inference workloads for SM90, [AutoMegaKernel](https://github.com/RightNow-AI/AutoMegaKernel)
123
+ generates Llama-family inference kernels, and [Mirage Persistent Kernel](https://arxiv.org/abs/2512.22219)
124
+ targets multi-GPU model inference. TrainKernel instead explores compiling the
125
+ stateful forward, loss, backward, and optimizer update of a small training step
126
+ on A100 into one kernel. It does not claim priority for megakernel compilation
127
+ in general.
128
+
129
+ The next engineering priorities are a measured shape-aware dispatcher that can
130
+ delegate GEMM-heavy steps to Inductor, an experimental `torch.compile` backend
131
+ after AOTAutograd, AdamW, and additional real online-learning workloads. These
132
+ are roadmap items, not v0.1 capabilities.
133
+
134
+ ## License
135
+
136
+ Apache License 2.0. See [LICENSE](https://github.com/arpjw/trainkernel/blob/main/LICENSE) and [NOTICE](https://github.com/arpjw/trainkernel/blob/main/NOTICE).
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "trainkernel"
7
+ version = "0.1.0"
8
+ description = "Compile a complete static PyTorch training step into one CUDA kernel"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE", "NOTICE"]
12
+ authors = [{name = "Arya Somu"}]
13
+ requires-python = ">=3.10"
14
+ dependencies = ["torch>=2.8", "ninja>=1.11"]
15
+ keywords = ["pytorch", "cuda", "compiler", "training", "gpu"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Environment :: GPU :: NVIDIA CUDA",
19
+ "Intended Audience :: Developers",
20
+ "Intended Audience :: Science/Research",
21
+ "Operating System :: POSIX :: Linux",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/arpjw/trainkernel"
31
+ Documentation = "https://github.com/arpjw/trainkernel#readme"
32
+ Issues = "https://github.com/arpjw/trainkernel/issues"
33
+ Source = "https://github.com/arpjw/trainkernel"
34
+
35
+ [tool.pytest.ini_options]
36
+ testpaths = ["tests"]
37
+
38
+ [project.optional-dependencies]
39
+ dev = ["build>=1.2", "pytest>=8", "twine>=5"]
40
+
41
+ [tool.setuptools.packages.find]
42
+ include = ["trainkernel*"]
43
+
44
+ [tool.setuptools.package-data]
45
+ trainkernel = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,89 @@
1
+ import pytest
2
+ import torch
3
+
4
+ from benchmarks.train_loop import (
5
+ _amortization,
6
+ _bootstrap_speedup_ci,
7
+ _close_training,
8
+ _trajectory,
9
+ make_batches,
10
+ step_master,
11
+ )
12
+
13
+
14
+ def test_amortization_includes_both_methods_setup_and_handles_no_win():
15
+ timings = {"mega": {"median_ms": 1.0}, "reference": {"median_ms": 2.0}}
16
+ compilation = {"mega": 2.0, "reference": 0.5}
17
+ capture = {"mega": 0.2, "reference": 0.1}
18
+ result = _amortization("mega", "reference", timings, compilation, capture)
19
+ assert result["incremental_setup_seconds"] == pytest.approx(1.6)
20
+ assert result["break_even_steps"] == pytest.approx(1600.0)
21
+
22
+ timings["mega"]["median_ms"] = 3.0
23
+ slower = _amortization("mega", "reference", timings, compilation, capture)
24
+ assert slower["break_even_steps"] is None
25
+ assert slower["break_even_defined"] is False
26
+
27
+
28
+ def test_training_policy_checks_loss_dtype_and_all_outputs():
29
+ params, batches = make_batches(2, 3, 4, 2, torch.bfloat16, torch.device("cpu"), 1, seed=17)
30
+ master = tuple(p.float() for p in params)
31
+ expected = step_master(master, *batches[0], 1e-3)
32
+ bad_loss = (expected[0].bfloat16(), expected[1], expected[2])
33
+ with pytest.raises(AssertionError):
34
+ _close_training(bad_loss, expected)
35
+ bad_gradients = (expected[0], tuple(g for g in expected[1][:-1]), expected[2])
36
+ with pytest.raises(AssertionError):
37
+ _close_training(bad_gradients, expected)
38
+
39
+
40
+ def test_teacher_targets_produce_finite_long_trajectory():
41
+ params, batches = make_batches(4, 8, 16, 4, torch.bfloat16, torch.device("cpu"), 4, seed=211)
42
+ master = tuple(p.float() for p in params)
43
+ losses, _ = _trajectory(lambda p, x, y: step_master(p, x, y, 1e-3), master, batches, 100)
44
+ assert len(losses) == 100
45
+ assert all(torch.isfinite(torch.tensor(losses)))
46
+
47
+
48
+ def test_classification_head_targets_are_one_hot_and_finite():
49
+ params, batches = make_batches(8, 6, 10, 4, torch.bfloat16, torch.device("cpu"), 3, seed=211, task="classification-head")
50
+ assert all(target.shape == (8, 4) for _, target in batches)
51
+ assert all(torch.equal(target.sum(dim=-1), torch.ones(8, dtype=torch.bfloat16)) for _, target in batches)
52
+ master = tuple(p.float() for p in params)
53
+ losses, _ = _trajectory(lambda p, x, y: step_master(p, x, y, 1e-3), master, batches, 20)
54
+ assert all(torch.isfinite(torch.tensor(losses)))
55
+
56
+
57
+ def test_bootstrap_is_deterministic_and_lower_ratio_is_faster():
58
+ a = [1.0, 1.1, 0.9, 1.05]
59
+ b = [2.0, 2.1, 1.9, 2.05]
60
+ first = _bootstrap_speedup_ci(a, b)
61
+ second = _bootstrap_speedup_ci(a, b)
62
+ assert first == second
63
+ assert first["median_ratio"] < 1.0
64
+ assert first["draws"] == 2000 and first["seed"] == 0
65
+
66
+
67
+ def test_report_mode_continues_after_baseline_mismatch():
68
+ params, batches = make_batches(2, 3, 4, 2, torch.bfloat16, torch.device("cpu"), 1, seed=307)
69
+ master = tuple(p.float() for p in params)
70
+ def bad(p, x, y):
71
+ loss, grads, updated = step_master(p, x, y, 1e-3)
72
+ return loss + 1.0, grads, updated
73
+ losses, _, report = _trajectory(bad, master, batches, 4, enforce=False, report=True)
74
+ assert len(losses) == 4
75
+ assert report["passed"] is False
76
+ assert report["first_failure_step"] == 0
77
+ with pytest.raises(AssertionError):
78
+ _trajectory(bad, master, batches, 4)
79
+
80
+
81
+ def test_report_mode_measures_nonzero_error_for_passing_perturbation():
82
+ params, batches = make_batches(2, 3, 4, 2, torch.bfloat16, torch.device("cpu"), 1, seed=101)
83
+ master = tuple(p.float() for p in params)
84
+ def near(p, x, y):
85
+ loss, grads, updated = step_master(p, x, y, 1e-3)
86
+ return loss, grads, tuple(value + 1e-8 for value in updated)
87
+ _, _, report = _trajectory(near, master, batches, 2, enforce=False, report=True)
88
+ assert report["passed"] is True
89
+ assert report["max_absolute_error"] > 0.0