Skip to content

Validate input ranks before calling dim_size() in ops - #1142

Open
mhucka wants to merge 2 commits into
tensorflow:masterfrom
mhucka:fix-rank-shape-validation
Open

mhucka wants to merge 2 commits into
tensorflow:masterfrom
mhucka:fix-rank-shape-validation

Conversation

@mhucka

@mhucka mhucka commented Nov 20, 2026

Copy link
Copy Markdown
Member

This is a fix for b/510434434, "Missing Rank and Shape Validation in Multiple C++ Operations".

Several op kernels read context->input(0).dim_size(0) (and, in TfqInnerProductGrad, context->input(1).dim_size(0)) and use that to set the size of the output tensor. However, they did this before the input parsers had checked the ranks of those tensors. For a scalar input, TensorFlow's dim_size(0) skips its bounds check and reads an uninitialized dimension slot, so the output was allocated with an arbitrary size before the op later failed.

This PR adds explicit OP_REQUIRES rank checks for programs (and for symbol_names in TfqInnerProductGrad) before any dim_size() call in the expectation, sampled-expectation, adjoint-gradient, inner-product, MPS 1D, and noisy expectation ops. Also correct the symbol_values error message in TfqAdjointGradient, which reported the rank of pauli_sums instead of symbol_values. Along with these changes, this also adds some regression tests.

Several op kernels read `context->input(0).dim_size(0)` (and, in
`TfqInnerProductGrad`, `context->input(1).dim_size(0)`) to size the
output tensor before the input parsers had checked the ranks of those
tensors. For a scalar input, TensorFlow's `dim_size(0)` skips its bounds
check and reads an uninitialized dimension slot, so the output was
allocated with an arbitrary size before the op later failed.

Add explicit `OP_REQUIRES` rank checks for `programs` (and for
`symbol_names` in `TfqInnerProductGrad`) before any `dim_size()` call in
the expectation, sampled-expectation, adjoint-gradient, inner-product,
MPS 1D, and noisy expectation ops. Also correct the `symbol_values`
error message in `TfqAdjointGradient`, which reported the rank of
`pauli_sums` instead of `symbol_values`.

Add regression tests that pass a scalar `programs` tensor to each
affected op, a scalar `symbol_names` tensor to `TfqInnerProductGrad`,
and check the corrected `symbol_values` error message.
@mhucka
mhucka marked this pull request as ready for review November 20, 2026 01:32
gemini-code-assist[bot]

This comment was marked as low quality.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant