This work provides operator-specific workspace estimation for the CUDA Attention family. It defines how an
Attention kernel derives a workspace recipe from a plain problem description and a selected backend.
The generic memory-estimation framework is a separate work track. PA and PMHA now use its Level-1 and Level-2
declaration points, but partition budgeting, memory planning, and planned-root or preallocation integration remain
outside this operator-specific work.
Related design and rollout:
The Attention work owns:
CUDA EP assignment happens during session initialization. Backend dispatch inside an assigned CUDA Attention kernel
can happen later, using the concrete inputs available to Compute(). These are distinct decisions.
Runtime sizing can be exact because the kernel first selects a backend and then requests that backend's recipe:
concrete inputs -> runtime dispatch -> selected backend -> exact workspace recipe
Ahead-of-time (AOT) estimation cannot assume that the same selection is known. Backend reachability can depend on
optional inputs, build and runtime options, cache state, runner availability, device properties, and concrete dynamic
sequence lengths. When the exact backend cannot be proven, AOT estimation must enumerate the reachable backend recipes
and take a safe upper bound:
shapes and bounds -> reachable backends -> recipe per backend -> maximum workspace
An estimator must not copy the runtime dispatch cascade or assume that dispatch is monotonic with shape. For example,
a larger shape may use a fused backend with small workspace while a nearby smaller shape falls back to an unfused
backend with an S^2 attention buffer. Head eligibility is also non-monotonic: a componentwise upper bound can exceed
a backend's supported head range while a smaller runtime head remains supported, and equal-head routes can be reachable
under unequal Q/K and V bounds. Each route reachable at a positive runtime geometry within the bounds must therefore be
sized using the original componentwise maximum geometry, whose current workspace terms are monotonic. PA'sqkv_hidden_sizes values are immutable node attributes, not shape bounds, so their derived head sizes retain exact
runtime eligibility checks. Only PA geometry derived without that attribute and PMHA geometry supplied throughWorkspaceInputShape use bounded head reachability.
An AOT result should therefore be classified as:
The reusable implementation follows this boundary:
operator shapes and attributes
|
v
plain Attention problem
|
v
checked backend/layout recipe
|
v
runtime allocation and workspace views
The plain problem and recipe must not depend on Node, NodeArg, GraphViewer, TensorShape, or CUDA runtime types.
A future framework adapter may translate framework inputs into the plain problem, but it must not duplicate sizing or
validation arithmetic.
Recipes must use checked arithmetic, enforce relevant CUDA ABI and grid limits, and prove that every derived view is
contained in the allocated workspace.
microsoft/onnxruntime#32283 is the first implementation in the
roadmap tracked by microsoft/onnxruntime#29775. Its scope isPackedAttention (PA) and PackedMultiHeadAttention (PMHA), plus a shared correction that widens CUTLASS MEA
attention-bias stride arithmetic for all MEA consumers.
PR1 establishes a single sizing and layout source of truth while preserving legacy workspace byte totals, allocation
counts, and allocation lifetimes. It does not change Attention backend selection. The shared stride correction can
change MEA's internal aligned-versus-unaligned kernel variant only in cases where the previous int32 calculation
overflowed before assignment to an int64 stride.
T and B * ST is the packed real-token count. B * S is padded capacity. Existing packed Attention paths use both:
T;B * S; andB * S attention allocation total even when a fused inner view uses T.Shrinking the total allocation from B * S to T is a separate optimization.
PA has a projection GEMM allocation and an Attention allocation. The recipe reports them separately; their sum must
not replace either allocation. PMHA receives Q/K/V inputs and has zero projection workspace.
| Backend | Q/K/V representation | Q/K/V view dimension | Backend scratch retained by PR1 |
|---|---|---|---|
| Flash | Planar materialized views or direct input views | T |
Softmax LSE: sizeof(float) * B * S * N |
TensorRT fused (FusedRunner) |
Interleaved [T, N, 3, H] |
T |
None |
| Memory-efficient Attention | Planar materialized views or direct input views | T |
Optional FP32 accumulator: sizeof(float) * B * S * N * H_v |
Unfused (Default) |
Planar [B, N, S, H] views |
B * S |
Two individually aligned element_size * B * N * S * S regions |
The MEA accumulator is needed when H_v > 128 and the input element size is smaller than FP32. PA does not dispatch
to Flash and always materializes Q/K/V after its projection GEMM. PMHA can skip materialization for packed[T, N, 3, H] input on TensorRT when bias is absent, or for separate Q/K/V input on Flash or MEA when bias is absent.
PR1 includes:
PR1 validates token-offset and cumulative-sequence tensor shapes and host-visible geometry. It does not inspect or
synchronize their device contents. Device-value validation requires a separate CUDA graph- and capture-safe contract.
PR1 does not:
B * S total to T;PR1 precedes the sequence below and establishes the checked-recipe architecture that later families can reuse.
The planned operator-specific sequence is:
MultiHeadAttention.GroupQueryAttention.PagedAttention.The first GroupQueryAttention backend follow-up adds graph-free, checked
recipes for two concrete selected backends:
GetXQAScratchSize. Its backend allocation alsoFlash split selection is discontinuous and concrete workspace is not monotonic
in KV length. For example, with B=1, S_q=1, two heads, head size 64, and
108 SMs, increasing KV length from 13,824 to 13,825 changes the selected split
count from 54 to 28 and reduces the concrete split workspace. A future bounded
aggregate must therefore compute a conservative envelope over the bounded
domain or report unavailable; evaluating only the componentwise maximum is not
safe.
The stacked route-composition follow-up adds the remaining selected backends:
A complete concrete route places its preparation regions once, then places the
selected backend's simultaneously-live allocation regions at checked
256-byte-aligned offsets. This does not change runtime allocation topology and
does not select or aggregate routes. cuDNN is explicitly unavailable because a
graph-free recipe must not query or build a cuDNN graph.
When exactly one past/present K/V pair aliases, non-windowed GQA preserves the
aliased past tensor in a separate scratch allocation before preprocessing
overwrites the present cache. The workspace problem records that asymmetric
alias fact and the past-cache capacity, and the preparation recipe includes the
checked preservation region. Windowed execution, XQA, and Flash fast decode
require both K/V pairs to alias and reject this state.
The GQA framework follow-up translates positional inputs and immutable kernel
attributes into a graph-free bounded domain. It covers packed and separate
Q/K/V, optional past-cache pairs, cache quantization, prompt and decode states,
windowed staging and compaction, XQA (including unresolved shared-memory
fallback), regular and fast-decode Flash, MEA, unfused, and cuDNN reachability.
Head geometry derived from WorkspaceInputShape is an upper bound: route
reachability searches supported smaller head sizes instead of testing only the
componentwise maximum.
Flash split selection is not monotonic in KV length. The bounded estimator uses
the runtime block size (256 for head size at most 64, 128 through 128, and64 above 128) and bounds the selected split count by:
min(128, SM count, ceil(KV length bound / block size))
It then sizes the split accumulators at that envelope. Complete routes are
mutually exclusive and are aggregated with max, not sum. The resulting
nonzero estimate is one operator-owned slot-0 root with 256-byte alignment.
Level 1 reports it as runtime_workspace_bytes; Level 2 declares one root from
the same estimator. Level 1 conservatively includes dynamic head-sink conversion
because prepack state is unavailable during capability analysis. For a constant
head sink, it separately charges the possible session-lived FP32 copy and the
initialization-only device staging copy, even when session configuration later
disables prepacking. Level 2 can omit the transient conversion region when the
constructed kernel has a prepacked head sink, so its root can be smaller.
Neither adapter changes runtimeGetScratchBuffer() calls or allocation topology.
The CPU total_sequence_length scalar and past/present aliasing are not
available through WorkspaceInputShape. For non-windowed GQA, the scalar can
exceed the past-cache sequence dimension and directly scale Flash, MEA, and
unfused workspace. Non-windowed execution can also preserve one full past
tensor when exactly one past/present pair aliases. The current adapter therefore
reports non-windowed GQA as unavailable rather than treating the past shape as
a total-KV bound or omitting alias-preservation scratch.
Successful estimates are currently limited to sliding-window cache nodes.
Their final cache capacity remains C, while a multi-token step uses a
transient staged/effective attention extent of C + S; a single-token step
uses C. This shape-only bound remains sound even when the scalartotal_sequence_length is much larger. Runtime requires both past/present
pairs to alias before staging or compaction, excluding the partial-alias
preservation path. Sliding-window attention bias remains
unsupported by runtime and is also unavailable to the estimator. If cuDNN can
be reached anywhere in a graph-free bounded domain, aggregation remains
unavailable because cuDNN's allocator-based workspace has no sound graph-free
oracle. Level 1 then uses the generic fallback and Level 2 emits no requirement.
Unlike the log-only PA/PMHA Level-1 probe, a successful GQA Level-1 estimate is
passed to the #31962 resource accountant as runtime_workspace_bytes and can
affect CUDA partition acceptance.
MHA and GQA are high-value coverage targets and have high estimation-drift risk. Their runtime behavior can include
dynamic internal backend dispatch, cache lifecycle and aliasing, optional inputs, non-monotonic fallback paths, and
unfused workspace governed by S_q * S_kv_total. GQA additionally has different Q and KV head counts. MHA can have
different query and total-KV sequence lengths or different Q/K and V head sizes. Shared backend kernels do not
eliminate operator-specific preparation, cache, transpose, grouping, or output workspace.
Paged, Linear, Sparse, and Longformer Attention require distinct memory models. They must not be forced into a dense
Attention formula solely because they share some backend infrastructure.
Each Attention family must provide:
This document defines operator-estimation work tracks and invariants. It does not prescribe a public framework API.
The PA/PMHA follow-up connects the graph-free recipes to the current Phase-A framework:
GetCapability() translates positional node inputs, uses max-shape inference when availableWorkspaceInputShape entries and declare nonzero workspaceWorkspaceInputShape does not identify whether a shape came from concrete graph metadata orRoute aggregation does not evaluate the runtime cascade only at the supplied maximum sequence length: dispatch gates
such as Flash and FP32 MEA thresholds or attention-bias alignment are non-monotonic across smaller runtime shapes.
Every backend that can be reached for some valid shape up to the supplied geometry is sized at that maximum geometry.
Unfused is always retained as a possible fallback for a nonempty problem, including alongside Flash, MEA, and
TensorRT candidates. Bound aggregates deliberately bypass exact equal-head recipe gates because an equal-head route
can be reachable below unequal maximum bounds; the recipe is still checked at those original maximum bounds. If a
newly reachable route's max-geometry recipe is invalid, or any included route otherwise cannot be safely bounded,
estimation is unavailable rather than silently omitting the route. Mutually exclusive route workspaces are combined
with max, never sum. The Level-1 aggregate describes one 256-byte-aligned, operator-owned root. PA places its
simultaneously-live projection and Attention regions in that root; PMHA naturally has only the Attention region:
PA attention offset = align_up(projection bytes, 256)
PA root bytes = attention offset + max(reachable attention routes)
PMHA attention offset = 0
PMHA root bytes = max(reachable attention routes)
The PA alignment gap is intentional, so its root can be up to 255 bytes larger than the unaligned sum. Level 2 emits
exactly one slot-0 requirement for either operator, with explicit alignment_bytes=256. This does not depend on the
framework's generic multi-slot capability.
Runtime allocation topology is unchanged: PA continues to make separate dynamic projection and AttentionGetScratchBuffer() allocations, and PMHA continues to dynamically allocate its Attention workspace. Future #32071
integration must atomically add the explicit SupportsPreallocatedWorkspace() planner opt-in, retrieve the planned
root, and slice it at the declared Attention offset. A declaration alone is not planner opt-in and does not itself
change runtime allocation behavior.