Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
Expand Down Expand Up @@ -214,8 +215,7 @@ class TfqSimulateMPS1DExpectationOp : public tensorflow::OpKernel {
}
};

const int64_t num_cycles =
200 * (int64_t(1) << static_cast<int64_t>(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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -84,9 +85,9 @@ class TfqSimulateMPS1DSampledExpectationOp : public tensorflow::OpKernel {
std::vector<Program> programs;
std::vector<int> num_qubits;
std::vector<std::vector<PauliSum>> 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<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
Expand Down Expand Up @@ -254,8 +255,7 @@ class TfqSimulateMPS1DSampledExpectationOp : public tensorflow::OpKernel {
}
};

const int64_t num_cycles =
200 * (int64_t(1) << static_cast<int64_t>(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);
Expand Down
14 changes: 8 additions & 6 deletions tensorflow_quantum/core/ops/math_ops/tfq_simulate_1d_samples.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ limitations under the License.

#include <stdlib.h>

#include <cstdint>
#include <string>

#include "../qsim/lib/circuit.h"
Expand All @@ -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"
Expand Down Expand Up @@ -65,8 +67,9 @@ class TfqSimulateMPS1DSamplesOp : public tensorflow::OpKernel {
std::vector<Program> programs;
std::vector<int> 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<SymbolMap> maps;
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -204,8 +207,7 @@ class TfqSimulateMPS1DSamplesOp : public tensorflow::OpKernel {
}
};

const int64_t num_cycles =
200 * (int64_t(1) << static_cast<int64_t>(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);
}
Expand Down
40 changes: 36 additions & 4 deletions tensorflow_quantum/core/ops/parse_context.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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<int>& num_qubits,
const int max_num_qubits) {
if (!context->status().ok()) {
return context->status();
}
if (max_num_qubits < 0) {
return Status(static_cast<tensorflow::errors::Code>(
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<tensorflow::errors::Code>(
absl::StatusCode::kInvalidArgument),
absl::StrCat("Circuit contains ", static_cast<unsigned int>(n),
" qubits, which exceeds the maximum of ", max_num_qubits,
"."));
}
}
return ::tensorflow::Status();
}

} // namespace

Status ParsePrograms(OpKernelContext* context, const std::string& input_name,
Expand Down Expand Up @@ -155,7 +185,8 @@ Status GetProgramsAndNumQubits(
OpKernelContext* context, std::vector<Program>* programs,
std::vector<int>* num_qubits,
std::vector<std::vector<PauliSum>>* 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.
Expand Down Expand Up @@ -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<Program>* programs,
std::vector<int>* num_qubits,
std::vector<std::vector<Program>>* other_programs) {
std::vector<std::vector<Program>>* 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.
Expand Down Expand Up @@ -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,
Expand Down
47 changes: 37 additions & 10 deletions tensorflow_quantum/core/ops/parse_context.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,24 +59,51 @@ tensorflow::Status GetProgramsAndProgramsToAppend(
// of the parameter (for forward computation).
typedef absl::flat_hash_map<std::string, std::pair<int, float>> 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<float> 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<float> 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<tfq::proto::Program>* programs, std::vector<int>* num_qubits,
std::vector<std::vector<tfq::proto::PauliSum>>* 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<tfq::proto::Program>* programs, std::vector<int>* num_qubits,
std::vector<std::vector<tfq::proto::Program>>* other_programs);
std::vector<std::vector<tfq::proto::Program>>* 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
Expand Down
10 changes: 7 additions & 3 deletions tensorflow_quantum/core/ops/tfq_calculate_unitary_op.cc
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <cstdint>
#include <string>

#include "../qsim/lib/circuit.h"
Expand Down Expand Up @@ -52,7 +53,9 @@ class TfqCalculateUnitaryOp : public tensorflow::OpKernel {
std::vector<Program> programs;
std::vector<int> 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<SymbolMap> maps;
Expand Down Expand Up @@ -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));
Expand Down
4 changes: 3 additions & 1 deletion tensorflow_quantum/core/ops/tfq_simulate_state_op.cc
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <cstdint>
#include <string>

#include "../qsim/lib/circuit.h"
Expand Down Expand Up @@ -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));
Expand Down
17 changes: 17 additions & 0 deletions tensorflow_quantum/core/ops/tfq_simulate_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 <algorithm>
#include <cstdint>
#include <limits>

#include "tensorflow/core/framework/op_kernel.h"

namespace tfq {
Expand All @@ -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<int64_t>::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_
2 changes: 2 additions & 0 deletions tensorflow_quantum/core/src/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
11 changes: 11 additions & 0 deletions tensorflow_quantum/core/src/circuit_parser_qsim.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.

#include <algorithm>
#include <initializer_list>
#include <limits>
#include <string>
#include <vector>

Expand Down Expand Up @@ -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<size_t>(std::numeric_limits<unsigned int>::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++) {
Expand Down
Loading