From a0752184ef7dc4a5076735225e5ddd6c33110c61 Mon Sep 17 00:00:00 2001 From: Michael Hucka Date: Tue, 17 Nov 2026 21:20:43 +0000 Subject: [PATCH] Validate input ranks before calling dim_size() in ops 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. --- .../ops/math_ops/inner_product_grad_test.py | 16 +++++++++++ .../ops/math_ops/inner_product_op_test.py | 7 +++++ .../core/ops/math_ops/simulate_mps_test.py | 28 +++++++++++++++++++ .../core/ops/math_ops/tfq_inner_product.cc | 5 ++++ .../ops/math_ops/tfq_inner_product_grad.cc | 10 +++++++ .../math_ops/tfq_simulate_1d_expectation.cc | 5 ++++ .../tfq_simulate_1d_sampled_expectation.cc | 5 ++++ .../ops/noise/noisy_expectation_op_test.py | 8 ++++++ .../noisy_sampled_expectation_op_test.py | 8 ++++++ .../core/ops/noise/tfq_noisy_expectation.cc | 5 ++++ .../noise/tfq_noisy_sampled_expectation.cc | 5 ++++ .../core/ops/tfq_adj_grad_op.cc | 7 ++++- .../core/ops/tfq_adj_grad_op_test.py | 11 +++++++- .../core/ops/tfq_simulate_expectation_op.cc | 5 ++++ .../core/ops/tfq_simulate_ops_test.py | 16 +++++++++++ .../tfq_simulate_sampled_expectation_op.cc | 5 ++++ 16 files changed, 144 insertions(+), 2 deletions(-) diff --git a/tensorflow_quantum/core/ops/math_ops/inner_product_grad_test.py b/tensorflow_quantum/core/ops/math_ops/inner_product_grad_test.py index c93bd3ae7..bcaebbdba 100644 --- a/tensorflow_quantum/core/ops/math_ops/inner_product_grad_test.py +++ b/tensorflow_quantum/core/ops/math_ops/inner_product_grad_test.py @@ -64,6 +64,14 @@ def test_inner_product_grad_inputs(self): symbol_names, symbol_values_array, util.convert_to_tensor(other_batch), prev_grad) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, + 'programs must be rank 1. Got rank 0'): + # Circuit tensor is a scalar. + inner_product_op._inner_product_grad( + util.convert_to_tensor(circuit_batch)[0], + symbol_names, symbol_values_array, + util.convert_to_tensor(other_batch), prev_grad) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_names must be rank 1.'): # symbol_names tensor has too many dimensions. @@ -72,6 +80,14 @@ def test_inner_product_grad_inputs(self): np.array([symbol_names]), symbol_values_array, util.convert_to_tensor(other_batch), prev_grad) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, + 'symbol_names must be rank 1. Got rank 0'): + # symbol_names tensor is a scalar. + inner_product_op._inner_product_grad( + util.convert_to_tensor(circuit_batch), + tf.constant(symbol_names[0]), symbol_values_array, + util.convert_to_tensor(other_batch), prev_grad) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_values must be rank 2.'): # symbol_values_array tensor has too many dimensions. diff --git a/tensorflow_quantum/core/ops/math_ops/inner_product_op_test.py b/tensorflow_quantum/core/ops/math_ops/inner_product_op_test.py index 15151066d..6e6b51d4a 100644 --- a/tensorflow_quantum/core/ops/math_ops/inner_product_op_test.py +++ b/tensorflow_quantum/core/ops/math_ops/inner_product_op_test.py @@ -61,6 +61,13 @@ def test_inner_product_inputs(self): util.convert_to_tensor([circuit_batch]), symbol_names, symbol_values_array, util.convert_to_tensor(other_batch)) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, + 'programs must be rank 1. Got rank 0'): + # Circuit tensor is a scalar. + inner_product_op.inner_product( + util.convert_to_tensor(circuit_batch)[0], symbol_names, + symbol_values_array, util.convert_to_tensor(other_batch)) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_names must be rank 1.'): # symbol_names tensor has too many dimensions. diff --git a/tensorflow_quantum/core/ops/math_ops/simulate_mps_test.py b/tensorflow_quantum/core/ops/math_ops/simulate_mps_test.py index 3ea6e4b89..f34842e2e 100644 --- a/tensorflow_quantum/core/ops/math_ops/simulate_mps_test.py +++ b/tensorflow_quantum/core/ops/math_ops/simulate_mps_test.py @@ -91,6 +91,14 @@ def test_simulate_mps_1d_expectation_inputs(self): symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums])) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, + 'programs must be rank 1. Got rank 0'): + # Circuit tensor is a scalar. + simulate_mps.mps_1d_expectation( + util.convert_to_tensor(circuit_batch)[0], symbol_names, + symbol_values_array, + util.convert_to_tensor([[x] for x in pauli_sums])) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_names must be rank 1.'): # symbol_names tensor has too many dimensions. @@ -904,6 +912,26 @@ def test_simulate_mps1d_sampled_expectation_inputs(self): util.convert_to_tensor([[small_pauli] for _ in pauli_sums]), num_samples) + def test_simulate_mps1d_sampled_expectation_scalar_programs(self): + """Make sure sampled expectation op rejects a scalar programs input.""" + batch_size = 5 + symbol_names = ['alpha'] + qubits = cirq.GridQubit.rect(1, 5) + circuit_batch = [ + cirq.Circuit(cirq.X(qubits[0])**sympy.Symbol(symbol_names[0])) + for _ in range(batch_size) + ] + symbol_values_array = np.full((batch_size, 1), 0.123) + pauli_sums = util.random_pauli_sums(qubits, 3, batch_size) + + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, + 'programs must be rank 1. Got rank 0'): + simulate_mps.mps_1d_sampled_expectation( + util.convert_to_tensor(circuit_batch)[0], symbol_names, + symbol_values_array, + util.convert_to_tensor([[x] for x in pauli_sums]), + [[10]] * batch_size) + def test_simulate_sampled_mps_1d_expectation_simple(self): """Makes sure that the op shows the same result with Cirq.""" n_qubits = 5 diff --git a/tensorflow_quantum/core/ops/math_ops/tfq_inner_product.cc b/tensorflow_quantum/core/ops/math_ops/tfq_inner_product.cc index 61f0485af..fcd829ef1 100644 --- a/tensorflow_quantum/core/ops/math_ops/tfq_inner_product.cc +++ b/tensorflow_quantum/core/ops/math_ops/tfq_inner_product.cc @@ -54,6 +54,11 @@ class TfqInnerProductOp : public tensorflow::OpKernel { tensorflow::errors::InvalidArgument(absl::StrCat( "Expected 4 inputs, got ", num_inputs, " inputs."))); + OP_REQUIRES(context, context->input(0).dims() == 1, + tensorflow::errors::InvalidArgument( + absl::StrCat("programs must be rank 1. Got rank ", + context->input(0).dims(), "."))); + OP_REQUIRES( context, context->input(3).dims() == 2, tensorflow::errors::InvalidArgument(absl::StrCat( diff --git a/tensorflow_quantum/core/ops/math_ops/tfq_inner_product_grad.cc b/tensorflow_quantum/core/ops/math_ops/tfq_inner_product_grad.cc index 6906ca9ab..7390dac39 100644 --- a/tensorflow_quantum/core/ops/math_ops/tfq_inner_product_grad.cc +++ b/tensorflow_quantum/core/ops/math_ops/tfq_inner_product_grad.cc @@ -55,6 +55,16 @@ class TfqInnerProductGradOp : public tensorflow::OpKernel { tensorflow::errors::InvalidArgument(absl::StrCat( "Expected 5 inputs, got ", num_inputs, " inputs."))); + OP_REQUIRES(context, context->input(0).dims() == 1, + tensorflow::errors::InvalidArgument( + absl::StrCat("programs must be rank 1. Got rank ", + context->input(0).dims(), "."))); + + OP_REQUIRES(context, context->input(1).dims() == 1, + tensorflow::errors::InvalidArgument( + absl::StrCat("symbol_names must be rank 1. Got rank ", + context->input(1).dims(), "."))); + OP_REQUIRES( context, context->input(3).dims() == 2, tensorflow::errors::InvalidArgument(absl::StrCat( diff --git a/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_expectation.cc b/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_expectation.cc index f4ace8d3a..8999ac3ef 100644 --- a/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_expectation.cc +++ b/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_expectation.cc @@ -63,6 +63,11 @@ class TfqSimulateMPS1DExpectationOp : public tensorflow::OpKernel { tensorflow::errors::InvalidArgument(absl::StrCat( "Expected 4 inputs, got ", num_inputs, " inputs."))); + OP_REQUIRES(context, context->input(0).dims() == 1, + tensorflow::errors::InvalidArgument( + absl::StrCat("programs must be rank 1. Got rank ", + context->input(0).dims(), "."))); + OP_REQUIRES( context, context->input(3).dims() == 2, tensorflow::errors::InvalidArgument(absl::StrCat( diff --git a/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_sampled_expectation.cc b/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_sampled_expectation.cc index 1af415c55..785a975c1 100644 --- a/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_sampled_expectation.cc +++ b/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_sampled_expectation.cc @@ -65,6 +65,11 @@ class TfqSimulateMPS1DSampledExpectationOp : public tensorflow::OpKernel { tensorflow::errors::InvalidArgument(absl::StrCat( "Expected 5 inputs, got ", num_inputs, " inputs."))); + OP_REQUIRES(context, context->input(0).dims() == 1, + tensorflow::errors::InvalidArgument( + absl::StrCat("programs must be rank 1. Got rank ", + context->input(0).dims(), "."))); + OP_REQUIRES( context, context->input(3).dims() == 2, tensorflow::errors::InvalidArgument(absl::StrCat( diff --git a/tensorflow_quantum/core/ops/noise/noisy_expectation_op_test.py b/tensorflow_quantum/core/ops/noise/noisy_expectation_op_test.py index deafcd3bf..e84462ef4 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_expectation_op_test.py +++ b/tensorflow_quantum/core/ops/noise/noisy_expectation_op_test.py @@ -60,6 +60,14 @@ def test_noisy_expectation_inputs(self): symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, + 'programs must be rank 1. Got rank 0'): + # Circuit tensor is a scalar. + noisy_expectation_op.expectation( + util.convert_to_tensor(circuit_batch)[0], symbol_names, + symbol_values_array, + util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_names must be rank 1.'): # symbol_names tensor has too many dimensions. diff --git a/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py b/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py index 2b03e0cb9..0a241549f 100644 --- a/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py +++ b/tensorflow_quantum/core/ops/noise/noisy_sampled_expectation_op_test.py @@ -60,6 +60,14 @@ def test_noisy_expectation_inputs(self): symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, + 'programs must be rank 1. Got rank 0'): + # Circuit tensor is a scalar. + noisy_sampled_expectation_op.sampled_expectation( + util.convert_to_tensor(circuit_batch)[0], symbol_names, + symbol_values_array, + util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_names must be rank 1.'): # symbol_names tensor has too many dimensions. diff --git a/tensorflow_quantum/core/ops/noise/tfq_noisy_expectation.cc b/tensorflow_quantum/core/ops/noise/tfq_noisy_expectation.cc index de32b8806..6739b4b9f 100644 --- a/tensorflow_quantum/core/ops/noise/tfq_noisy_expectation.cc +++ b/tensorflow_quantum/core/ops/noise/tfq_noisy_expectation.cc @@ -66,6 +66,11 @@ class TfqNoisyExpectationOp : public tensorflow::OpKernel { tensorflow::errors::InvalidArgument(absl::StrCat( "Expected 5 inputs, got ", num_inputs, " inputs."))); + OP_REQUIRES(context, context->input(0).dims() == 1, + tensorflow::errors::InvalidArgument( + absl::StrCat("programs must be rank 1. Got rank ", + context->input(0).dims(), "."))); + OP_REQUIRES( context, context->input(3).dims() == 2, tensorflow::errors::InvalidArgument(absl::StrCat( diff --git a/tensorflow_quantum/core/ops/noise/tfq_noisy_sampled_expectation.cc b/tensorflow_quantum/core/ops/noise/tfq_noisy_sampled_expectation.cc index 9b9058165..4e725bbb4 100644 --- a/tensorflow_quantum/core/ops/noise/tfq_noisy_sampled_expectation.cc +++ b/tensorflow_quantum/core/ops/noise/tfq_noisy_sampled_expectation.cc @@ -67,6 +67,11 @@ class TfqNoisySampledExpectationOp : public tensorflow::OpKernel { tensorflow::errors::InvalidArgument(absl::StrCat( "Expected 5 inputs, got ", num_inputs, " inputs."))); + OP_REQUIRES(context, context->input(0).dims() == 1, + tensorflow::errors::InvalidArgument( + absl::StrCat("programs must be rank 1. Got rank ", + context->input(0).dims(), "."))); + OP_REQUIRES( context, context->input(3).dims() == 2, tensorflow::errors::InvalidArgument(absl::StrCat( diff --git a/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc b/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc index cd651da43..1007a9b9d 100644 --- a/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc +++ b/tensorflow_quantum/core/ops/tfq_adj_grad_op.cc @@ -55,10 +55,15 @@ class TfqAdjointGradientOp : public tensorflow::OpKernel { tensorflow::errors::InvalidArgument(absl::StrCat( "Expected 5 inputs, got ", num_inputs, " inputs."))); + OP_REQUIRES(context, context->input(0).dims() == 1, + tensorflow::errors::InvalidArgument( + absl::StrCat("programs must be rank 1. Got rank ", + context->input(0).dims(), "."))); + OP_REQUIRES( context, context->input(2).dims() == 2, tensorflow::errors::InvalidArgument(absl::StrCat( - "symbol_values must be rank 2. Got ", context->input(3).dims()))); + "symbol_values must be rank 2. Got ", context->input(2).dims()))); OP_REQUIRES( context, context->input(3).dims() == 2, diff --git a/tensorflow_quantum/core/ops/tfq_adj_grad_op_test.py b/tensorflow_quantum/core/ops/tfq_adj_grad_op_test.py index bba67db0a..04605c1e5 100644 --- a/tensorflow_quantum/core/ops/tfq_adj_grad_op_test.py +++ b/tensorflow_quantum/core/ops/tfq_adj_grad_op_test.py @@ -61,6 +61,15 @@ def test_adj_grad_inputs(self): util.convert_to_tensor([[x] for x in pauli_sums]), tf.convert_to_tensor(upstream_grads)) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, + 'programs must be rank 1. Got rank 0'): + # Circuit tensor is a scalar. + tfq_adj_grad_op.tfq_adj_grad( + util.convert_to_tensor(circuit_batch)[0], symbol_names, + tf.convert_to_tensor(symbol_values_array), + util.convert_to_tensor([[x] for x in pauli_sums]), + tf.convert_to_tensor(upstream_grads)) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_names must be rank 1.'): # symbol_names tensor has too many dimensions. @@ -71,7 +80,7 @@ def test_adj_grad_inputs(self): tf.convert_to_tensor(upstream_grads)) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, - 'symbol_values must be rank 2.'): + 'symbol_values must be rank 2. Got 3'): # symbol_values_array tensor has too many dimensions. tfq_adj_grad_op.tfq_adj_grad( util.convert_to_tensor(circuit_batch), symbol_names, diff --git a/tensorflow_quantum/core/ops/tfq_simulate_expectation_op.cc b/tensorflow_quantum/core/ops/tfq_simulate_expectation_op.cc index e287a480b..7f680cb96 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_expectation_op.cc +++ b/tensorflow_quantum/core/ops/tfq_simulate_expectation_op.cc @@ -54,6 +54,11 @@ class TfqSimulateExpectationOp : public tensorflow::OpKernel { tensorflow::errors::InvalidArgument(absl::StrCat( "Expected 4 inputs, got ", num_inputs, " inputs."))); + OP_REQUIRES(context, context->input(0).dims() == 1, + tensorflow::errors::InvalidArgument( + absl::StrCat("programs must be rank 1. Got rank ", + context->input(0).dims(), "."))); + OP_REQUIRES( context, context->input(3).dims() == 2, tensorflow::errors::InvalidArgument(absl::StrCat( diff --git a/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py b/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py index e794f60f1..546476dc4 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py +++ b/tensorflow_quantum/core/ops/tfq_simulate_ops_test.py @@ -58,6 +58,14 @@ def test_simulate_expectation_inputs(self): symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums])) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, + 'programs must be rank 1. Got rank 0'): + # Circuit tensor is a scalar. + tfq_simulate_ops.tfq_simulate_expectation( + util.convert_to_tensor(circuit_batch)[0], symbol_names, + symbol_values_array, + util.convert_to_tensor([[x] for x in pauli_sums])) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_names must be rank 1.'): # symbol_names tensor has too many dimensions. @@ -535,6 +543,14 @@ def test_simulate_sampled_expectation_inputs(self): symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, + 'programs must be rank 1. Got rank 0'): + # Circuit tensor is a scalar. + tfq_simulate_ops.tfq_simulate_sampled_expectation( + util.convert_to_tensor(circuit_batch)[0], symbol_names, + symbol_values_array, + util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) + with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_names must be rank 1.'): # symbol_names tensor has too many dimensions. diff --git a/tensorflow_quantum/core/ops/tfq_simulate_sampled_expectation_op.cc b/tensorflow_quantum/core/ops/tfq_simulate_sampled_expectation_op.cc index 4fe98dfea..b3dd8bd80 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_sampled_expectation_op.cc +++ b/tensorflow_quantum/core/ops/tfq_simulate_sampled_expectation_op.cc @@ -58,6 +58,11 @@ class TfqSimulateSampledExpectationOp : public tensorflow::OpKernel { tensorflow::errors::InvalidArgument(absl::StrCat( "Expected 5 inputs, got ", num_inputs, " inputs."))); + OP_REQUIRES(context, context->input(0).dims() == 1, + tensorflow::errors::InvalidArgument( + absl::StrCat("programs must be rank 1. Got rank ", + context->input(0).dims(), "."))); + OP_REQUIRES( context, context->input(3).dims() == 2, tensorflow::errors::InvalidArgument(absl::StrCat(