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..f1f4a187b 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 @@ -32,6 +32,7 @@ limitations under the License. #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow_quantum/core/ops/parse_context.h" +#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h" #include "tensorflow_quantum/core/proto/pauli_sum.pb.h" #include "tensorflow_quantum/core/proto/program.pb.h" #include "tensorflow_quantum/core/src/program_resolution.h" @@ -88,9 +89,9 @@ class TfqSimulateMPS1DExpectationOp : public tensorflow::OpKernel { // https://github.com/tensorflow/quantum/pull/610 // once https://github.com/quantumlib/qsim/issues/492 // is resolved. - OP_REQUIRES_OK(context, - GetProgramsAndNumQubits(context, &programs, &num_qubits, - &pauli_sums, true)); + OP_REQUIRES_OK(context, GetProgramsAndNumQubits( + context, &programs, &num_qubits, &pauli_sums, + /*swap_endianness=*/true, kMaxMPSQubits)); std::vector maps; OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps)); @@ -214,8 +215,7 @@ class TfqSimulateMPS1DExpectationOp : public tensorflow::OpKernel { } }; - const int64_t num_cycles = - 200 * (int64_t(1) << static_cast(max_num_qubits)); + const int64_t num_cycles = EstimateSimulationCycles(max_num_qubits); context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( unfused_circuits.size() * output_dim_op_size, num_cycles, DoWork); OP_REQUIRES_OK(context, compute_status); 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..7e48cd066 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 @@ -35,6 +35,7 @@ limitations under the License. #include "tensorflow/core/lib/random/simple_philox.h" #include "tensorflow/core/util/guarded_philox_random.h" #include "tensorflow_quantum/core/ops/parse_context.h" +#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h" #include "tensorflow_quantum/core/proto/pauli_sum.pb.h" #include "tensorflow_quantum/core/proto/program.pb.h" #include "tensorflow_quantum/core/src/program_resolution.h" @@ -84,9 +85,9 @@ class TfqSimulateMPS1DSampledExpectationOp : public tensorflow::OpKernel { std::vector programs; std::vector num_qubits; std::vector> pauli_sums; - OP_REQUIRES_OK(context, - GetProgramsAndNumQubits(context, &programs, &num_qubits, - &pauli_sums, true)); + OP_REQUIRES_OK(context, GetProgramsAndNumQubits( + context, &programs, &num_qubits, &pauli_sums, + /*swap_endianness=*/true, kMaxMPSQubits)); std::vector maps; OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps)); @@ -254,8 +255,7 @@ class TfqSimulateMPS1DSampledExpectationOp : public tensorflow::OpKernel { } }; - const int64_t num_cycles = - 200 * (int64_t(1) << static_cast(max_num_qubits)); + const int64_t num_cycles = EstimateSimulationCycles(max_num_qubits); context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( unfused_circuits.size() * output_dim_op_size, num_cycles, DoWork); OP_REQUIRES_OK(context, compute_status); diff --git a/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_samples.cc b/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_samples.cc index 57450b55d..5b873d967 100644 --- a/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_samples.cc +++ b/tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_samples.cc @@ -15,6 +15,7 @@ limitations under the License. #include +#include #include #include "../qsim/lib/circuit.h" @@ -36,6 +37,7 @@ limitations under the License. #include "tensorflow/core/lib/random/simple_philox.h" #include "tensorflow/core/util/guarded_philox_random.h" #include "tensorflow_quantum/core/ops/parse_context.h" +#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h" #include "tensorflow_quantum/core/proto/program.pb.h" #include "tensorflow_quantum/core/src/circuit_parser_qsim.h" #include "tensorflow_quantum/core/src/program_resolution.h" @@ -65,8 +67,9 @@ class TfqSimulateMPS1DSamplesOp : public tensorflow::OpKernel { std::vector programs; std::vector num_qubits; OP_REQUIRES_OK(context, - GetProgramsAndNumQubits(context, &programs, &num_qubits, - nullptr, true)); + GetProgramsAndNumQubits( + context, &programs, &num_qubits, /*p_sums=*/nullptr, + /*swap_endianness=*/true, kMaxMPSQubits)); // Parse symbol maps for parameter resolution in the circuits. std::vector maps; @@ -121,8 +124,8 @@ class TfqSimulateMPS1DSamplesOp : public tensorflow::OpKernel { const size_t output_dim_size = maps.size(); tensorflow::TensorShape output_shape; output_shape.AddDim(output_dim_size); - output_shape.AddDim(num_samples); - output_shape.AddDim(max_num_qubits); + OP_REQUIRES_OK(context, output_shape.AddDimWithStatus(num_samples)); + OP_REQUIRES_OK(context, output_shape.AddDimWithStatus(max_num_qubits)); tensorflow::Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output)); @@ -204,8 +207,7 @@ class TfqSimulateMPS1DSamplesOp : public tensorflow::OpKernel { } }; - const int64_t num_cycles = - 200 * (int64_t(1) << static_cast(max_num_qubits)); + const int64_t num_cycles = EstimateSimulationCycles(max_num_qubits); context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( unfused_circuits.size(), num_cycles, DoWork); } diff --git a/tensorflow_quantum/core/ops/parse_context.cc b/tensorflow_quantum/core/ops/parse_context.cc index 6f6b1a0a1..122c637b6 100644 --- a/tensorflow_quantum/core/ops/parse_context.cc +++ b/tensorflow_quantum/core/ops/parse_context.cc @@ -55,6 +55,36 @@ Status ParseProto(const std::string& text, T* proto) { "Unparseable proto: " + text); } +// Ensures prior parallel parsing succeeded (so unresolved -1 sentinels cannot +// convert to large unsigned shift counts) and verifies every qubit count is in +// [0, max_num_qubits]. +Status ValidateNumQubits(const OpKernelContext* context, + const std::vector& num_qubits, + const int max_num_qubits) { + if (!context->status().ok()) { + return context->status(); + } + if (max_num_qubits < 0) { + return Status(static_cast( + absl::StatusCode::kInvalidArgument), + absl::StrCat("max_num_qubits must be non-negative. Got ", + max_num_qubits, ".")); + } + for (const int n : num_qubits) { + if (n < 0 || n > max_num_qubits) { + // Cast to unsigned when formatting so counts above INT_MAX that wrapped + // on conversion from ResolveQubitIds's unsigned int print accurately. + return Status( + static_cast( + absl::StatusCode::kInvalidArgument), + absl::StrCat("Circuit contains ", static_cast(n), + " qubits, which exceeds the maximum of ", max_num_qubits, + ".")); + } + } + return ::tensorflow::Status(); +} + } // namespace Status ParsePrograms(OpKernelContext* context, const std::string& input_name, @@ -155,7 +185,8 @@ Status GetProgramsAndNumQubits( OpKernelContext* context, std::vector* programs, std::vector* num_qubits, std::vector>* p_sums /*=nullptr*/, - bool swap_endianness /*=false*/) { + bool swap_endianness /*=false*/, + int max_num_qubits /*=kMaxStateVectorQubits*/) { // 1. Parse input programs // 2. (Optional) Parse input PauliSums // 3. Convert GridQubit locations to integers. @@ -202,13 +233,14 @@ Status GetProgramsAndNumQubits( context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( num_qubits->size(), cycle_estimate, DoWork); - return ::tensorflow::Status(); + return ValidateNumQubits(context, *num_qubits, max_num_qubits); } tensorflow::Status GetProgramsAndNumQubits( OpKernelContext* context, std::vector* programs, std::vector* num_qubits, - std::vector>* other_programs) { + std::vector>* other_programs, + int max_num_qubits /*=kMaxStateVectorQubits*/) { // 1. Parse input programs // 2. Parse other_programs // 3. Convert GridQubit locations to integers and ensure exact matching. @@ -247,7 +279,7 @@ tensorflow::Status GetProgramsAndNumQubits( context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( num_qubits->size(), cycle_estimate, DoWork); - return ::tensorflow::Status(); + return ValidateNumQubits(context, *num_qubits, max_num_qubits); } Status GetPauliSums(OpKernelContext* context, diff --git a/tensorflow_quantum/core/ops/parse_context.h b/tensorflow_quantum/core/ops/parse_context.h index 21257169a..d22f069e9 100644 --- a/tensorflow_quantum/core/ops/parse_context.h +++ b/tensorflow_quantum/core/ops/parse_context.h @@ -59,24 +59,51 @@ tensorflow::Status GetProgramsAndProgramsToAppend( // of the parameter (for forward computation). typedef absl::flat_hash_map> SymbolMap; -// Parses Cirq Program protos out of the 'circuit_specs' input Tensor. Also -// resolves the QubitIds inside of the Program. Optionally will resolve the -// QubitIds found in programs into PauliSums such that they are consistent -// and correct with the original programs. +// Upper bounds on circuit qubit counts accepted by simulation ops, derived from +// a 256 TiB (2^48-byte) classical memory ceiling and a 1,000,000-qubit circuit +// limit: +// - Dense state-vector ops store 2^n complex amplitudes (8 * 2^n bytes +// per state vector): at n = 43 a single vector takes 64 TiB, 2-buffer ops +// (batch-1 state output + workspace, expectation, inner product) take +// 128 TiB, and 3-buffer large-n gradient ops take 192 TiB. At n = 44 +// (128 TiB per vector), 3-buffer ops require 384 TiB and 2-buffer ops hit +// 256 TiB with zero headroom. +// - Dense unitary ops store 2^n x 2^n complex entries (8 * 2^(2n) bytes +// per matrix): at n = 21 each matrix takes 32 TiB (64 TiB across workspace +// and batch-1 output), whereas n = 22 (128 TiB per matrix) hits 256 TiB with +// zero headroom. +// - 1D MPS simulation scales linearly with n up to the 1,000,000-qubit circuit +// limit. +// Enforcing these bounds during input parsing prevents undefined behavior in +// `1 << n` shifts and TensorShape CHECK-failures on unsimulatable circuits. +inline constexpr int kMaxStateVectorQubits = 43; +inline constexpr int kMaxUnitaryQubits = 21; +inline constexpr int kMaxMPSQubits = 1000000; +static_assert(kMaxStateVectorQubits >= 0 && kMaxStateVectorQubits < 63, + "kMaxStateVectorQubits must keep (int64_t{1} << n) valid."); +static_assert(kMaxUnitaryQubits >= 0 && 2 * kMaxUnitaryQubits < 63, + "kMaxUnitaryQubits must keep (int64_t{1} << (2 * n)) valid."); +static_assert(kMaxMPSQubits >= 0, "kMaxMPSQubits must be non-negative."); + +// Parses Cirq Program protos out of the 'programs' input tensor, resolves +// QubitIds inside each Program (and optionally PauliSums), and verifies that +// `max_num_qubits >= 0` and every circuit's qubit count is in +// [0, max_num_qubits]. tensorflow::Status GetProgramsAndNumQubits( tensorflow::OpKernelContext* context, std::vector* programs, std::vector* num_qubits, std::vector>* p_sums = nullptr, - bool swap_endianness = false); + bool swap_endianness = false, int max_num_qubits = kMaxStateVectorQubits); -// Parses Cirq Program protos out of the 'circuit_specs' input Tensor. Also -// resolves the QubitIds inside of the Program. This override also parses and -// resolves other_programs. Ensuring all qubits found in programs[i] are also -// found in all programs[i][j] for all j. +// Parses Cirq Program protos out of the 'programs' and 'other_programs' input +// tensors, resolves QubitIds ensuring exact qubit matching across paired +// programs, and verifies that `max_num_qubits >= 0` and every circuit's qubit +// count is in [0, max_num_qubits]. tensorflow::Status GetProgramsAndNumQubits( tensorflow::OpKernelContext* context, std::vector* programs, std::vector* num_qubits, - std::vector>* other_programs); + std::vector>* other_programs, + int max_num_qubits = kMaxStateVectorQubits); // Parses PauliSum protos out of the 'pauli_sums' input tensor. Note this // function does NOT resolve QubitID's as any paulisum needs a reference diff --git a/tensorflow_quantum/core/ops/tfq_calculate_unitary_op.cc b/tensorflow_quantum/core/ops/tfq_calculate_unitary_op.cc index 8fe306390..915733e3f 100644 --- a/tensorflow_quantum/core/ops/tfq_calculate_unitary_op.cc +++ b/tensorflow_quantum/core/ops/tfq_calculate_unitary_op.cc @@ -13,6 +13,7 @@ See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ +#include #include #include "../qsim/lib/circuit.h" @@ -52,7 +53,9 @@ class TfqCalculateUnitaryOp : public tensorflow::OpKernel { std::vector programs; std::vector num_qubits; OP_REQUIRES_OK(context, - GetProgramsAndNumQubits(context, &programs, &num_qubits)); + GetProgramsAndNumQubits( + context, &programs, &num_qubits, /*p_sums=*/nullptr, + /*swap_endianness=*/false, kMaxUnitaryQubits)); // Parse symbol maps for parameter resolution in the circuits. std::vector maps; @@ -94,10 +97,11 @@ class TfqCalculateUnitaryOp : public tensorflow::OpKernel { // TODO(pmassey): Investigate creating a matrix that isn't just the maximum // required size. const size_t output_dim_size = maps.size(); + const int64_t dim = int64_t{1} << max_num_qubits; tensorflow::TensorShape output_shape; output_shape.AddDim(output_dim_size); - output_shape.AddDim(uint64_t(1) << max_num_qubits); - output_shape.AddDim(uint64_t(1) << max_num_qubits); + OP_REQUIRES_OK(context, output_shape.AddDimWithStatus(dim)); + OP_REQUIRES_OK(context, output_shape.AddDimWithStatus(dim)); tensorflow::Tensor *output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output)); diff --git a/tensorflow_quantum/core/ops/tfq_simulate_state_op.cc b/tensorflow_quantum/core/ops/tfq_simulate_state_op.cc index e483e65ae..af0231449 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_state_op.cc +++ b/tensorflow_quantum/core/ops/tfq_simulate_state_op.cc @@ -13,6 +13,7 @@ See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ +#include #include #include "../qsim/lib/circuit.h" @@ -95,7 +96,8 @@ class TfqSimulateStateOp : public tensorflow::OpKernel { const size_t output_dim_size = maps.size(); tensorflow::TensorShape output_shape; output_shape.AddDim(output_dim_size); - output_shape.AddDim(uint64_t(1) << max_num_qubits); + OP_REQUIRES_OK(context, + output_shape.AddDimWithStatus(int64_t{1} << max_num_qubits)); tensorflow::Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output)); diff --git a/tensorflow_quantum/core/ops/tfq_simulate_utils.h b/tensorflow_quantum/core/ops/tfq_simulate_utils.h index 935563d81..12e22b261 100644 --- a/tensorflow_quantum/core/ops/tfq_simulate_utils.h +++ b/tensorflow_quantum/core/ops/tfq_simulate_utils.h @@ -16,6 +16,10 @@ limitations under the License. #ifndef TFQ_CORE_OPS_TFQ_SIMULATE_UTILS_H_ #define TFQ_CORE_OPS_TFQ_SIMULATE_UTILS_H_ +#include +#include +#include + #include "tensorflow/core/framework/op_kernel.h" namespace tfq { @@ -25,6 +29,19 @@ namespace tfq { // CPU worker threads are unavailable or non-positive. int GetBlockSize(tensorflow::OpKernelContext* context, const int output_size); +// Estimates per-item CPU cycles for ParallelFor when simulating circuits of up +// to `max_num_qubits` qubits, capping the shift so the result fits in signed +// int64_t (values near that limit already saturate thread scheduling). +inline constexpr int64_t EstimateSimulationCycles(uint64_t max_num_qubits) { + constexpr int64_t kCycleMultiplier = 200; + constexpr uint64_t kMaxCycleShift = 55; + static_assert(kCycleMultiplier <= + (std::numeric_limits::max() >> kMaxCycleShift), + "Cycle estimate overflows int64_t."); + return kCycleMultiplier * + (int64_t{1} << std::min(max_num_qubits, kMaxCycleShift)); +} + } // namespace tfq #endif // TFQ_CORE_OPS_TFQ_SIMULATE_UTILS_H_ diff --git a/tensorflow_quantum/core/src/BUILD b/tensorflow_quantum/core/src/BUILD index 0f8d6b078..d6239153e 100644 --- a/tensorflow_quantum/core/src/BUILD +++ b/tensorflow_quantum/core/src/BUILD @@ -71,6 +71,7 @@ cc_library( "@com_google_absl//absl/container:flat_hash_map", "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", "@local_config_tf//:libtensorflow_framework", "@local_config_tf//:tf_header_lib", "@qsim//lib:channel", @@ -116,6 +117,7 @@ cc_library( "@com_google_absl//absl/container:inlined_vector", # unclear why needed. "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", "@local_config_tf//:libtensorflow_framework", "@local_config_tf//:tf_header_lib", "@qsim//lib:qsim_lib", diff --git a/tensorflow_quantum/core/src/circuit_parser_qsim.cc b/tensorflow_quantum/core/src/circuit_parser_qsim.cc index 6c6ed8d3f..dff82e44a 100644 --- a/tensorflow_quantum/core/src/circuit_parser_qsim.cc +++ b/tensorflow_quantum/core/src/circuit_parser_qsim.cc @@ -17,6 +17,7 @@ limitations under the License. #include #include +#include #include #include @@ -194,6 +195,16 @@ inline Status OptionalInsertControls(const Operation& op, if (control_qubits.empty()) { return ::tensorflow::Status(); } + // qsim::MakeControlledGate accumulates gate.cmask using `(val & 1) << i` + // on `unsigned int`, which invokes undefined behavior for i >= width. + constexpr size_t kMaxControlQubits = + std::min(std::numeric_limits::digits, 64); + if (control_qubits.size() > kMaxControlQubits) { + return Status( + absl::StatusCode::kInvalidArgument, + absl::StrCat("Controlled gate supports at most ", kMaxControlQubits, + " control qubits, got ", control_qubits.size(), ".")); + } // qsim's index arithmetic assumes that the control qubits of a gate are // distinct from each other and from its target qubits. for (size_t i = 0; i < control_qubits.size(); i++) { diff --git a/tensorflow_quantum/core/src/util_qsim.h b/tensorflow_quantum/core/src/util_qsim.h index fc2461acf..852ddb256 100644 --- a/tensorflow_quantum/core/src/util_qsim.h +++ b/tensorflow_quantum/core/src/util_qsim.h @@ -28,6 +28,8 @@ limitations under the License. #include "../qsim/lib/gate_appl.h" #include "../qsim/lib/gates_cirq.h" #include "../qsim/lib/matrix.h" +#include "absl/strings/numbers.h" +#include "absl/strings/str_cat.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/random/simple_philox.h" @@ -206,6 +208,13 @@ tensorflow::Status ComputeSampledExpectationQsim( if (num_samples == 0) { return ::tensorflow::Status(); } + const unsigned int num_qubits = state.num_qubits(); + if (num_qubits > 64) { + return tensorflow::Status( + absl::StatusCode::kInvalidArgument, + absl::StrCat("Sampled expectation supports at most 64 qubits. Got ", + num_qubits, ".")); + } // apply the gates of the pauliterms to a copy of the state vector // and add up expectation value term by term. tensorflow::Status status = ::tensorflow::Status(); @@ -238,21 +247,18 @@ tensorflow::Status ComputeSampledExpectationQsim( std::vector state_samples = ss.Sample(scratch, num_samples, random_source.Rand32()); - // Find qubits on which to measure parity - std::vector parity_bits; + // Compute the bitmask of qubits on which to measure parity (little-endian). + uint64_t mask = 0; for (const tfq::proto::PauliQubitPair& pair : term.paulis()) { unsigned int location; - // GridQubit id should be parsed down to integer at this upstream - // so it is safe to just use atoi. - (void)absl::SimpleAtoi(pair.qubit_id(), &location); - // Parity functions use little-endian indexing - parity_bits.push_back(state.num_qubits() - location - 1); - } - - // Compute the BitMask. - uint64_t mask = 0; - for (const unsigned int parity_bit : parity_bits) { - mask |= uint64_t(1) << uint64_t(parity_bit); + if (!absl::SimpleAtoi(pair.qubit_id(), &location) || + location >= num_qubits) { + return tensorflow::Status( + absl::StatusCode::kInvalidArgument, + absl::StrCat("Invalid qubit id in Pauli term: '", pair.qubit_id(), + "'. Expected an integer in [0, ", num_qubits, ").")); + } + mask |= uint64_t{1} << (num_qubits - location - 1); } // Compute the running parity.