Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse context with ProjectorSums #642

Open
wants to merge 26 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
41d4162
Parsei context with ProjectorSums
tonybruguier Nov 19, 2021
7a165a9
nits
tonybruguier Nov 19, 2021
2a04237
nits
tonybruguier Nov 19, 2021
eb373ed
Intermediate
tonybruguier Nov 21, 2021
a92bff7
intermediate
tonybruguier Nov 21, 2021
ba02b65
intermediate
tonybruguier Nov 23, 2021
4b97fb6
intermediate
tonybruguier Nov 24, 2021
a41d28e
intermediate
tonybruguier Nov 26, 2021
3178de3
intermediate
tonybruguier Nov 26, 2021
af44e0a
intermediate
tonybruguier Nov 27, 2021
3571f16
Intermediate
tonybruguier Nov 28, 2021
db69d3c
format
tonybruguier Nov 28, 2021
61cedc2
Undo some line removals
tonybruguier Dec 3, 2021
5af5f53
Make projector optional
tonybruguier Dec 3, 2021
2f458ce
nit
tonybruguier Dec 3, 2021
7ca8ff0
nit
tonybruguier Dec 3, 2021
6cd4d81
Merge branch 'tfq_psum_op' of github.com:tonybruguier/quantum into tf…
tonybruguier Dec 3, 2021
d673912
longer timeouts for tests
tonybruguier Dec 4, 2021
68120a1
special casing
tonybruguier Dec 4, 2021
211a6b6
Merge branch 'master' of github.com:tensorflow/quantum into tfq_psum_op
tonybruguier Dec 10, 2021
da0bfba
Merge branch 'master' of github.com:tensorflow/quantum into tfq_psum_op
tonybruguier Dec 11, 2021
0037288
Merge branch 'master' of github.com:tensorflow/quantum into tfq_psum_op
tonybruguier Jan 6, 2022
4254f3a
nits
tonybruguier Jan 6, 2022
ba472d1
Merge branch 'master' of github.com:tensorflow/quantum into tfq_psum_op
tonybruguier Jan 20, 2022
814e571
Merge branch 'master' of github.com:tensorflow/quantum into tfq_psum_op
tonybruguier Jan 22, 2022
adb22a4
Attempt to fix build
tonybruguier Jan 22, 2022
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
15 changes: 10 additions & 5 deletions tensorflow_quantum/core/ops/batch_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
# be used end to end with engine. This current issue is that
# cirq.PauliSumCollector does not produce serializable gates for basis
# conversion.
class TFQPauliSumCollector(cirq.work.collector.Collector):
class TFQPauliProjectorSumCollector(cirq.work.collector.Collector):
"""Copy of cirq.PauliSumCollector with some fixes to work with engine."""

def __init__(self,
Expand Down Expand Up @@ -261,7 +261,7 @@ def batch_calculate_expectation(circuits, param_resolvers, ops, simulator):
if not isinstance(sub_list, (list, tuple, np.ndarray)):
raise TypeError('elements of ops must be type list.')
for x in sub_list:
if not isinstance(x, cirq.PauliSum):
if not isinstance(x, (cirq.PauliSum, cirq.ProjectorSum)):
raise TypeError('ops must contain only cirq.PauliSum objects.'
' Given: {}'.format(type(x)))

Expand All @@ -279,8 +279,13 @@ def batch_calculate_expectation(circuits, param_resolvers, ops, simulator):
sim_result = simulator.simulate(c, p)
for j, op in enumerate(op_row):
dm = sim_result.final_density_matrix
all_exp_vals[i][j] = op.expectation_from_density_matrix(
dm, qubit_order, check_preconditions=False)
if isinstance(op, cirq.PauliSum):
all_exp_vals[i][j] = op.expectation_from_density_matrix(
dm, qubit_order, check_preconditions=False)
else:
assert isinstance(op, cirq.ProjectorSum)
all_exp_vals[i][j] = op.expectation_from_density_matrix(
dm, qubit_order)
else:
# Valid observables always have real expectation values.
all_exp_vals[i] = np.real(
Expand Down Expand Up @@ -359,7 +364,7 @@ def batch_calculate_sampled_expectation(circuits, param_resolvers, ops,
continue
circuit = cirq.resolve_parameters(c, params)
for op_index, op in enumerate(ops[c_index]):
collector = TFQPauliSumCollector(
collector = TFQPauliProjectorSumCollector(
circuit, op, samples_per_term=n_samples[c_index][op_index])
collector.collect(sampler)
result = collector.estimated_energy().real
Expand Down
1 change: 0 additions & 1 deletion tensorflow_quantum/core/ops/math_ops/tfq_inner_product.cc
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ limitations under the License.
namespace tfq {

using ::tensorflow::Status;
using ::tfq::proto::PauliSum;
using ::tfq::proto::Program;

typedef qsim::Cirq::GateCirq<float> QsimGate;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ limitations under the License.
namespace tfq {

using ::tensorflow::Status;
using ::tfq::proto::PauliSum;
using ::tfq::proto::Program;

typedef qsim::Cirq::GateCirq<float> QsimGate;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class TfqSimulateMPS1DExpectationOp : public tensorflow::OpKernel {
// is resolved.
OP_REQUIRES_OK(context,
GetProgramsAndNumQubits(context, &programs, &num_qubits,
&pauli_sums, true));
&pauli_sums, nullptr, true));

std::vector<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class TfqSimulateMPS1DSampledExpectationOp : public tensorflow::OpKernel {
std::vector<std::vector<PauliSum>> pauli_sums;
OP_REQUIRES_OK(context,
GetProgramsAndNumQubits(context, &programs, &num_qubits,
&pauli_sums, true));
&pauli_sums, nullptr, true));

std::vector<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class TfqSimulateMPS1DSamplesOp : public tensorflow::OpKernel {
std::vector<int> num_qubits;
OP_REQUIRES_OK(context,
GetProgramsAndNumQubits(context, &programs, &num_qubits,
nullptr, true));
nullptr, nullptr, true));

// Parse symbol maps for parameter resolution in the circuits.
std::vector<SymbolMap> maps;
Expand Down
2 changes: 2 additions & 0 deletions tensorflow_quantum/core/ops/noise/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ py_library(

py_test(
name = "noisy_expectation_op_test",
timeout = "long",
srcs = ["noisy_expectation_op_test.py"],
python_version = "PY3",
deps = [
Expand All @@ -103,6 +104,7 @@ py_library(

py_test(
name = "noisy_sampled_expectation_op_test",
timeout = "long",
srcs = ["noisy_sampled_expectation_op_test.py"],
python_version = "PY3",
deps = [
Expand Down
19 changes: 17 additions & 2 deletions tensorflow_quantum/core/ops/noise/noisy_expectation_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,12 @@
NOISY_OP_MODULE = load_module(os.path.join("noise", "_tfq_noise_ops.so"))


def expectation(programs, symbol_names, symbol_values, pauli_sums, num_samples):
def expectation(programs,
symbol_names,
symbol_values,
pauli_sums,
num_samples,
projector_sums=None):
"""Calculate the analytic expectation values using monte-carlo trajectories.

Simulate the final state of `programs` given `symbol_values` are placed
Expand Down Expand Up @@ -88,11 +93,21 @@ def expectation(programs, symbol_names, symbol_values, pauli_sums, num_samples):
threads to TensorFlow. For best performance ensure that the
quantities in `num_samples` are a multiple of the number of
available threads.
projector_sums: `tf.Tensor` of strings with shape [batch_size, n_ops]
containing the string representation of the operators that will
be used on all of the circuits in the expectation calculations.
Returns:
`tf.Tensor` with shape [batch_size, n_ops] that holds the
expectation value for each circuit with each op applied to it
(after resolving the corresponding parameters in).
"""
# TODO(tonybruguier): Always supply a projector sum to this function and
# remove the special-casing below.
if projector_sums is None:
if len(pauli_sums.shape) == 1:
projector_sums = pauli_sums[0:0]
else:
projector_sums = pauli_sums[:, 0:0]
return NOISY_OP_MODULE.tfq_noisy_expectation(
programs, symbol_names, tf.cast(symbol_values, tf.float32), pauli_sums,
tf.cast(num_samples, dtype=tf.int32))
projector_sums, tf.cast(num_samples, dtype=tf.int32))
Loading