Skip to content

Add quantized KV attention primitives - #25033

Open
xingguo01 wants to merge 1 commit into
pytorch:mainfrom
xingguo01:arm-quantized-kv-attention-primitives
Open

xingguo01 wants to merge 1 commit into
pytorch:mainfrom
xingguo01:arm-quantized-kv-attention-primitives

Conversation

@xingguo01

@xingguo01 xingguo01 commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Configure native SDPA through quantizer annotations and decomposition provenance instead of requiring model-specific attention arithmetic. Support A16 attention and experimental A8 QK/AV, deriving INT32 QK scales from symmetric operands and retaining A16 masked softmax.

Keep calibrated integer cache storage separate from attention policy. Retain the experimental Vela-specific INT16 variable path without a model-specific SDPA source transform. Cover quantizer selection, masks, GQA, accumulator bounds, and delegated mutable-buffer ownership.

AI-assisted-by: Codex

cc @digantdesai @freddan80 @per @zingo @oscarandersson8218 @mansnils @Sebastian-Larsson @robell @rascani

@pytorch-bot

pytorch-bot Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25033

Note: Links to docs will display an error until the docs builds have been completed.

❌ 2 New Failures, 5 Pending, 2 Unrelated Failures, 1 Unclassified Failure

As of commit 1f4b7fd with merge base 765e973 (image):

NEW FAILURES - The following jobs have failed:

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 13, 2026
@github-actions github-actions Bot added ciflow/trunk module: arm Issues related to arm backend labels Nov 13, 2026
@xingguo01 xingguo01 added release notes: arm Changes to the ARM backend delegate help wanted Extra attention is needed labels Nov 13, 2026
@digantdesai

Copy link
Copy Markdown
Contributor

@claude review this pr. effort:max

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Claude finished @digantdesai's task in 4m 37s —— View job


No blockers, but the A8 attention policy only exists as a test helper whose behaviour depends on call order. The new output_activation factory contract also fails on existing no-node callers, and the INT16 cache path promised in the description is never lowered in a test.

Detailed review

PR Review: #25033

Summary

The PR adds SDPA node finders and a derived INT32 QK accumulator qspec so native SDPA can be quantized as A16 or A8, and adds INT16 storage to StaticQuantizedKVCache. The QK accumulator maths checks out: scale is q_scale * k_scale, zero point is 0, operands with non-zero zero points are rejected, and the overflow bound is checked. The problems are an undocumented API contract, matching that can fail loudly or quietly, and gaps in test coverage.

API Design

  • The A8 policy is only built in a test helper, and the order of calls matters (backends/arm/test/quantizer/test_sdpa_quantization.py:64-83). Getting A8 QK, A16 softmax and an INT32 accumulator takes three set_node_finder calls in this order: SDPAFinder, then SDPAScoreFinder, then SDPAMatmulFinder("qk"). That works only because add_quantizer does insert(0) (arm_quantizer.py:1417), so the last call wins. The caller must also replace(...) the input qspec with per_tensor_symmetric and pass the same spec to the partial(get_int8_matmul_accumulator_qspec, input_qspec=...) factory.
    • Nothing checks that input_qspec matches the config's input_activation. If they differ, the INT32 overflow check no longer protects anything.
    • The PR description says users can configure SDPA through quantizer annotations, but users have no public helper or documented recipe to do it.
    • Suggestion: expose a helper such as configure_sdpa_quantization(quantizer, config) from backends/arm/quantizer, and derive the accumulator's input_qspec from the config itself.
  • A callable output_activation is a new public contract that existing callers can't use (quantization_config.py:224-227).
    • Without a node it raises "Output activation factory requires a node". Several existing paths still call get_output_act_qspec() with no node: CortexMQuantizationConfig.get_output_act_qspec (backends/cortex_m/quantizer/quantization_configs.py:161,165,170) and pattern_checkers.py:58,90,183,375.
    • get_int8_matmul_accumulator_qspec raises on any node that isn't a matmul.
    • When a factory is set, TOSAQuantizationConfig.get_output_act_qspec skips every TOSA-specific rule: fixed-output ops, to.dtype, and the shared qspecs for pooling and upsample (quantization_config.py:509).
    • Net effect: a factory config is safe only when it is scoped to a finder that returns nothing but matmuls, and the docstring doesn't say so.
    • quantization_annotator.py:691-696 also decides whether to pass node by checking the field's runtime type (callable(output_activation)). It would be simpler to always pass node, as get_bias_qspec(node) already does two lines below.

Backward Compatibility

  • A shared transform changes behaviour for other backends (backends/transforms/decompose_sdpa.py:145-149). This pass is also used by Qualcomm (qnn_pass_manager.py:192,230) and Samsung (enn_pass_manager.py:53).
    • source_fn_stack now keeps the outer stack and adds a synthetic (node.name, sdpa) entry. The first element is now a str instead of a Node.
    • [-1] is unchanged, so get_source_partitions should behave the same, and I found no consumer in those backends that breaks.
    • The new metadata contract that the finders rely on isn't pinned in backends/transforms/test/test_decompose_sdpa.py.

Code Quality

  • SDPAMatmulFinder can fail loudly or quietly (backends/cortex_m/quantizer/node_finders.py:274-287).
    • Loud: if a group doesn't contain exactly 2 bmm/matmul nodes, it raises ValueError, which aborts quantization of the whole model instead of skipping that SDPA call. This can happen with a different decomposition table, or a later pass that copies SDPA meta onto a new matmul (ArmPass.call_operator copies meta).
    • Quiet: a group that still holds an undecomposed aten.scaled_dot_product_attention is skipped with no message. For example, DecomposeScaledDotProductAttentionPass.allowed_to_transform returns False. The user who asked for A8 QK then silently gets the SDPAFinder config.
    • SDPAScoreFinder builds SDPAMatmulFinder("qk") internally, so a score-only policy inherits both behaviours.
    • Consider logging a warning and skipping in both cases.
  • Another decomposition pass still drops SDPA provenance (backends/arm/_passes/get_decomposition_pass.py:138, not changed here). It still overwrites source_fn_stack with [(subgraph_node, target)]. Any SDPA child decomposed through it after SDPA decomposition will drop out of SDPAFinder/SDPAScoreFinder without warning. Low confidence: I didn't confirm which ops inside the SDPA decomposition go through this pass.
  • The INT16 cache keeps a default scale meant for INT8 (custom_kv_cache.py:265,474,553). scale still defaults to 1/127. With quantized_cache_dtype=torch.int16 and no calibration, that gives the INT8 step size over a range of about ±258: twice the storage for no precision gain. Either derive the default from iinfo(dtype).max or require an explicit scale for INT16. The tests always pass 1/32767 by hand, so they don't catch this.
  • quantization_config.py:621: int(lhs.meta["val"].shape[-1]) specializes or fails when the reduction dim is symbolic, and raises KeyError when val is missing. A clearer error would help.
  • custom_kv_cache.py:289: observed_shape = scale_shape is an alias that does nothing, and the register_buffer reformatting at lines 300-307 is unrelated churn.

Testing

  • The "experimental Vela-specific INT16 variable path" from the description is never lowered.
    • test_attention_quantization_preserves_delegated_int8_variable_cache only asserts torch.int8 buffers and INT8 TOSA variables.
    • The INT16 cache is tested only in eager mode in the llama tests, with use_custom_update_cache_op=False.
    • No caller in the repo passes quantized_cache_dtype: neither export_llama_lib.py nor backends/arm/test/models/test_llama.py.
  • test_replace_static_quantized_cache_preserves_sdpa can't fail (examples/models/llama/tests/test_replace_kv_cache.py:430-442). replace_kv_cache_with_static_quantized_kv_cache never touches attention.SDPA, so assertIs(attention.SDPA, original_sdpa) always passes.
  • test_attention_policy_does_not_change_mutable_cache_storage_dtype doesn't test what its name says (test_sdpa_quantization.py:238-258). It swaps in a float KVCache and then asserts the float buffers stay float. PT2E never retypes buffers, so this passes whatever the attention policy does.
  • No negative or precision checks in the llama tests:
    • Nothing covers the new ValueError for an unsupported quantized_cache_dtype such as uint8 or float16.
    • The INT16 round-trip test uses atol=scales.max(), a full quantization step. Correct rounding guarantees half a step, so an off-by-one rounding bug would still pass.
  • Not registered in Buck: quantizer/test_sdpa_quantization.py and quantizer/test_quantization_config.py aren't in backends/arm/test/targets.bzl, while misc/test_delegated_state_partitioning.py is.
  • Strict export only: every end-to-end SDPA test uses strict=True. The grouping depends on source_fn_stack, which non-strict export (the default) fills in differently.

Recommendation

Request Changes

  1. Give the A8/A16 SDPA policy a public, documented entry point instead of a call-order-dependent test helper.
  2. Define the output_activation factory contract: always pass node, and handle or reject the no-node and non-matmul callers.
  3. Make SDPAMatmulFinder fail predictably instead of raising for the whole model or skipping silently.
  4. Fix the INT16 default scale, and either lower the INT16 cache through Ethos-U in a test or drop the claim from the description.
  5. Replace the two tests that can't fail.

@xingguo01
xingguo01 force-pushed the arm-quantized-kv-attention-primitives branch from ab23fc2 to 5a0ef12 Compare November 17, 2026 17:05
@xingguo01

Copy link
Copy Markdown
Collaborator Author

@claude Thanks for the detailed review. I’ve addressed the concrete issues: documented the node-finder recipe and precedence, clarified the output-qspec factory contract, strengthened accumulator validation, preserved decomposition provenance, corrected the dtype-dependent cache scale, and expanded tests and Buck registration. Coverage now includes non-strict export and INT16 persistent-variable lowering with a compatible Vela build.

A few design clarifications:

  • The production A8/A16 selection policy is in a later “Llama: Wire quantized KV attention to Ethos-U export” commit not on Github yet. This PR provides the reusable primitives and a documented recipe.
  • I retained the existing node-finder API rather than introducing another SDPA-specific configuration helper, following Adrian’s review direction.
  • Later-registration precedence is existing quantizer behavior and is now documented.
  • Output-qspec factories explicitly require a node and must be scoped to supported operators; ordinary qspec configurations retain no-node support.
  • Ambiguous QK/AV matching fails explicitly rather than silently skipping the requested precision.
  • The cache/attention separation tests were strengthened rather than removed, since that separation remains an important invariant.

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Claude finished @xingguo01's task in 5m 46s —— View job


Most of the first review is resolved. Three things remain: an SDPA role finder can still turn into a silent no-op, which the new docs say can't happen; the only real INT16 Vela lowering test is always skipped in CI; and a few tests are still weak.

Detailed review

PR Review: #25033 (re-review)

Summary

The PR adds SDPA node finders, an INT32 QK accumulator qspec factory and INT16 StaticQuantizedKVCache storage. This pass treats the design choices from the author's reply as settled: keeping the node-finder API, later registration taking precedence, factories that require a node, and failing on ambiguous QK/AV. The findings below are what is still left.

The diff was read from HEAD~1..HEAD because origin/main has no merge base in this shallow checkout. That range matches the PR's 17 files and +1678/-51 lines.

API Design

  • Role finders still skip native SDPA without telling anyone, which contradicts the new docs (backends/cortex_m/quantizer/node_finders.py:280-284).
    • The docs say "role finders reject ambiguous decompositions rather than silently selecting a different precision".
    • But when a group still contains an undecomposed aten.scaled_dot_product_attention, SDPAMatmulFinder("qk"/"av") hits continue and quietly selects nothing.
    • Trigger: _TOSAQuantizerV2.transform_for_annotation (arm_quantizer.py:1389-1411) annotates the native graph first. It marks every node no quantizer annotated with DISALLOW_TFA_META_KEY=True, and the SDPA decomposition then skips those nodes.
      • The role finders select nothing on a native graph: there are no matmuls yet, and the native op is not in softmax_targets.
      • So if a user registers SDPAMatmulFinder("qk") and/or SDPAScoreFinder() with no broad SDPAFinder() and no global config, SDPA is never decomposed. Their QK and score configs then do nothing, and nothing reports it.
      • Any other case where SDPA isn't decomposed ends the same way.
    • The documented recipe works only because it registers SDPAFinder() first, and the docs never say that step is required.
    • Fix: when self.role is set, raise here instead of continue. Alternatively, state in the docs that a broad SDPAFinder (or global) registration is required for decomposition.
    • Confidence: I confirmed the continue by reading the code. Two reviewers traced the TFA gating independently, but I did not run it.

Testing

  • The INT16 Vela persistent-variable lowering is always skipped in CI (backends/arm/test/quantizer/test_sdpa_quantization.py:300-307).
    • The int16-vela case skips unless vela --help lists --separate-persistent-region.
    • backends/arm/requirements-arm-ethos-u.txt:8 pins ethos-u-vela == 5.2.0, and backends/arm/ethosu/compile_spec.py:196 says that flag needs Vela 5.3 or later. So no CI job runs the "compatible Vela build" coverage mentioned in your reply.
    • The INT16 cases that do run stub vela_compile, so they only check TOSA variable dtypes.
    • The new test_int8_state_lowers_as_persistent_variable_u85_INT (test_delegated_state_partitioning.py:103) is INT8 only.
    • Suggestion: say this explicitly in the PR description, or mark the test with a visible xfail/skip reason tied to the Vela pin so it gets turned on when the pin moves.
  • The INT16 cache is only tested with use_custom_update_cache_op=False.
    • Every INT16 case in examples/models/llama/tests/test_replace_kv_cache.py (e.g. lines 166, 184, 219, 260) and in test_sdpa_quantization.py avoids torch.ops.llama.update_cache.
    • The default for both StaticQuantizedKVCache and replace_kv_cache_with_static_quantized_kv_cache is True, so INT16 storage on the default path is never run.
    • Low confidence: the op looks dtype-generic (it copies by element_size), but no test confirms it.
  • The "disabled" case in test_sdpa_policy_is_opt_in_and_preserves_unrelated_matmul can't tell an override from a missing decomposition (test_sdpa_quantization.py:103-116).
    • "default" and "disabled" make the same assertion: zero SDPA matmuls.
    • That passes whether set_node_finder(None, SDPAFinder()) really overrode the earlier registrations, or SDPA simply never got decomposed.
    • Suggestion: assert that no quantize/dequantize nodes surround the SDPA region.

Code Quality

  • A score-only policy fails because of a QK/AV problem it didn't ask about (node_finders.py:309).
    • SDPAScoreFinder.find_nodes always calls SDPAMatmulFinder("qk"), which raises "Cannot identify QK and AV in SDPA decomposition" for any group that doesn't have exactly two matmuls.
    • So registering only the A16 softmax policy fails on such a group, and the error names a role the user never configured.
    • Fix: catch the error and re-raise it with score-finder context, or have the score region not depend on QK classification when no QK policy is registered.
  • SDPAFinder._groups mixes two kinds of key (node_finders.py:213-226), so groups could merge (low confidence, not reproduced).
    • Native nodes are keyed by their live node.name, while decomposed nodes are keyed by the name frozen in source_fn_stack.
    • If a native SDPA's current name ever matches a stale provenance name (after a retrace or re-export), the two groups merge. That would trigger the QK/AV error, or the silent native-skip described under API Design.
    • Keeping the two kinds of key in separate namespaces would rule this out.
  • The log shows scale=None and leaves out the dtype (examples/models/llama/source_transformation/custom_kv_cache.py:562-568). replace_kv_cache_with_static_quantized_kv_cache logs the raw scale argument before the dtype-dependent default is resolved, and doesn't log quantized_cache_dtype at all.

Recommendation

Request Changes

  1. Make role finders raise instead of continue on undecomposed SDPA, or document that a broad SDPAFinder registration is required.
  2. Make the CI gap on the INT16 Vela path visible.

The rest is minor.

@xingguo01
xingguo01 force-pushed the arm-quantized-kv-attention-primitives branch from 5a0ef12 to f41f05c Compare November 19, 2026 16:26
@xingguo01

Copy link
Copy Markdown
Collaborator Author

@claude Thanks for the follow-up. Updated the implementation, documentation and tests:

  • Native SDPA: documented that role finders select decomposed nodes; a quantized SDPAFinder() or global policy must enable decomposition first. Added strict/non-strict regressions for role-only registration.
  • Vela coverage: explicitly documented the repository’s 5.2.0 pin and its coverage limitation. The real INT16 persistent-region compilation test reports that it requires Vela 5.3.0 or a compatible development build; TOSA-only checks are distinguished from actual compilation.
  • Default cache-update path: added INT16 custom-op versus tensor-update comparisons covering both quantization granularities, overwrite/append updates and values beyond the INT8 range.
  • Disabled policy: strengthened assertions to verify that no quantize/dequantize nodes remain, rather than relying only on matmul counts.
  • Score-finder errors: added score-region context when classification fails.
  • Grouping: separated native-node and decomposition-provenance key namespaces, with a collision regression.
  • Logging: now reports the storage dtype and resolved effective scale.
    For the earlier API points, I retained node-finder configuration and documented registration precedence and the node-aware factory contract. The production attention policy is supplied by the following Llama export commit, intentionally outside this primitives PR. Ambiguous decompositions still fail explicitly rather than silently changing precision.

INT16 default scales are dtype-dependent, accumulator validation checks actual input observers, and the provenance and cache-history tests have been strengthened.

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Claude finished @xingguo01's task in 5m 3s —— View job


Everything that was blocking in the last round is fixed, so I'd approve this. Five minor points remain; none block the merge. Points you already settled in your replies (keeping the node-finder API, the factory contract, the Cortex-M no-node callers, the Vela 5.2.0 pin, the source_fn_stack format) are not raised again.

Detailed review

PR Review: #25033 (second re-review)

Summary

The PR adds SDPA node finders, an INT32 QK accumulator qspec factory, and INT16 StaticQuantizedKVCache storage. I read the diff as HEAD~1..HEAD, because the shallow checkout has no merge base with origin/main; it matches the PR's 17 files and +1846/-53 lines. I did not run any tests.

API Design

  • The A8 snippet in the docs only works if you run the A16 snippet first (docs/source/backends/arm-ethos-u/arm-ethos-u-quantization.md, same text in the .md.in template).
    • The second block uses quantizer, SDPAFinder and get_symmetric_a16w8_quantization_config but never imports them. Run on its own, it fails with NameError.
    • Run after the first block, it registers a8 on top of the A16 SDPAFinder(). It only works because later registrations win, and the docs don't say the two blocks are meant to be combined.
    • Suggestion: make each snippet self-contained, so the A8 recipe builds its own quantizer and shows the full registration order.
    • The docs say role finders "reject ambiguous decompositions". They should also say that one ambiguous SDPA anywhere in the model stops quantization of the whole model. This applies to SDPAScoreFinder too, because it classifies QK internally.

Code Quality

  • The default scale is computed in two places (examples/models/llama/source_transformation/custom_kv_cache.py:562-564 and :276-277).
    • replace_kv_cache_with_static_quantized_kv_cache recomputes 1 / iinfo(dtype).max only to log it. If the rule in __init__ changes, the logged "effective" scale will stop matching the scale actually used.
    • For an unsupported dtype it logs scale=None, and only then does __init__ raise.
    • Suggestion: validate the dtype and resolve the default once, either in a shared place or by logging from the constructed cache.
  • Accumulator observer checks only run at convert time (backends/arm/quantizer/quantization_config.py:565-590).
    • The dtype, qscheme and dynamic checks on the actual input observers run inside derive_qparams_fn, which is first called during convert_pt2e.
    • Trigger: a later registration gives the QK operands an INT16 or affine spec. Prepare and calibration both succeed, and the error only appears at convert.
    • This is acceptable as a backstop, but the message could name the matmul node so the user can find the conflicting registration.
  • Group keys from two naming schemes can still collide (backends/cortex_m/quantizer/node_finders.py:219-224). Low confidence: two reviewers reasoned this out, nobody reproduced it.
    • Decomposed groups are keyed by ("decomposed", name), where name comes either from the FX aten node name (this PR's passes) or from the Dynamo source name (entries targeting F.scaled_dot_product_attention).
    • Trigger: one SDPA decomposed through each route ends up with the same name. The two groups merge, and SDPAMatmulFinder("qk") raises "Cannot identify QK and AV".
    • Fix: add target to the key. It costs almost nothing and removes the overlap.

Testing

  • The "disabled" case never runs with the A8 role finders registered (backends/arm/test/quantizer/test_sdpa_quantization.py:98-104).
    • policy == "disabled" goes through _configure_attention with the A16 config. That config registers only SDPAFinder() (lines 66-67), so it never tests whether set_node_finder(None, SDPAFinder()) also overrides earlier SDPAScoreFinder / SDPAMatmulFinder("qk") registrations.
    • Suggestion: add an A8-then-disabled variant.

Recommendation

Approve

Nothing blocks the merge. The doc snippet fix and the duplicated default scale are worth a quick follow-up.

@xingguo01
xingguo01 force-pushed the arm-quantized-kv-attention-primitives branch from f41f05c to 63d72e1 Compare November 19, 2026 17:08
@xingguo01

Copy link
Copy Markdown
Collaborator Author

@claude Thanks for the re-review. Addressed the remaining nits:

  • Made the A8 recipe self-contained and clarified that ambiguous role matching stops model quantization.
  • Removed duplicate default-scale calculation; logging now reports the constructed cache’s actual scale.
  • Included the matmul node name in accumulator-observer validation errors.
  • Added the provenance target to SDPA group keys, with a collision regression test.
  • Added A8-then-disabled coverage to verify that disabling overrides earlier role-specific registrations.

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Claude finished @xingguo01's task in 4m 17s —— View job


All five nits from the last round are fixed and nothing blocks the merge, so I'd approve this; four minor follow-ups remain, the most useful being a test that runs the A8 QK path on the TOSA reference model.

Detailed review

PR Review: #25033 (third re-review)

Summary

The PR adds SDPA node finders, an INT32 QK accumulator qspec factory, and INT16 StaticQuantizedKVCache storage. I read the diff as HEAD~1..HEAD because the shallow checkout has no merge base with origin/main, and I did not run any tests. Settled points are not raised again: the node-finder API, later registration winning, factories that require a node, failing on ambiguous QK/AV, the Vela 5.2.0 pin and the source_fn_stack format.

Testing

  • No test runs the A8 QK→softmax path through TOSA numerically (backends/arm/test/quantizer/test_sdpa_quantization.py).
    • The A8 accuracy checks (:172, :250) compare the converted PT2E model against eager, using fake-quant in Python.
    • The lowered test (:330-387) replaces vela_compile with a stub that returns b"test", then checks only the dtypes of the TOSA matmuls and variables.
    • So nothing runs the INT32 score tensor, the rescale into A16 and the masked softmax on a backend.
    • Trigger: a wrong rescale multiplier or shift in the lowering of the INT32 accumulator would pass every test.
    • Suggestion: add one A8 SDPA case through TosaPipelineINT with run_on_tosa_ref_model, named ..._tosa_INT so test_arm_baremetal.sh picks it up in the TOSA job.

Code Quality

  • The replacement log is now printed once per cache (examples/models/llama/source_transformation/custom_kv_cache.py:593-601). Two reviewers found this.
    • The "Replacing KVCache… modifies the model in place" message moved inside the recursive loop.
    • A 32-layer model now logs it 32 times, and a model with no matching caches logs nothing.
    • The message reports cache.k_cache_scale. With use_per_channel=True, that scalar is only the starting value, and the cache actually uses the k_cache_scales buffer.
    • Suggestion: log once in replace_kv_cache_with_static_quantized_kv_cache, using the first cache that was built, or move the per-layer line to DEBUG.
    • Fix this →
  • Errors raised by the factory still don't name the node (backends/arm/quantizer/quantization_config.py:618-650). The fix added node_name only to the observer errors in _derive_matmul_accumulator_qparams. The errors raised at annotation time still say only "INT8 accumulation requires a matmul node", "…tensor shape metadata", "…static reduction dimension" and "Matmul reduction can overflow INT32 accumulation". These are the ones a user hits first when a finder selects the wrong node or one layer has a large or symbolic reduction. Adding node.name to them works the same way.

Infrastructure

  • The Buck dependency is broader than the test needs (backends/arm/test/targets.bzl:214). test_sdpa_quantization.py only imports custom_kv_cache, but it depends on //executorch/examples/models/llama:source_transformation, which also pulls in quantize, spin_quant, lora and others. The narrower //executorch/examples/models/llama:custom_kv_cache target is defined at examples/models/llama/BUCK:222.

Recommendation

Approve

None of these block the merge. The TOSA reference-model case would give real coverage of the new A8 QK path, which today is only checked in eager mode and by dtype.

@xingguo01
xingguo01 force-pushed the arm-quantized-kv-attention-primitives branch from 63d72e1 to 1df6aa4 Compare November 19, 2026 20:24
@xingguo01

Copy link
Copy Markdown
Collaborator Author

@claude Thanks. Added a real TOSA reference-model regression covering INT8 QK, INT32 accumulation, the QK-specific INT16 rescale and masked attention outputs, compared against PT2E and eager.

Factory errors now include node names. Per-cache logging is DEBUG and identifies the initial scale. The Buck dependency now uses the narrower custom_kv_cache target.

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Claude finished @xingguo01's task in 5m 23s —— View job


All four follow-ups from the last round are fixed and nothing blocks the merge, so I'd approve this; two small test issues remain, and the most useful fix is a log test that can no longer fail now that the message is logged at DEBUG.

Detailed review

PR Review: #25033 (fourth re-review)

Summary

The PR adds SDPA node finders, an INT32 QK accumulator qspec factory and INT16 StaticQuantizedKVCache storage, and now includes a TOSA reference-model test for the A8 path.

  • How I read it: I read the diff as HEAD~1..HEAD, because the shallow checkout has no merge base with origin/main.
  • What I didn't do: I ran no tests. No reviewer confirmed that the .md and .md.in doc additions are identical.
  • Not raised again: points already settled are the node-finder API, later registration winning, factories that require a node (including the Cortex-M callers that pass no node or drop it), raising on ambiguous QK/AV, the Vela 5.2.0 pin and the source_fn_stack format.

Testing

  • test_replace_static_quantized_cache_rejects_dtype_before_logging can no longer fail (examples/models/llama/tests/test_replace_kv_cache.py:337).
    • The test asserts assertNoLogs(level="INFO").
    • The replacement message is now logging.debug (custom_kv_cache.py:593), and DEBUG records are below INFO, so the assertion passes even if the code logs before it validates the dtype.
    • Fix: use level="DEBUG" in this test. ..._does_not_log_at_info (:326) is correct as it is.
    • Fix this →
  • The new TOSA test checks the boolean mask loosely (backends/arm/test/quantizer/test_sdpa_quantization.py:263-333).
    • With v = eye(8), the output is the probability vector itself, and columns 4: are masked, so they must be exactly 0.
    • atol=0.04 would still accept a partial mask leak: masked probabilities up to 0.04 instead of 0. A complete mask failure would still be caught.
    • Suggestion: assert that the reference-model output at [..., 4:] is exactly zero.
    • The second run_method_and_compare_outputs call (:327) relies on the default "latest stage" and leaves out the pipeline's compare_callback. Passing stage= explicitly would keep the eager comparison on the TOSA reference-model artifact if the pipeline's stages change.

Code Quality

  • A matched SDPA group with no matmuls aborts role-based quantization (backends/cortex_m/quantizer/node_finders.py:281-287). Low confidence: one reviewer raised this and nobody reproduced it.
    • Only an undecomposed aten.scaled_dot_product_attention.default is skipped.
    • Trigger: a group whose source_fn_stack points at F.scaled_dot_product_attention but which holds a fused op instead of matmuls, for example _scaled_dot_product_flash_attention_for_cpu after run_decompositions(). That group reaches len(matmuls) != 2 and raises "Cannot identify QK and AV", which stops quantization of the whole model.
    • The Arm flow quantizes the pre-dispatch graph, so it probably never hits this.
    • Possible fix: skip groups that contain no matmuls, the same way native groups are skipped.

Recommendation

Approve

None of these block the merge. The assertNoLogs level is a one-line fix.

@xingguo01
xingguo01 force-pushed the arm-quantized-kv-attention-primitives branch from 1df6aa4 to a77aba9 Compare November 23, 2026 13:37
@xingguo01

Copy link
Copy Markdown
Collaborator Author

@claude Thanks. Fixed the DEBUG logging guard and strengthened the TOSA mask assertions. Both comparisons now explicitly select the TOSA reference artifact and share the comparison callback.

I also reproduced the fused CPU SDPA case using real export/decomposition. Groups without explicit matmuls are now skipped, with regressions confirming that incomplete or ambiguous decompositions still fail.

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Claude finished @xingguo01's task in 4m 18s —— View job


All three items from the last round are fixed and nothing blocks the merge, so I'd approve this. Three minor points remain: some of the TOSA test's tolerance arguments have no effect, one condition in SDPAMatmulFinder can never be true, and the new "no matmuls" skip may hide an incomplete decomposition.

Detailed review

PR Review: #25033 (fifth re-review)

Summary

The PR adds SDPA node finders, an INT32 QK accumulator qspec factory and INT16 StaticQuantizedKVCache storage, with a TOSA reference-model test for the A8 path.

  • How I read it: from HEAD~1..HEAD, because the shallow checkout has no merge base with origin/main.
  • What I didn't do: run any tests.
  • Not raised again: points settled in earlier rounds, which are the node-finder API, later registration winning, factories that require a node, raising on ambiguous QK/AV, the Vela 5.2.0 pin, the source_fn_stack format and the DEBUG-level replacement log.
  • Files read only partly: test_quantization_config.py, test_node_finders.py and the second half of test_sdpa_quantization.py.

Code Quality

  • Groups with no matmuls are skipped even when they contain a softmax (backends/cortex_m/quantizer/node_finders.py:282-286). Low confidence: one reviewer raised this, and nobody built the graph that triggers it.
    • The skip is meant for fused calls such as _scaled_dot_product_flash_attention_for_cpu. It also covers a group that was decomposed into a softmax but whose products are not aten.bmm/aten.matmul (for example mm or baddbmm after another decomposition).
    • In that case SDPAMatmulFinder("qk") selects nothing. SDPAScoreFinder then has no QK operands to subtract (:337-340), so it applies the A16 score config to the QK product and its operands.
    • The requested A8 QK precision is then lost without any error, which goes against "incomplete or ambiguous decompositions still fail".
    • Possible fix: skip only when the group also has no softmax node, and raise otherwise.
  • The native-SDPA half of that condition can never be true (node_finders.py:282-285).
    • _groups gives every aten.scaled_dot_product_attention.default node its own ("native", …) group and hits continue (:216-218). A native group therefore holds only that one node, and not matmuls already covers it.
    • The any(...) clause reads like a separate guard but never changes the result. Dropping it makes if not matmuls: continue the whole rule.

Testing

  • Some tolerances in test_native_a8_attention_masked_softmax_tosa_INT have no effect (backends/arm/test/quantizer/test_sdpa_quantization.py:288-351).
    • When compare_callback is set, ArmTester._compare_outputs calls only the callback (backends/arm/test/tester/arm_tester.py:1146-1149). That makes atol=0.04, rtol=0.03, qtol=0 dead in all three places they're passed: the pipeline constructor, change_args and the explicit second call. Only the values hardcoded in compare_outputs apply.
    • The first comparison, inside pipeline.run(), sets no reference_stage_type. It falls back to StageType.QUANTIZE (arm_tester.py:554-555), so only the second call explicitly selects its reference (INITIAL_MODEL).
    • If comparing against both PT2E and eager is intended, pass reference_stage_type=StageType.QUANTIZE in change_args and remove the unused tolerance kwargs, so the test reads the way it behaves.
    • qk = matmuls[0] (:330) assumes QK is serialized first. The test already follows QK's output to find the rescale, so it could also identify QK by data flow: the MATMUL whose output reaches the INT32→INT16 RESCALE.

Recommendation

Approve

None of these block the merge. The no-softmax condition on the skip is the only one that could change behaviour, and nobody has reproduced it.

Configure native SDPA through quantizer annotations and decomposition
provenance instead of requiring model-specific attention arithmetic.
Support A16 attention and experimental A8 QK/AV, deriving INT32 QK
scales from symmetric operands and retaining A16 masked softmax.

Keep calibrated integer cache storage separate from attention policy.
Retain the experimental Vela-specific INT16 variable path without a
model-specific SDPA source transform. Cover quantizer selection, masks,
GQA, accumulator bounds, and delegated mutable-buffer ownership.

AI-assisted-by: Codex
Change-Id: Ia0d7d8113e3d0f6aa6b625a121329c86d7b6c539
Signed-off-by: Xingguo Li <xingguo.li@arm.com>
@xingguo01
xingguo01 force-pushed the arm-quantized-kv-attention-primitives branch from a77aba9 to 1f4b7fd Compare November 23, 2026 15:20
@xingguo01

Copy link
Copy Markdown
Collaborator Author

@claude Thanks, addressed these points.

  • Reproduced the zero-matmul issue using a numerically equivalent SDPA decomposition with aten.mm. Groups containing exposed softmax now raise when QK/AV cannot be identified; native/fused opaque calls remain skipped. Added regressions for QK, AV and score selection.
  • Removed the redundant native-SDPA condition.
  • Removed unused tolerance arguments and explicitly selected the PT2E and eager references. The shared callback retains the numerical tolerances and exact-zero masked-output check.
  • QK identification now follows the INT32→INT16 rescale’s producer chain rather than assuming serialization order.

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Claude finished @xingguo01's task in 3m 52s —— View job


All four fixes from the last round are in and nothing blocks the merge, so I'd approve this. Three minor points remain, the most useful being that the second reference-model comparison in the new TOSA test isn't guarded when the TOSA reference model is unavailable.

Detailed review

PR Review: #25033 (sixth re-review)

Summary

The PR adds SDPA node finders, an INT32 QK accumulator qspec factory and INT16 StaticQuantizedKVCache storage, with a TOSA reference-model test for the A8 path.

  • How I read it: from HEAD~1..HEAD, because the shallow checkout has no merge base with origin/main.
  • What I didn't do: run any tests.
  • Not raised again: the node-finder API, later registration winning, factories that require a node (including the Cortex-M callers that pass no node), raising on ambiguous QK/AV, the Vela 5.2.0 pin, the source_fn_stack format and the DEBUG-level log.
  • Files only partly read: test_quantization_config.py, test_get_decomposition_pass.py, test_decompose_sdpa.py.

Code Quality

  • SDPAMatmulFinder() with no role skips the new guard (backends/cortex_m/quantizer/node_finders.py:296-300). Two reviewers found this.
    • The if self.role is None: ... continue branch runs before the "exposed softmax but no recognised matmul" check.
    • Trigger: your aten.mm decomposition. SDPAMatmulFinder("qk") and ("av") raise, but SDPAMatmulFinder() returns nothing and gives no warning. If it is registered as an override on top of a broad SDPAFinder(), QK and AV quietly keep the broad precision.
    • The class docstring says role selection is what rejects these cases, which is accurate. The .md and .md.in docs describe finders in general as rejecting them, which isn't.
    • Relatedly, get_int8_matmul_accumulator_qspec (quantization_config.py, ~619) accepts only bmm/matmul. The annotator does quantize aten.mm.default, so for an mm-based QK the error "requires a matmul node" is misleading.
    • Fix: move the softmax/no-matmul check above the role is None branch. Alternatively, recognise aten.mm.default in both places.
  • Nested decompositions write the parent's source_fn_stack entry twice (backends/arm/_passes/get_decomposition_pass.py:138-142, and the same code in backends/transforms/decompose_sdpa.py:145-149).
    • A child produced by an earlier decomposition already ends its stack with (child.name, child.target). Decomposing that child again appends the same pair before the grandchild's entry, giving [..., (sdpa, …), (mm_x, matmul), (mm_x, matmul), (grandchild, …)].
    • Trigger: DecomposeScaledDotProductAttention runs, then a GetDecompositionPass subclass decomposes one of the SDPA's children.
    • Nothing breaks today, because get_source_partitions reads [-1] and SDPAFinder finds the first SDPA entry.
    • The new test_get_decomposition_pass.py sets the parent's stack without its own trailing entry, so it doesn't test the real nested shape.
    • Fix: skip the append when stack[-1] is already (node.name, node.target).

Testing

  • The second reference-model comparison in test_native_a8_attention_masked_softmax_tosa_INT has no guard (backends/arm/test/quantizer/test_sdpa_quantization.py:345-350).
    • TOSAPipeline.run() (backends/arm/test/tester/test_pipeline.py:565-574) removes the run_method_and_compare_outputs stage with a warning when the TOSA reference model isn't available. The direct pipeline.tester.run_method_and_compare_outputs(...) call after it isn't covered by that check, so in the same environment the test fails instead of skipping.
    • Fix: wrap the call in if pipeline.is_tosa_ref_model_available():, as test_pixel_shuffling.py:159 and test_ioquantization_pass.py:418 do. Or add the eager comparison as a second pipeline stage so the existing skip applies to it.
    • Fix this →

Recommendation

Approve

None of these block the merge. The guard on the second comparison is a one-line fix, and moving the no-matmul check above the role is None branch would make "no silent precision change" hold for every role.

@xingguo01

Copy link
Copy Markdown
Collaborator Author

@digantdesai I think I have addressed all concerns from Claude, though it is a bit persistent

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. help wanted Extra attention is needed module: arm Issues related to arm backend release notes: arm Changes to the ARM backend delegate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants