channellast 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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,267 @@
1
+ Metadata-Version: 2.4
2
+ Name: channellast
3
+ Version: 0.1.0
4
+ Summary: Channels-last rewrite of the ONNX ops fixed to NCHW (Conv, pools, norms...) for TensorRT: standard ops + AOT NVRTC plugins
5
+ Author: tuan2k33
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/tuan2k33/channellast
8
+ Project-URL: Issues, https://github.com/tuan2k33/channellast/issues
9
+ Keywords: tensorrt,onnx,nhwc,channels-last,convnext,cuda,plugin
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Environment :: GPU :: NVIDIA CUDA
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: onnx
18
+ Requires-Dist: numpy
19
+ Requires-Dist: tensorrt
20
+ Requires-Dist: cuda-core[cu13]
21
+ Requires-Dist: nvidia-cuda-runtime
22
+ Provides-Extra: bench
23
+ Requires-Dist: torch; extra == "bench"
24
+ Requires-Dist: timm; extra == "bench"
25
+ Requires-Dist: onnxruntime; extra == "bench"
26
+ Dynamic: license-file
27
+
28
+ # channellast
29
+
30
+ ONNX fixes Conv, pooling, BatchNorm/InstanceNorm/GroupNorm, DepthToSpace/SpaceToDepth, GridSample and RoiAlign to NCHW. TensorRT runs
31
+ them channels-last inside anyway, but when such an op sits next to a last-axis op (LayerNorm over channels, a Linear as MatMul, softmax
32
+ over channels) the graph carries a Transpose on each side, and TensorRT does not remove them: ConvNeXt-T spends about a quarter of its
33
+ time moving data around its 18 depthwise convs.
34
+
35
+ `channellast` rewrites the ONNX graph so those ops run on NHWC tensors:
36
+
37
+ - **standard ONNX ops** wherever an equivalent exists and is not slower (1x1 and patchify convs as MatMul, global pools as Reduce,
38
+ BatchNorm as Mul/Add over the last axis, DepthToSpace as inner-axis Reshape/Transpose);
39
+ - **NHWC CUDA kernels** as TensorRT AOT Python plugins where no standard form exists or it was clearly slower (depthwise conv, pools,
40
+ Instance/GroupNorm, GridSample, RoiAlign). The PTX is stored inside the engine: the engine runs on plain TensorRT (`trtexec`, C++), no `.so` to ship.
41
+
42
+ Layout is chosen per connected region of the graph to minimise the bytes moved by transposes, so all-conv networks (ResNet, MobileNet)
43
+ are left exactly as they are, and ConvNeXt-like ones go NHWC end to end.
44
+
45
+ ## Use
46
+
47
+ ```bash
48
+ pip install channellast # or pip install -e . in a clone; [bench] adds torch, timm, onnxruntime for the benchmarks
49
+ channellast build model.onnx model.engine --shapes x:1x3x224x224,8x3x224x224,64x3x224x224 [--opt-level 3] [--check]
50
+ trtexec --loadEngine=model.engine # runs on plain TensorRT: no plugin library (DeepStream model-engine-file too)
51
+
52
+ channellast convert model.onnx model.cl.onnx [--no-flat] # only the rewritten ONNX
53
+ channellast bench model.onnx --input x --shape 3x224x224 [--both] # original vs rewritten engine: ms at batch 1/8/64, profile, cos
54
+ channellast bench-ops [--only dwconv] # per-op table: each lowering vs the original op (below)
55
+ ```
56
+
57
+ `channellast build` rewrites the ONNX and builds the engine on this GPU; `--check` also builds the original and prints the output cos.
58
+ Needs TensorRT with AOT Python plugins (`tensorrt.plugin.aot_impl`, recent 10.x and 11), `cuda-core` and NVRTC, and `cuda_fp16.h`
59
+ (found in `$CUDA_HOME`, `/usr/local/cuda` or the pip `nvidia-cuda-runtime` package; `CHANNELLAST_CUDA_INCLUDE` overrides). `python -m
60
+ channellast` works too.
61
+
62
+ ```python
63
+ import onnx
64
+ from channellast import rewrite
65
+ from channellast.engine import build
66
+ model, stats = rewrite(onnx.load("model.onnx"), io="keep", conv="keep") # flat=True is the default
67
+ build(model, "model.engine", {"x": ((1, 3, 224, 224), (8, 3, 224, 224), (64, 3, 224, 224))})
68
+ ```
69
+
70
+ `trtexec --onnx` cannot build the rewritten ONNX: the plugins are registered from Python while building, so build with `channellast
71
+ build` (or `channellast.engine.build`) and hand the engine to trtexec / DeepStream / your runtime. Engines are tied to the GPU and
72
+ TensorRT version, so on a Jetson build on the Jetson (NVRTC compiles for the GPU it runs on; `CHANNELLAST_ARCH=87` forces an
73
+ architecture). Where the Jetson has no Python or a TensorRT without AOT plugins, `cross/` builds the same plugins as a C++ plugin
74
+ library cross-compiled on the PC (`trtexec --onnx=model.cl.onnx --dynamicPlugins=libchannellast_plugins.so`); not part of the pip
75
+ package, tested on x86 only.
76
+
77
+ By default (flat) the channels-last region also runs on 2D [N*H*W, C] tensors where H and W are fixed: every op that only works on
78
+ the channel axis (elementwise, Q/DQ, LayerNorm, Softmax, last-axis Reduce, MatMul, the depthwise and norm plugins), with one Reshape in
79
+ and one out where an op needs H and W. Equal or faster everywhere measured (below), and it is what makes opt level 5 work. Where H or W is
80
+ dynamic the region stays 4D (no error); `--no-flat` (`flat=False`) keeps it 4D everywhere. All-conv nets are not affected either way.
81
+
82
+ ## Ops
83
+
84
+ Feature maps of rank 3-5 ([N, C, L], [N, C, H, W], [N, C, D, H, W]) go channels-last ([N, *spatial, C]); every lowering is written
85
+ once for 1D / 2D / 3D, and the plugins are 3D kernels where 1D / 2D run with unit leading dimensions (compile-time constants, no cost).
86
+
87
+ | Group (file) | Op | Channels-last form |
88
+ |---|---|---|
89
+ | conv | Conv 1x1 (any stride) | [strided Slice] + MatMul; with Q/DQ and `--no-flat`: Reshape to [N*spatial, C, 1, 1] + Conv 1x1 + Reshape back |
90
+ | conv | Conv kernel == stride, no pad (patchify, downsample) | strided Slices + Concat + MatMul |
91
+ | conv | Conv depthwise (any kernel, stride, pads, dilation) | plugin `nhwc::dwconv` |
92
+ | conv | other group-1 Conv | left to TensorRT (stays NCHW: the layout choice keeps it in an original-layout region) |
93
+ | conv | ConvTranspose kernel == stride | MatMul + pixel shuffle |
94
+ | pool | GlobalAveragePool / GlobalMaxPool | ReduceMean / ReduceMax over the spatial axes |
95
+ | pool | Max/AveragePool (any kernel, stride, pads, dilation, ceil_mode, count_include_pad) | plugin `nhwc::pool` |
96
+ | norm | BatchNormalization (inference) | Mul + Add |
97
+ | norm | InstanceNormalization, GroupNormalization (opset 18 and 21) | plugin `nhwc::group_norm` (InstanceNorm: groups = C) |
98
+ | space | DepthToSpace (DCR, CRD), SpaceToDepth (4D only, as in ONNX) | Reshape + inner-axis Transpose + Reshape |
99
+ | sample | GridSample 2D (linear / nearest; zeros / border / reflection) | plugin `nhwc::grid_sample` |
100
+ | sample | RoiAlign (avg / max, half_pixel / output_half_pixel) | plugin `nhwc::roi_align` |
101
+
102
+ Layout-free ops follow their inputs with axes remapped: elementwise (with constant or scalar broadcast operands), Q/DQ, Concat, Split,
103
+ Slice, Pad, Resize, Reduce*, ArgMax/Min, Softmax, Expand, Tile, Shape (re-gathered to logical order). Anything else (Reshape, MatMul on
104
+ feature maps, LayerNormalization over the last axis...) keeps the original layout, with a Transpose in front only if the cost model
105
+ wants one. Not handled: LRN, LpPool, Col2Im, DeformConv, GridSample cubic / 3D.
106
+
107
+ ### Q/DQ (INT8) graphs
108
+
109
+ - Per-tensor activation Q/DQ is layout-free; per-channel Q/DQ gets its axis remapped; per-channel weight scales follow the weight
110
+ (Conv axis 0 -> MatMul axis 1 for patchify; ConvTranspose scales repeated per kernel tap).
111
+ - A per-tensor Q/DQ in front of a lowering that moves data (strided Slice and Reshape of a 1x1 conv, patchify Slices + Concat)
112
+ is re-applied after the data movement, so TensorRT still sees DequantizeLinear -> Conv / MatMul and runs it in INT8.
113
+ - An NHWC tensor [N, H, W, C] has the memory of an NCHW [N*H*W, C, 1, 1], so with `--no-flat` an INT8 1x1 conv stays a standard
114
+ Conv: TensorRT runs its own INT8 conv kernel (faster and closer to FP32 than the Myelin GEMM a MatMul becomes, which adds a
115
+ separate output Cast kernel). Flat graphs keep the MatMul: TensorRT 11.5 fails to build them at opt level 3 (a fusePattern
116
+ assertion) when the Conv's [M, Co, 1, 1] output feeds a 2D elementwise op.
117
+ - When act scale x weight scale falls below the FP16 normal range (6.1e-5) the weight scales are raised by 2^n and the output
118
+ multiplied by 2^-n: TensorRT multiplies the two in FP16, in Myelin GEMMs and in its own conv alike (test: 25-45% error without,
119
+ TensorRT's NCHW conv included; 0.2% with).
120
+ - Depthwise convs become the plugin: with a symmetric per-tensor Q/DQ in front it reads the INT8 tensor (the scale folded into its
121
+ weights), and when its only consumer is such a Q it writes INT8 (the Q done in its store). TensorRT cannot fuse a Q or DQ into a
122
+ plugin, so each one left next to it would be its own kernel (~0.35 ms each at ConvNeXt stage-1 size, batch 64).
123
+
124
+ ## Results (RTX 3050 Ti Laptop, TensorRT 11.5, GPU time per batch, `channellast bench`)
125
+
126
+ DINOv3 ConvNeXt-T (ModelTemplate Classifier backbone, uint8 NHWC image in, resized to 224 inside the graph), batch 1 / 8 / 64 in ms,
127
+ all rows measured in one session (2026-12-05, driver 621.47):
128
+
129
+ | Graph | opt level 3 | opt level 5 | transposes + reformats at 64 (o3 / o5) |
130
+ |---|---|---|---|
131
+ | FP16, original (36 transposes) | 3.10 / 9.11 / 65.46 | 2.76 / 8.67 / 60.08 | 15.4 / 12.7 ms |
132
+ | FP16, channellast `--no-flat` | 2.13 / 7.05 / 49.99 | 2.93 / 9.09 / 62.32 | 0 / 6.7 ms |
133
+ | FP16, channellast (flat) | **2.08 / 6.19 / 39.71** | 2.21 / 6.38 / 40.40 | 0 / 1.1 ms |
134
+ | INT8 Q/DQ, original | 2.27 / 6.50 / 42.33 | 2.11 / 6.29 / 40.40 | 12.0 / 12.0 ms |
135
+ | INT8 Q/DQ, channellast `--no-flat` | 1.73 / 4.74 / 30.42 | 2.56 / 6.83 / 42.94 | 0 / 6.5 ms |
136
+ | INT8 Q/DQ, channellast (flat) | **1.61 / 4.31 / 28.07** | 1.63 / 4.77 / 30.00 | 0 / 0.9 ms |
137
+
138
+ The INT8 graph is ModelTemplate's mixed INT8 one before its channels-last rewrite (Q/DQ on the stem / downsample and pointwise
139
+ MatMuls; depthwise convs, LayerNorm and GELU in FP16). Outputs against the original engine: cos 0.99999 (FP16) and 0.9995 mean / 0.9991
140
+ min (INT8, both rewrites alike). The 0.9-1.1 ms left at opt level 5 is a Reformat on each side of the first depthwise conv.
141
+
142
+ timm ConvNeXt-T FP16 at 224 (same session):
143
+
144
+ | Graph | opt level 3 | opt level 5 |
145
+ |---|---|---|
146
+ | original (46 transposes) | 2.90 / 8.87 / 63.30 | 2.35 / 7.55 / 53.56 |
147
+ | channellast `--no-flat` | 2.18 / 7.08 / 49.95 | 3.09 / 9.08 / 62.39 |
148
+ | channellast (flat) | **2.09 / 5.87 / 37.13** | 2.11 / 5.95 / 38.58 |
149
+
150
+ Opt level 5 with `--no-flat` is slower: TensorRT stores Myelin's 4D tensors as NHWC8, which for an [N, H, W, C] tensor treats H as the
151
+ channel axis, and puts a Reformat on each side of every plugin (plugins are LINEAR only). 2D tensors can only be LINEAR, so on the
152
+ flattened graph there is nothing left to reformat.
153
+
154
+ `dwconv`: a thread computes a tile of output pixels for 2 channels, loading each input row of the tile once (one 4-byte load per input
155
+ pixel). FP16 input runs half2 math: each input row's taps are summed in half2 and added to an FP32 accumulator (error about 2x the FP16
156
+ output rounding: 1e-3 of max |y| vs 5e-4 before). TensorRT picks per layer among 4 tile shapes (plugin tactics: 2x8, 3x8, 1x14, 2x16;
157
+ FP32 / INT8 input keeps the FP32-math kernel with 4x4, 3x4, 1x4 x 4 channels, 4x8 x 1 channel). The 18 ConvNeXt-T depthwise layers at
158
+ batch 64 take 3.6-3.7 ms (4.7 ms with the FP32-math kernel, same session; a plain copy of the same tensors takes 3.1 ms). Tried and
159
+ dropped: a shared-memory input tile with halo per block (5.05-5.9 ms in a standalone harness, vs 4.5 ms for the FP32-math kernel and
160
+ 3.5 ms for half2). ResNet18 and MobileNetV3-Small come out unchanged (0 plugins, 0 transposes, the same graph flat or not).
161
+
162
+ `channellast bench model.onnx --both` reproduces a row (original, `--no-flat`, flat).
163
+
164
+ ### Per op
165
+
166
+ `channellast bench-ops [--only dwconv] [--batches 1,64]` builds each lowering on its own (single-op graph, FP16, realistic sizes) and
167
+ compares, on TensorRT at opt level 3: the original op (NCHW in and out), the original op with the NHWC <-> NCHW transposes a
168
+ channels-last neighbour needs, and the rewrite with NHWC I/O (flat where it changes the graph, else `--no-flat`). Errors are max
169
+ |out - ref| / max |ref| and cosine against onnxruntime FP32 on the original graph. `cache/bench_ops.md` marks a row as a regression
170
+ when ours is more than 3% slower than the original op alone, or its error is more than 1.5x the original's. Batch 64 in ms, plus
171
+ ours vs original at batch 1 (all rows, flat and not, in `cache/bench_ops.md`; one session, 2026-12-05):
172
+
173
+ | Op | Shape | Original | Original + T | Ours | vs original | vs original + T | Original err / cos | Ours err / cos | vs original, batch 1 |
174
+ |---|---|---|---|---|---|---|---|---|---|
175
+ | Conv 1x1 | 256->64 @56 | 2.408 | 3.731 | 0.770 | 3.13x | 4.84x | 1.5e-03 / 1.00000 | 2.2e-03 / 1.00000 | 4.30x (0.083 / 0.019 ms) |
176
+ | Conv 1x1 stride 2 | 256->512 @56 | 2.406 | 3.956 | 0.967 | 2.49x | 4.09x | 2.3e-03 / 1.00000 | 2.3e-03 / 1.00000 | 1.22x (0.075 / 0.061 ms) |
177
+ | Conv patchify 4x4/4 (stem) | 3->96 @224 | 1.397 | 1.572 | 1.208 | 1.16x | 1.30x | 1.2e-03 / 1.00000 | 9.8e-04 / 1.00000 | 1.22x (0.044 / 0.036 ms) |
178
+ | Conv 2x2/2 (downsample) | 96->192 @56 | 1.121 | 1.673 | 1.056 | 1.06x | 1.58x | 2.6e-03 / 1.00000 | 3.0e-03 / 1.00000 | 1.41x (0.046 / 0.033 ms) |
179
+ | Conv depthwise 7x7 | 96 @56 | 1.684 | 2.022 | 0.530 | 3.18x | 3.82x | 2.7e-03 / 1.00000 | 7.8e-04 / 1.00000 | 1.89x (0.032 / 0.017 ms) |
180
+ | Conv depthwise 7x7 | 384 @14 | 0.554 | 0.737 | 0.141 | 3.93x | 5.22x | 2.5e-03 / 1.00000 | 8.4e-04 / 1.00000 | 0.78x (0.017 / 0.022 ms) |
181
+ | Conv depthwise 3x3 | 144 @56 | 0.755 | 2.464 | 0.753 | 1.00x | 3.27x | 1.4e-03 / 1.00000 | 7.6e-04 / 1.00000 | 0.84x (0.017 / 0.021 ms) |
182
+ | Conv depthwise 3x3 stride 2 | 144 @56 | 0.442 | 1.422 | 0.495 | 0.89x | 2.87x | 1.2e-03 / 1.00000 | 6.7e-04 / 1.00000 | 1.91x (0.055 / 0.029 ms) |
183
+ | INT8 Conv 1x1 | 256->64 @56 | 1.935 | 3.804 | 2.053 | 0.94x | 1.85x | 9.0e-04 / 1.00000 | 3.9e-03 / 1.00000 | 1.50x (0.071 / 0.047 ms) |
184
+ | INT8 Conv 1x1 `--no-flat` (Conv form) | 256->64 @56 | 1.935 | 3.804 | 1.750 | 1.11x | 2.17x | 9.0e-04 / 1.00000 | 2.3e-03 / 1.00000 | 1.64x (0.071 / 0.043 ms) |
185
+ | INT8 Conv 2x2/2 (downsample) | 96->192 @56 | 0.866 | 1.687 | 1.094 | 0.79x | 1.54x | 1.2e-03 / 1.00000 | 3.8e-03 / 1.00000 | 0.99x (0.052 / 0.053 ms) |
186
+ | INT8 Conv depthwise 7x7 (INT8 in) | 96 @56 | 1.939 | 2.658 | 1.073 | 1.81x | 2.48x | 3.5e-03 / 1.00000 | 3.5e-03 / 1.00000 | 0.93x (0.046 / 0.050 ms) |
187
+ | INT8 Conv depthwise 7x7 (INT8 in, out) | 96 @56 | 2.220 | 3.416 | 1.404 | 1.58x | 2.43x | 1.6e-02 / 0.99983 | 1.6e-02 / 0.99983 | 1.31x (0.086 / 0.066 ms) |
188
+ | ConvTranspose 2x2/2 | 256->128 @28 | 2.000 | 2.479 | 1.233 | 1.62x | 2.01x | 1.7e-03 / 1.00000 | 1.7e-03 / 1.00000 | 1.12x (0.051 / 0.046 ms) |
189
+ | GlobalAveragePool | 768 @7 | 0.062 | 0.073 | 0.038 | 1.63x | 1.92x | 4.2e-04 / 1.00000 | 4.2e-04 / 1.00000 | 0.41x (0.012 / 0.030 ms) |
190
+ | GlobalMaxPool | 768 @7 | 0.058 | 0.077 | 0.045 | 1.30x | 1.71x | 0.0e+00 / 1.00000 | 0.0e+00 / 1.00000 | 0.98x (0.014 / 0.014 ms) |
191
+ | MaxPool 2x2/2 | 64 @112 | 0.788 | 2.579 | 0.783 | 1.01x | 3.29x | 0.0e+00 / 1.00000 | 0.0e+00 / 1.00000 | 0.93x (0.015 / 0.016 ms) |
192
+ | AveragePool 2x2/2 | 64 @112 | 2.375 | 2.557 | 0.780 | 3.04x | 3.28x | 3.7e-04 / 1.00000 | 3.7e-04 / 1.00000 | 0.69x (0.016 / 0.024 ms) |
193
+ | MaxPool 3x3/2 pad 1 (plugin) | 64 @112 | 2.298 | 2.934 | 0.870 | 2.64x | 3.37x | 0.0e+00 / 1.00000 | 0.0e+00 / 1.00000 | 1.35x (0.020 / 0.015 ms) |
194
+ | AveragePool 3x3/1 pad 1 (plugin) | 64 @56 | 0.777 | 1.469 | 0.325 | 2.39x | 4.52x | 3.5e-04 / 1.00000 | 3.5e-04 / 1.00000 | 1.41x (0.029 / 0.021 ms) |
195
+ | BatchNormalization | 64 @112 | 1.282 | 3.984 | 1.274 | 1.01x | 3.13x | 6.0e-04 / 1.00000 | 6.0e-04 / 1.00000 | 1.08x (0.021 / 0.019 ms) |
196
+ | InstanceNormalization | 64 @56 | 0.345 | 0.963 | 0.323 | 1.07x | 2.98x | 6.8e-04 / 1.00000 | 5.5e-04 / 1.00000 | 0.83x (0.019 / 0.023 ms) |
197
+ | GroupNormalization 32 groups | 128 @56 | 0.652 | 1.912 | 0.654 | 1.00x | 2.93x | 6.7e-04 / 1.00000 | 3.6e-04 / 1.00000 | 0.35x (0.011 / 0.033 ms) |
198
+ | DepthToSpace 2 (DCR) | 256 @28 | 0.521 | 1.295 | 0.517 | 1.01x | 2.50x | 0.0e+00 / 1.00000 | 0.0e+00 / 1.00000 | 1.32x (0.018 / 0.014 ms) |
199
+ | SpaceToDepth 2 | 64 @56 | 0.523 | 1.191 | 0.522 | 1.00x | 2.28x | 0.0e+00 / 1.00000 | 0.0e+00 / 1.00000 | 1.74x (0.032 / 0.018 ms) |
200
+ | GridSample bilinear | 64 @56, grid 56x56 | 0.511 | 0.320 | 0.334 | 1.53x | 0.96x | 4.2e-04 / 1.00000 | 4.2e-04 / 1.00000 | 0.49x (0.014 / 0.028 ms) |
201
+ | RoiAlign avg 7x7 | 256 @56, 64 rois / image | 9.080 | 12.186 | 6.787 | 1.34x | 1.80x | 3.6e-01 / 0.99985 | 2.6e-04 / 1.00000 | 1.41x (0.143 / 0.102 ms) |
202
+
203
+ Only ops the rewrite lowers are listed. Dense convs other than 1x1 / patchify are not lowered: the layout choice leaves them in an
204
+ original-layout region, so a graph pays exactly what it paid before for them (a single-op table row would only time TensorRT's conv
205
+ plus the transposes the forced NHWC I/O adds). An im2col lowering (Pad + k*k Slices + Concat + MatMul) was an option until
206
+ 2026-12-05 and is removed: the im2col tensor is k*k times the input, so the 3x3 64->64 @56 conv took 3.1-3.4 ms against TensorRT's
207
+ 1.1 ms (0.37x; 0.49x at 128->128 @28, 0.68x at 256->256 @14). Shift-and-accumulate without the im2col tensor (Pad, then per tap a
208
+ shifted Slice, MatMul by W[kh, kw] and an Add chain / balanced Add tree / Sum, 4D or flat [N*H*W, C]) is worse: TensorRT materializes
209
+ every slice and partial product, 0.21x / 0.28x / 0.41x at batch 64 and 0.07-0.24x at batch 1 on the same three shapes. One MatMul to
210
+ 9 x Co followed by a shifted Sum (3.2 ms) and 3 W-tap Concat + 3 MatMuls (4.0 ms) were no better either.
211
+
212
+ Read as: against the op alone (an NCHW graph with nothing to gain) every lowering is at 0.89x or better at batch 64 except the INT8
213
+ 2x2/2 downsample (0.79x here, 0.80-0.92x in the two other runs of the day; error 3x TensorRT's INT8 conv, cos still 1.00000), and the
214
+ INT8 1x1 MatMul of flat graphs, which reads 0.86-0.94x (error 4x). The layout choice leaves such ops alone unless they sit next to
215
+ last-axis ops, where the "original + T" column is the one that counts (1.5-1.9x). TensorRT's own times move between sessions (INT8
216
+ Conv 2x2/2: 0.76-1.00 ms; depthwise 3x3 stride 2: 1.19 ms in one session, 0.44 in the next three), so a row near 0.8x can read either
217
+ side of it. Changes on 2026-12-05:
218
+ - INT8 Conv 1x1 with `--no-flat`: Reshape of the NHWC tensor to [N*H*W, C, 1, 1] (the same memory) + Q/DQ + a standard Conv 1x1 +
219
+ Reshape back, instead of MatMul. TensorRT runs its own INT8 conv kernel: 256->64 @56 at batch 64 1.41-1.79 ms and 2.3-2.6e-3 error
220
+ across runs (1.1-1.4x the original op; TensorRT's NCHW INT8 conv: 0.9-1.1e-3 error), against 1.85 ms and 3.9e-3 for MatMul (0.86x).
221
+ The bias is an Add after the Reshape back (1.41 vs 1.77 ms inside the Conv, same run). Flat (the default) keeps the MatMul: with the
222
+ Conv form TensorRT 11.5 fails to build at opt level 3 (fusePattern assertion) once the Conv's [M, Co, 1, 1] output reaches a 2D
223
+ elementwise op (bias in or out of the Conv, a 4D bias Add, a 2D Reshape, a 1D Conv: all fail on a Q/DQ ConvNeXt-atto or the single
224
+ op), so the INT8 1x1 flat row stays at 0.86-0.94x. FP16 keeps MatMul everywhere: the Conv form equals the flat MatMul on the single op
225
+ (0.70 ms) but is slower on a whole ConvNeXt-atto (conv_mlp, all MLPs Conv 1x1; 15.2-16.4 vs 13.0-14.2 ms at batch 64, same run). The
226
+ FP16-subnormal scale shift applies to the Conv form too: TensorRT's own NCHW INT8 conv has the same ~25% error there (test).
227
+ - INT8 Conv 2x2/2 (and patchify) stays strided Slices + Concat + Q/DQ + MatMul. Profile at batch 64: the 4 Slices with the re-applied
228
+ Q, the GEMM and a separate Cast kernel (Myelin GEMMs multiply the scales in FP16 and cast in another kernel) against TensorRT's Q +
229
+ INT8 conv + reformat. Tried and dropped (0.48-0.75x of the 0.76 ms original in the same runs): Conv 1x1 on the Slices + Concat
230
+ output (1.02 vs 0.96 ms MatMul, error 2.0e-3 vs 3.4e-3: the Slices run as 4 separate kernels plus 4 Q copies), space-to-depth by
231
+ Reshape + 5D / 6D Transpose before a Conv 1x1 (1.44-1.6 ms: the Transpose is a 0.9 ms shuffle), 2 Slices on the outer axes only
232
+ (1.10 ms), Q before the Slices (TensorRT refuses a Q in front of Slice), Q/DQ before the Slices (the Conv then runs in FP16, 1.9
233
+ ms), MatMul without bias (the Cast kernel stays). The FP16 2x2/2 is faster as Conv 1x1 (0.84 vs 0.99 ms at batch 64) but slower at
234
+ batch 1 (0.065 vs 0.038 ms), and the Cin = 3 stem is slower both ways (1.65 vs 1.08 ms), so patchify keeps MatMul in FP16 too.
235
+ - DINOv3 ConvNeXt-T is unchanged by this: its pointwise layers are MatMul (Linear) in the ONNX and only the stem and 3 downsamples are
236
+ Convs, so the flat graph is the same as before (final run, o3 flat, batch 1 / 8 / 64: FP16 2.31 / 6.71 / 47.90 ms vs original 2.60 /
237
+ 10.34 / 76.51; INT8 1.71 / 5.11 / 34.41 vs 2.31 / 7.63 / 50.82, in a slower-clocked session than the table above; cos 0.99999 and
238
+ 0.99948 mean / 0.99911 min as before).
239
+ - InstanceNorm / GroupNorm: plugin `nhwc::group_norm` instead of Reduce / Sub / Mul / Div (2.26 / 1.33 ms before, 0.29 / 0.58 now,
240
+ equal to TensorRT's own). A block takes one image x 2-16+ channels (whole groups), reads its pixels once into registers while summing
241
+ shifted x and x^2 per channel in FP32, combines per group through shared memory, and writes x * a + b from the registers; tactics
242
+ pick channels per block / per thread and 256-1024 threads. Error is half of TensorRT's.
243
+ - Pools: every Max/AveragePool is the plugin, which now loads 2-8 channels per thread (tactics); the crop + Reshape + Reduce form of
244
+ kernel == stride was 2x slower (AveragePool 2x2/2: 1.38 ms before, 0.70 now). Global pools reshape to [N, H*W, C] before the Reduce
245
+ (0.050 -> 0.036 ms in isolation).
246
+ - GridSample: 2-8 channels per thread with one grid read and one set of taps per thread (0.76 ms before, 0.30 now, 1.6x faster than
247
+ TensorRT's GridSample).
248
+
249
+ At batch 1 the plugins that reduce or sample per image are slower than TensorRT's op alone: InstanceNorm / GroupNorm (a block per image
250
+ and channel slice leaves most of the GPU idle at 3136 pixels: 0.04-0.05 vs 0.013 ms), GridSample (0.041 vs 0.013 ms), the depthwise
251
+ plugin on some shapes (too few tiles to fill the GPU); they still beat "original + T" except GridSample (and GlobalAveragePool,
252
+ 0.017 vs 0.013 ms). Batch-1 times of 0.01-0.06 ms
253
+ move by 30-50% between runs. TensorRT's own ROIAlign plugin (original RoiAlign column) does not match onnxruntime here (3.6e-1 error).
254
+
255
+ ## Tests
256
+
257
+ `python -m pytest -q tests`: every lowering against onnxruntime (FP32 tight, FP16 loose) with NHWC graph I/O, INT8 depthwise I/O, plus
258
+ ConvNeXt-atto, ResNet18, MobileNetV3 and a 1D ConvNeXt-style TCN exported from PyTorch (random weights) rewritten with the original I/O,
259
+ flat (opt level 3 and 5) and `--no-flat`, and a dynamic-H/W graph where flat falls back to 4D.
260
+
261
+ ## License
262
+
263
+ Apache-2.0, see [LICENSE](LICENSE).
264
+
265
+ ## AI Disclosure
266
+
267
+ Written with Claude Code (Anthropic); design decisions and review by the author.