contrib-op-shape-inference-memory-safety
Skill22k starsChanged 3 months agoMITView on GitHub
Audit and fix out-of-range output writes in ONNX Runtime operator shape-inference functions. Use when reviewing or fixing a contrib (or standard) op TypeAndShapeInference where a getNumOutputs() guard precedes a write to a higher output index - optional trailing outputs make a smaller output count schema-valid, so getOutputType(index) can run one past the declared outputs at Graph::Resolve.
Trending
Less talk lately.about the whole repository
Who's talking about microsoft/onnxruntime
- A Hacker News story“ONNX Runtime merges WebGPU backend”Hacker News · Apr 24, 2023 · 178 points
- immich-app/immich“feat(ml): introduce support of onnxruntime-rocm for AMD GPU”GitHub · Jul 12, 2024 · 28 reactions
- Unstructured-IO/unstructured“feat/numpy_2”GitHub · Oct 1, 2024 · 17 reactions
- microsoft/vcpkg“[onnxruntime] new ports for microsoft/onnxruntime v1.23.2”GitHub · Feb 19, 2024 · 17 reactions
- huggingface/transformers.js“Can GPU acceleration be used when using this library in a node.js environment?”GitHub · Feb 7, 2024 · 17 reactions
The biggest 5 of 39 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 39
Talked about on GitHub, Hacker News, Bluesky and the web (39 times).
On GitHub · 32
- Jul 12, 2024feat(ml): introduce support of onnxruntime-rocm for AMD GPU — immich-app/immich28 reactions · 58 comments
- Oct 1, 2024feat/numpy_2 — Unstructured-IO/unstructured17 reactions · 10 comments
- Feb 19, 2024[onnxruntime] new ports for microsoft/onnxruntime v1.23.2 — microsoft/vcpkg17 reactions · 80 comments
- Feb 7, 2024Can GPU acceleration be used when using this library in a node.js environment? — huggingface/transformers.js17 reactions · 6 comments
- Jan 21, 2024FAQ/GUIDE: I've figured out why CUDA isn't available in Insightface! — cubiq/ComfyUI_IPAdapter_plus17 reactions · 14 comments
27 more on GitHub
- Jan 8, 2020[request] some of most relevant c++ libraries in github (by number of stars) — conan-io/conan-center-index16 reactions · 132 comments
- Jun 18, 2024feat: add support for custom ai models | Pipeline API RFC — supabase/edge-runtime14 reactions · 18 comments
- Mar 16, 2021Add support for anchor tags — lycheeverse/lychee13 reactions · 39 comments
- May 14, 2024wanted: microsoft/onnxruntime — bazelbuild/bazel-central-registry11 reactions · 3 comments
- Mar 6, 2021[request] onnxruntime/1.7.1 — conan-io/conan-center-index11 reactions · 11 comments
- Nov 13, 2025Getting wrong .NET version — actions/setup-dotnet10 reactions · 18 comments
- May 8, 2025Enable Android 16 KB page size support — microsoft/onnxruntime-extensions9 reactions · 14 comments
- Apr 11, 2024Expose onnxruntime session options (intra_op_num_threads) — deepinsight/insightface9 reactions
- Sep 16, 2020Exporting the pytorch grid_sample operator to ONNX opset version 9 is not supported — pytorch/pytorch7 reactions · 1 comment
- Dec 29, 2023wasm does not work on node right now with multiple threads — huggingface/transformers.js6 reactions · 3 comments
- Mar 22, 2022Define layer normalization as a function — onnx/onnx6 reactions
- Dec 2, 2020[onnxruntime] Add new port — microsoft/vcpkg6 reactions · 28 comments
- Jul 28, 2026(partially) fix #23462: configure onnxruntime to stop VRAM usage from growing — immich-app/immich5 reactions · 4 comments
- Jul 23, 2024windows 10 installation tutorial (win10 安装教程) — warmshao/FasterLivePortrait5 reactions · 1 comment
- Nov 30, 2023[ROCm] TunableOp — pytorch/pytorch5 reactions · 31 comments
- Apr 15, 2025[DO NOT SUBMIT] Model cache POC — shiyi9801/chromium4 reactions · 2 comments
- Nov 19, 2024GafferML — GafferHQ/gaffer4 reactions · 3 comments
- Apr 15, 2026Add support for q1, q1f16, q2, q2f16 data types — huggingface/transformers.js3 reactions · 1 comment
- Dec 26, 2025onnx and onnxruntime bump versions (fixed onnx dependency with shared=True) — conan-io/conan-center-index3 reactions
- Nov 4, 2025python3Packages.rapidocr-onnxruntime: fix aarch64-linux build — NixOS/nixpkgs3 reactions · 7 comments
- Feb 26, 2025introduce "--webnn-ort-ov-gpu-precision" to specify gpu precision — shiyi9801/chromium3 reactions · 1 comment
- Feb 4, 2025Add: WASM Emscripten example — pykeio/ort3 reactions · 33 comments
- Feb 1, 2025Object mask — darktable-org/darktable3 reactions · 5 comments
- Sep 23, 2024C, C++, and Python API for Adapters (Multi-LoRA and others) — microsoft/onnxruntime-genai3 reactions
- Dec 12, 2023relax protobuf restriction — microsoft/onnxconverter-common3 reactions · 12 comments
- Apr 1, 2023onnxruntime: add 1.14.1 — conan-io/conan-center-index3 reactions · 36 comments
- Jan 14, 2022Add Col2Im operator — onnx/onnx3 reactions · 21 comments
On Hacker News · 5
- Apr 24, 2023ONNX Runtime merges WebGPU backend178 points · 35 comments
- Jan 19, 2020ONNX Runtime: cross-platform, high performance scoring engine for ML models8 points · 1 comment
- Sep 26, 2025ONNX Runtime v1.23.0 Released4 points
- Dec 11, 2020ONNX Runtime v1.6.0 Release1 point
- Oct 31, 2019Microsoft collects telemetry in onnxruntime Python module1 point
On Bluesky · 1
- Aug 22, 2026📦 microsoft / onnxruntime ⭐ 21,420 (+5) 🗒 C++ ONNX Runtime: cross-platform, high performance ML inferencing and training accelerator — @github-trending.bsky.social1 likes and repost
On the web · 1
- Oct 21, 2026microsoft/onnxruntime - GitHub Explorer — ghe.derekchia.com
In this repository15 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .github/copilot-instructions.mdCopilot instructions
- code-reviewSkill
- cuda-attention-kernel-patternsSkill
- cuda-cutlass-fmha-incremental-rebuildSkill
- onnx-opset-bump-checklistSkill
- ort-buildSkill
- ort-ciSkill
- ort-lintSkill
- ort-release-notesSkill
- ort-testSkill
- ort-transformers-gpu-pytestSkill
- python-kwargs-setattr-securitySkill
- webgpu-local-testingSkill
- workspace-estimation-shared-headerSkill
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 3 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 73
Do not stop at the reported function.
- Very specific: line 159
Only the full resolve path constructs the real InferenceContextImpl and hits the getOutputType sink described in §2.
- Very specific: line 198
Run lintrunner -a before pushing so the CLANGFORMAT / Python-format gate passes.
- Distinctive: line 200
Use correctness/robustness framing in code, comments, commit messages, and the PR body
- Distinctive: line 206
When reviewing or hardening any operator implementation or its shape inference:
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Contrib-Op Shape-Inference Output-Index Safety
Reusable method for finding and fixing the bug class where an operator's
TypeAndShapeInference function guards an output write with getNumOutputs() > N but then
writes an output index greater than N. For a node that declares fewer outputs, the
written index is past the end of the inference context's output vector.
Scope: schema-level shape inference in
onnxruntime/core/graph/contrib_ops/*.ccandshape_inference_functions.cc. This runs once duringGraph::Resolve(model-load time), EP-agnostic - there is no per-EP (CPU/CUDA/ROCm) kernel duplicate of this code to chase. Op kernels allocate outputs via the bounds-safeOpKernelContext::Output(index)and are a separate concern.
1. The pattern
// onnxruntime/core/graph/contrib_ops/bert_defs.cc (before)
propagateElemTypeFromInputToOutput(ctx, 0, 0);
if (ctx.getNumOutputs() > 1) { // guard says "> 1"
propagateElemTypeFromInputToOutput(ctx, 0, 1);
propagateElemTypeFromInputToOutput(ctx, 0, 2); // but writes index 2
}The guard getNumOutputs() > 1 admits a node with exactly 2 outputs (indices 0, 1), yet
the body writes index 2. The implication "> 1 ⇒ index 2 exists" is false: > 1 only
guarantees indices 0 and 1.
Why a smaller output count is valid
Trailing outputs declared OpSchema::Optional lower min_output. ONNX derives
min_output = number of required outputs, max_output = total declared. The model checker
(checker::check_node) only enforces min_output <= N <= max_output.
| Op | Output decls | min / max | A 2-output node? |
DecoderAttention | out (req), new_key_cache (Opt), new_value_cache (Opt) | 1 / 3 | passes checker |
MultiHeadAttention | out (req), present_key (Opt), present_value (Opt), qk (Opt) | 1 / 4 | passes checker |
DecoderMaskedMultiHeadAttention | out (req) + 3 Optional | 1 / 4 | passes checker |
So a node with output=['out','present_key'] is schema-valid, passes the checker, and then
reaches the index-2 write. A passing checker is not a guarantee the index is in range.
2. The sink (why the write is not caught)
// onnxruntime/core/graph/graph.cc - InferenceContextImpl
const TypeProto* getInputType(size_t index) const override {
return node_.InputDefs().at(index)->TypeAsProto(); // .at() -> bounds-checked
}
TypeProto* getOutputType(size_t index) override {
return &node_output_types_[index]; // operator[] -> NOT bounds-checked
}node_output_types_is sized tonode.OutputDefs().size()in theInferenceContextImplctor, so for a 2-output node it has 2 elements;getOutputType(2)returns one past the end.getInputTypeuses.at()(would throw on a bad index);getOutputTypeuses rawoperator[](no check) - the asymmetry is the root cause.- The call runs at
Graph::Resolve→InferAndVerifyTypeMatch→RunInferencing. The surroundingORT_TRY/ORT_CATCH(const std::exception&)only catches thrownfail_shape_inference; a raw out-of-rangeoperator[]does not throw, so the catch does not help. - Because this is schema-level inference, it is EP-independent - no CUDA/ROCm copy.
3. Audit technique — always sweep siblings
Do not stop at the reported function. Grep every shape-inference guard and compare its threshold against the highest output index written before the next guard.
git grep -n 'getNumOutputs' -- \
onnxruntime/core/graph/contrib_ops/*.cc \
onnxruntime/core/graph/contrib_ops/shape_inference_functions.ccFor each if (ctx.getNumOutputs() > N) block, find the largest index passed to
propagateElemTypeFromInputToOutput(ctx, _, index) / updateOutputShape(ctx, index, _) /
getOutputType(index) inside it. Rule: the guard must require strictly more outputs than
the highest index written (write index k ⇒ guard must ensure getNumOutputs() > k).
Correct exemplars already in the tree to copy:
| Exemplar | Pattern | Why it is safe |
BaseGroupQueryAttention... | if (getNumOutputs() >= 3) then writes idx 2 | guard covers highest index |
PagedAttention... | nested > 1 + inner if (getNumOutputs() != 3) fail_shape_inference | fails before any write |
EmbedLayerNormalizationShapeInference | > 2 then writes idx 2 | fixed by PR #28176 (precedent) |
SkipLayerNormalizationShapeInference | each idx k guarded by > k | per-index guard |
Gotcha — conditional writes can hide a vacuous audit. A write may sit behind an inner condition (e.g.
hasInputShape(past_key_index)before writing index 2). The site is still a bug, but you can only observe it when that inner condition is also satisfied. Keep this in mind both for the audit and for tests (§5).
4. Fix patterns
Point fix (required): raise the guard to cover the highest index written.
// before
if (ctx.getNumOutputs() > 1) { ... writes idx 2 ... }
// after
if (ctx.getNumOutputs() > 2) { // both present_key (idx 1) AND present_value (idx 2)
...
}Justify the threshold with the op's output semantics. For these attention ops the two trailing
outputs - present_key (idx 1) and present_value (idx 2) for MultiHeadAttention,
new_key_cache / new_value_cache for DecoderAttention (see the §1 table for each op's
exact output names) - are a both-or-neither pair: there is no valid configuration that
emits one without the other, so requiring all three outputs before populating indices 1 and 2
is behavior-preserving. (PagedAttention encodes the same invariant via its nested != 3
check.)
Defense-in-depth (recommended): bound the sink so a future author cannot reintroduce the class.
// onnxruntime/core/graph/graph.cc - InferenceContextImpl::getOutputType
TypeProto* getOutputType(size_t index) override {
if (index >= node_output_types_.size()) {
fail_type_inference("output index ", index, " is out of range; node has ",
node_output_types_.size(), " outputs");
}
return &node_output_types_[index];
}This mirrors getInputType's .at() and the existing bounds checks in the sibling
DataPropagationContextImpl. Placing it at the base layer transitively protects the NHWC and
quantization wrapper contexts. After the point fix this branch is unreachable through a normal
model (the guard already prevents the out-of-range index), so it is pure defense-in-depth. Its
failure mode is build-dependent: with exceptions enabled, fail_type_inference raises
InferenceError (a std::exception), caught by the existing ORT_CATCH(const std::exception&)
around RunInferencing and surfaced as a clean load-time error; under ORT_NO_EXCEPTIONS it is
not compiled out - ONNX's no-exceptions path prints the message to std::cerr and calls
abort(), a deterministic fail-fast (consistent with getInputType's .at(), which likewise
terminates under no-exceptions). Either way the result is a controlled failure rather than an
out-of-range write.
5. Test recipe
Tests live in onnxruntime/test/contrib_ops/*.cc and are auto-globbed into the
onnxruntime_provider_test target by cmake/onnxruntime_unittests.cmake
(test/contrib_ops/*.cc pattern) - no cmake edit needed for a new file. See the
ort-test skill for the executable taxonomy (onnxruntime_provider_test vs
onnxruntime_test_all).
Rules that make the regression test actually guard the fix:
- Drive through
Model+Graph::Resolve, not ONNX's standaloneTestShapeInference. Only the full resolve path constructs the realInferenceContextImpland hits thegetOutputTypesink described in §2. A standalone ONNX shape-inference helper uses a different context and bypasses the sink, so it cannot reproduce the bug. - Negative tests must be NON-VACUOUS - they must actually enter the write branch on
pre-fix source. If a write is gated by an inner condition (§3 gotcha), satisfy it: e.g. for
MultiHeadAttention/DecoderMaskedMultiHeadAttention, supply a shapedpast_key(andpast_sequence_length/past_present_share_bufferas the op requires) so the index-2 block runs. A negative test that only suppliesqueryskips the block and passes even on pre-fix source - regression-proof in name only. - Add positive (all-outputs) cases: a node with every output present must still infer the trailing output types - proves the tightened guard did not over-restrict.
- Keep tests throw-free post-fix so they are valid under
ORT_NO_EXCEPTIONS. Any case that is expected tofail_shape_inference(throws) must be excluded with#ifndef ORT_NO_EXCEPTIONS. The "2 outputs must not go out of range" case is throw-free after the point fix and is safe in all builds.
Verify the negative test is non-vacuous (sanitizer A/B) - the most reliable way to prove a negative test enters the previously-out-of-range branch: build the test at the pre-fix commit with AddressSanitizer and confirm it flags the out-of-range output access; then confirm it is clean after the fix.
# Functional run (any Debug build):
cmake --build build/Linux/Debug --target onnxruntime_provider_test -j"$(nproc)"
./build/Linux/Debug/onnxruntime_provider_test \
--gtest_filter='AttentionOptionalOutputsShapeInferenceTest.*'
# A/B proof (isolated worktree at the pre-fix commit, CPU-only Debug + sanitizer):
git worktree add --detach ../ort-prefix-check <fix_commit>~1
# copy the new test file in, then:
python3 tools/ci_build/build.py --build_dir build/asan --config Debug --parallel \
--skip_tests --enable_address_sanitizer --skip_submodule_sync \
--cmake_generator Ninja --target onnxruntime_provider_test
# Pre-fix: the negative tests fail (the sanitizer flags the out-of-range output access).
# Post-fix (cherry-pick the guard fix): all tests pass, no sanitizer report.6. Process / wording conventions
- Run
lintrunner -abefore pushing so theCLANGFORMAT/ Python-format gate passes. See theort-lintskill. - Use correctness/robustness framing in code, comments, commit messages, and the PR body
- describe the change as fixing an optional-output guard, not as a security fix. This
matches repo convention (compare
python-kwargs-setattr-security) and keeps the PR neutral.
- describe the change as fixing an optional-output guard, not as a security fix. This
matches repo convention (compare
7. Audit checklist (per-operator review)
When reviewing or hardening any operator implementation or its shape inference:
- Read the op's spec - ONNX standard op page, or for a contrib op its
OpSchemaregistration (.Input/.Output/.Attr, andOptional/Variadicmarkers). A local ONNX checkout has the standard-op spec pages; contrib ops are defined only in ORT. - Enumerate all inputs, attributes, and outputs, noting which are optional and the
resulting
min/maxinput and output counts. - Validate every input/attribute before indexing into it, to avoid out-of-range reads (which can cascade into worse failures). Match each output-index write to a guard that guarantees the index is in range (§3 rule).
- Prefer
ORT_RETURN_IF/ORT_RETURN_IF_NOTfor validation; useORT_ENFORCEin constructors. In shape inference usefail_shape_inference/fail_type_inference. - Use
SafeInt<>/narrow<>()for index and size arithmetic and casts to avoid overflow or truncation that yields a wrong index. Seecore/common/safeint.handdocs/Coding_Conventions_and_Standards.md. - Ensure tests build and pass under no-exceptions builds;
#ifndef ORT_NO_EXCEPTIONSaround any case expected to throw. - Exclude EPs known not to support the op, with a comment explaining why.
- Check whether other EPs (notably CUDA/ROCm) implement the same op and whether the same issue exists there. (For shape inference specifically, the logic is EP-agnostic and single-source - confirm there is no kernel-side analogue.)
References
- PR #28176 - "Fix ... in EmbedLayerNormalizationShapeInference": the precedent that fixed
the identical
> 1→> 2primitive in one site; the sibling attention sites were missed, motivating the sweep in §3. - PR #29268 - this fix: guards corrected in
DecoderAttention/MultiHeadAttention/DecoderMaskedMultiHeadAttentionshape inference, plus thegetOutputTypebounds check and non-vacuous regression tests. - Sibling skill:
ort-test(test executables,--gtest_filter, contrib-op test layout);ort-lint(lintrunner -a);ort-build(build flags, ASan).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

