Repository navigation
feat(dynamo): convert stable sort of index tensors with a counting sort - #5020
Open
shoumikhin wants to merge 3 commits into
Open
shoumikhin wants to merge 3 commits into
shoumikhin wants to merge 3 commits into
Conversation
shoumikhin
force-pushed
the
counting-sort-index
branch
from
November 14, 2026 17:15
e087d89 to
ea3372e
Compare
shoumikhin
added a commit
to shoumikhin/TensorRT
that referenced
this pull request
Nov 15, 2026
…5021 on main Brings the grouped GEMM kernel on this branch to the current version of pytorch#5021 on main. The kernel is opt-in through a grouped_mm_kernel setting (default False). It declines, with one warning that names the reason, when Triton, the driver's PTX limit, the GPU, hardware compatibility or Windows cross-compilation rule it out. A build failure is cached and logged once. Rows are masked so invalid offsets, past mat1 or negative, never read or write outside mat1 or the output. The dense converter's warning suggests the setting only when it is off and the kernel would likely take the op, checked without starting Triton. The tests are the same as on main, including engine-only exports run in a fresh process that loads only TensorRT and PyTorch, and a .pte run by the ExecuTorch runtime. It adapts to the release branch's kernel helpers. The plugin launch is still built in the kernel module, since this branch has no _common.make_pointer_aot_fn. The 48 KiB shared memory limit is a named constant in kernels/_common.py, used by the triton_op check, its error message and this kernel, as on main. compile_triton_to_ptx here hints every pointer as 16-byte aligned; it gets an optional per-pointer pointer_alignment, with the old behaviour as the default, so the kernel can leave the offsets unhinted as it does on main. This branch is release/2.15 (5aca374) with these release/2.15 ports of pull requests on main, oldest first: - pytorch#5014: fix(conversion): leave large aten._grouped_mm to PyTorch instead of the dense lowering - pytorch#5016: fix(kernels): reject AOT kernels that need more than 48 KiB of shared memory - pytorch#5017: fix(kernels): give triton_op kernels Triton's pointer alignment hint - pytorch#5021: feat(conversion): run aten._grouped_mm in TensorRT with a grouped GEMM kernel - pytorch#5021: fix(conversion): build the grouped GEMM plugin launch directly on release/2.15 - pytorch#5020: feat(dynamo): convert stable sort of index tensors with a counting sort - pytorch#5020: fix(dynamo): counting sort: add the key count to the engine cache key, convert single rows only - pytorch#5019: fix(dynamo): keep a select of a uint8 tensor inside the TensorRT engine - pytorch#5022: fix(dynamo): keep a cast to uint8 inside the TensorRT engine - pytorch#5023: Compute antialiased resize weights like PyTorch's CUDA kernel - pytorch#5024: Convert antialiased bilinear resize by default - pytorch#5021: fix(conversion): compile the grouped GEMM kernel without tensor memory on sm_100 and newer - pytorch#5015: fix(dynamo): release weights before serializing the engine, not after - pytorch#5021: feat(conversion): make the grouped GEMM kernel opt-in, as in pytorch#5021 on main Signed-off-by: Anthony Shoumikhin <[email protected]>
shoumikhin
added a commit
to shoumikhin/TensorRT
that referenced
this pull request
Nov 15, 2026
…5021 on main Brings the grouped GEMM kernel on this branch to the current version of pytorch#5021 on main. The kernel is opt-in through a grouped_mm_kernel setting (default False). It declines, with one warning that names the reason, when Triton, the driver's PTX limit, the GPU, hardware compatibility or Windows cross-compilation rule it out. A build failure is cached and logged once. Rows are masked so invalid offsets, past mat1 or negative, never read or write outside mat1 or the output. The dense converter's warning suggests the setting only when it is off and the kernel would likely take the op, checked without starting Triton. The tests are the same as on main, including engine-only exports run in a fresh process that loads only TensorRT and PyTorch, and a .pte run by the ExecuTorch runtime. It adapts to the release branch's kernel helpers. The plugin launch is still built in the kernel module, since this branch has no _common.make_pointer_aot_fn. The 48 KiB shared memory limit is a named constant in kernels/_common.py, used by the triton_op check, its error message and this kernel, as on main. compile_triton_to_ptx here hints every pointer as 16-byte aligned; it gets an optional per-pointer pointer_alignment, with the old behaviour as the default, so the kernel can leave the offsets unhinted as it does on main. This branch is release/2.15 (5aca374) with these release/2.15 ports of pull requests on main, oldest first: - pytorch#5014: fix(conversion): leave large aten._grouped_mm to PyTorch instead of the dense lowering - pytorch#5016: fix(kernels): reject AOT kernels that need more than 48 KiB of shared memory - pytorch#5017: fix(kernels): give triton_op kernels Triton's pointer alignment hint - pytorch#5021: feat(conversion): run aten._grouped_mm in TensorRT with a grouped GEMM kernel - pytorch#5021: fix(conversion): build the grouped GEMM plugin launch directly on release/2.15 - pytorch#5020: feat(dynamo): convert stable sort of index tensors with a counting sort - pytorch#5020: fix(dynamo): counting sort: add the key count to the engine cache key, convert single rows only - pytorch#5019: fix(dynamo): keep a select of a uint8 tensor inside the TensorRT engine - pytorch#5022: fix(dynamo): keep a cast to uint8 inside the TensorRT engine - pytorch#5023: Compute antialiased resize weights like PyTorch's CUDA kernel - pytorch#5024: Convert antialiased bilinear resize by default - pytorch#5021: fix(conversion): compile the grouped GEMM kernel without tensor memory on sm_100 and newer - pytorch#5015: fix(dynamo): release weights before serializing the engine, not after - pytorch#5021: feat(conversion): make the grouped GEMM kernel opt-in, as in pytorch#5021 on main Signed-off-by: Anthony Shoumikhin <[email protected]>
shoumikhin
force-pushed
the
counting-sort-index
branch
6 times, most recently
from
November 22, 2026 01:07
e956695 to
d72fbe7
Compare
shoumikhin
force-pushed
the
counting-sort-index
branch
3 times, most recently
from
November 25, 2026 16:11
27ae3d1 to
684deb1
Compare
A stable sort always ran in PyTorch. aten.sort.stable had no converter, and the TopK layer that converts aten.sort.default sorts at most 3840 elements and does not promise to keep equal keys in input order. Mixture-of-experts routing hits this in every layer: it sorts the expert ids that topk returns (argsort(stable=True)) to group tokens by expert. The fallback splits the engine around each sort. Those keys are indices into a dimension of known size, so a counting sort is exact: an element goes to the number of smaller keys plus the number of equal keys before it. The converter counts keys per tile of 128 elements with a float16 product with a lower triangle of ones (exact, since every count is at most 128), adds the counts of earlier tiles and of smaller keys, gathers each element's count at its own key, and scatters the indices to those positions. A static length that is a whole number of tiles is not padded. Keys are clamped into their range first: a key outside the range would give two elements the same position, so the result would not be a permutation. A new pass, annotate_sort_num_keys, finds the key range in post_lowering, after every other pass and after the fake tensor refresh: it walks back from the sort input through ops that only move values or cast them to int32 or int64 to the indices output of topk, or to argmax or argmin, and records the size of that dimension in node.meta. It reads that size from the shapes the refresh updated, so it records nothing when there is no fake mode, when a pass returned a new module, which the refresh does not update, or when a pass replaced a module attribute with one of another shape, which the refresh does not see, so it compares the shape of each attribute with its shape before the passes and with its meta. The default complex number lowering on torch 2.14 and newer returns a new module, so there a graph with complex numbers keeps the sort in PyTorch. The validator and the converter read the range from node.meta, and the engine cache key includes it, since the engine depends on it. The range is proven for the shapes seen at compile time. Keys made in PyTorch would come from whatever the caller passes, so the validator also needs the topk, argmax or argmin, and every op between it and the sort, to convert. The validator runs again on the TensorRT subgraph, where a producer left out of the engine is a placeholder, so such a sort fails to convert rather than sort wrongly. With resource partitioning, which splits engines after this check, the sort stays in PyTorch. The validator needs TensorRT 10.8 or newer, which has a cumulative layer, and keeps the sort in PyTorch on TensorRT-RTX, where the converter has not run. It takes int32 and int64 keys in a single row that is not empty, since the converter flattens its input into one row. It needs at most 2**20 counts (padded length times key values): each count holds about 5.5 bytes of device memory for the life of the engine, on top of its other activations, and a dynamic length counts at its upper bound, so the cap keeps the sort's own tensors under about 6 MiB, which a small device can afford in every mixture-of-experts layer. That also means at most 2**13 key values. With a dynamic length, the engine that takes in the sort can also plan more memory for the ops around it, which grows with the length and their sizes, not with the counts. It also needs at most 2**14 elements: in a routing layer measured on A100, rows of 2**15 elements or more could make the engine slower than a sort in PyTorch with the split, because TensorRT fuses the gathers that read the order less well. Within both caps the counting sort saved 0.16 to 0.5 ms per layer in every measured case. For top-8 routing, the caps cover up to 2048 tokens with 64 experts, 1024 with 128 and 512 with 256, and for top-2 routing over at most 64 experts up to 8192 tokens: decode and short prefill. Longer prefill keeps the sort in PyTorch. Each refusal is logged at debug level with its own reason. Signed-off-by: Anthony Shoumikhin <[email protected]>
…om its keys The stable sort converter trusts the key range only when the topk, argmax or argmin that makes the keys runs in the same engine, but the validator only checked that this op has a converter. A partitioner can still put the two in different engines. The global partitioner does it when an op that runs in PyTorch reads the keys and feeds an op after the sort, since one engine for both would need a cycle through that op. The fast partitioner does it when it refuses the op that makes the keys for a reason the converter registry does not check, such as a rank above 8. The hierarchical partitioner does it when a backend of higher priority takes that op. The validator then refused the sort again when converting its engine, where the keys are an engine input, and the whole compile failed. Before this converter existed, that sort ran in PyTorch. Now the fast, global and hierarchical partitioners check the TensorRT engines they propose. When the ops from a sort back to the op that makes its keys are not all in the engine of the sort, they drop the key range of that sort, so the validator refuses it, and propose again. The sort runs outside TensorRT, as before. The step that recomputes values made only from graph inputs in each later engine no longer copies a converted sort, since the copy could be cut off from the op that makes its keys. The later engine reads the order instead. The walk from a sort back to the op that makes its keys is now one function, key_chain, used by the annotation pass, the validator and the partitioners, so they cannot accept different chains. The validator tests reset the converter registry first, since it keeps the torch_executed_ops of the last compile in the process. Signed-off-by: Anthony Shoumikhin <[email protected]>
A converted stable sort now always gets its keys from a topk, argmax or argmin in the same engine, so its key range is the size of a dim of the input of that op. The hashed graph, the weight shapes and the input shapes already fix it. Remove the special case for it from the engine cache and its test. Signed-off-by: Anthony Shoumikhin <[email protected]>
shoumikhin
force-pushed
the
counting-sort-index
branch
from
November 26, 2026 00:11
684deb1 to
c2449e1
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What is wrong today
A stable sort (
x.argsort(stable=True)) always runs in PyTorch:aten.sort.stablehas no converter, and the TopK layer sorts at most 3840 elements and is not stable.Mixture-of-experts (MoE) routing sorts the expert ids from
topk, so the engine splits in every MoE layer:What this change does
These keys are positions along a dimension of known size, so a counting sort is exact and stable.
annotate_sort_num_keys. After lowering, it walks back from the sort to the indices oftopk,argmaxorargminand stores that dimension's size innode.meta. It stores nothing when those shapes may be out of date: a pass returned a new module (the default complex number lowering on torch 2.14 and newer does, so graphs with complex numbers keep the sort in PyTorch) or replaced a weight with one of another shape.Results
A routing layer (router, top-k, sort, gather, weighted
index_add), float16, A100:With a dynamic token count, extra memory depends on what shares the sort's engine: 0 to 2 MiB when the experts run in PyTorch (as
_grouped_mmdoes with dynamic shapes), up to 108 MiB when the whole layer is one engine (hidden size 7168, 2048 tokens).torch_executed_ops={"torch.ops.aten.sort.stable"}keeps the sort in PyTorch.Tests
Exact results for partial and whole tiles, descending keys, other dims and the largest accepted sorts; each key range source and each cap; keys made in PyTorch; splits by each partitioner; passes that return a new module or replace a weight; a dynamic length.