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
6 changes: 4 additions & 2 deletions recirq/contextuality/ghz_game_2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@

This module provides a complete pipeline for benchmarking the fidelity of
Greenberger-Horne-Zeilinger (GHZ) states on a 2D grid of qubits.
This is the code used for the implementation of the GHZ game detailed in arxiv.2512.02284
This is the code used for the implementation of the GHZ game detailed in
Google Quantum AI and Collaborators, Science 394, 870-874 (2026)
(https://doi.org/10.1126/science.aec3042).

The GHZ Game:
The GHZ game is a non-communication game that can be won against classical
Expand Down Expand Up @@ -248,7 +250,7 @@ def _generate_experiment_circuits(
add_dd_and_align_right: bool = True,
rng_or_seed: int | np.random.Generator | None = None,
) -> tuple[list[cirq.Circuit], list[dict[str, Any]]]:
"""Generates a master list of all individual circuits required for the batch run,
"""Generates a primary list of all individual circuits required for the batch run,
including GHZ game trials (that are same for X-stabilizer) and Z-stabilizer
circuits for each base circuit.

Expand Down
47 changes: 28 additions & 19 deletions recirq/contextuality/kochen_specker.py
Comment thread
mhucka marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.

"""Bell-Kochen-Specker (BKS) state-independent contextuality experiment.

This module implements continuous quantum nondemolition (QND) measurements of
magic square contexts to test the Bell-Kochen-Specker inequality, as described in
Google Quantum AI and Collaborators, Science 394, 870-874 (2026)
(https://doi.org/10.1126/science.aec3042).
"""

from __future__ import annotations
import warnings
import collections
Expand Down Expand Up @@ -42,7 +50,7 @@ class MagicSquare:
"""Represents a MagicSquare.

A MagicSquare is a 3x3 grid of two-qubit Pauli operators used to demonstrate quantum
contextuality, specifically the Kochen-Specker theorem.
contextuality, specifically the Bell-Kochen-Specker (BKS) theorem.

The operators in each row and each column mutually commute.
The product of operators in each row is +I.
Expand Down Expand Up @@ -114,9 +122,10 @@ def kochen_specker_expt(
qnd_strategy: QndStrategy = "map_all_paulis_to_ancilla",
virtual_z_half_turns: float = 0.0,
) -> MagicSquareExperiment:
"""Builds a Kochen-Specker experiment, which measures state-independent contextuality.
"""Builds a Bell-Kochen-Specker (BKS) experiment, which measures state-independent

See https://arxiv.org/pdf/2512.02284 for more details.
contextuality. See Google Quantum AI and Collaborators, Science 394, 870-874 (2026)
(https://doi.org/10.1126/science.aec3042) for more details.

Args:
q0: First data qubit.
Expand Down Expand Up @@ -241,7 +250,7 @@ class MagicSquareResult:
"""The results of a `MagicSquareExperiment`.

This class holds the `cirq.Result` from running the experiment and provides
methods to analyze the results, such as estimating the Kochen-Specker value (chi)
methods to analyze the results, such as estimating the Bell-Kochen-Specker value (chi_BKS)
and other statistical properties.

Attributes:
Expand All @@ -253,10 +262,10 @@ class MagicSquareResult:
result: cirq.Result

def estimate_chi(self) -> tuple[float, float]:
"""Estimate chi out of the 6 parity averages.
"""Estimate chi_BKS out of the 6 parity averages.

This method takes the cirq.Result output by the Kochen-Specker
experiment and returns an estimate of chi. We assume that the length of the
This method takes the cirq.Result output by the Bell-Kochen-Specker
experiment and returns an estimate of chi_BKS. We assume that the length of the
circuit ran was long enough to contain at least one instance of each of the
six 3-observable parities, e.g. (1X X1 XX).
"""
Expand All @@ -269,7 +278,7 @@ def squeezed_records(self) -> Mapping[str, np.ndarray]:
"""Squeeze the ResultDict.records.values() ndarrays to 2D.

Since there is only one qubit per measurement key in our experiments, the third index is
a dummy index. This helps us process data more easily.
a placeholder index. This helps us process data more easily.
"""
squeezed_records = {
pauli_key: np.squeeze(records_values)
Expand Down Expand Up @@ -366,11 +375,11 @@ def estimate_coincidences(
This dictionary is useful for debugging purposes.
Each PauliString can show up in a circuit as part of a context that
corresponds to either a row or a column. For the compatible pairs of
measurements in a Kochen Specker circuit (and only the compatible pairs),
this dictionary is a mapping between each PauliString in the MagicSquare to a
list of tuples containing whether each tuples of previous context, where each
tuple contains the axis context corresponds to a row or column context. For the
example we are analysing, this would give:
measurements in a Bell-Kochen-Specker circuit (and only the compatible pairs),
this dictionary maps each Pauli operator in the MagicSquare to a list of
`(previous_axis, current_axis)` tuples indicating whether each measurement in
the pair came from a `'row'` or `'col'` context. For the example we are
analysing, this would give:

pauli_to_compatible_contexts[ZZ] = [('row', 'col'), ('col', 'col')]
"""
Expand Down Expand Up @@ -896,11 +905,11 @@ def estimate_chi(
records: Mapping[str, np.ndarray],
contexts: Mapping[tuple[Axis, int], Sequence[PauliKey]],
) -> tuple[float, float]:
"""Estimate chi out of the 6 parity averages.
"""Estimate chi_BKS out of the 6 parity averages.

This method takes the output of the Kochen-Specker experiment and returns an estimate of chi.
We assume that the length of the circuit ran was long enough to contain at least one instance of
each of the six 3-observable parities, e.g. (1X X1 XX).
This method takes the output of the Bell-Kochen-Specker experiment and returns an estimate of
chi_BKS. We assume that the length of the circuit ran was long enough to contain at least one
instance of each of the six 3-observable parities, e.g. (1X X1 XX).
"""
context_averages = estimate_parities(records, contexts)

Expand All @@ -919,7 +928,7 @@ def get_parities_from_single_context_experiments(
) -> dict[tuple[Axis, int], tuple[float, float]]:
"""Get the parities (with uncertainties) for each context.

Assumes that we ran 6 single-context Kochen Specker experiments. Returns a mapping from
Assumes that we ran 6 single-context Bell-Kochen-Specker experiments. Returns a mapping from
context to their parities (with uncertainties).

Args:
Expand All @@ -946,7 +955,7 @@ def get_parities_from_single_context_experiments(
def get_chi_from_single_context_experiment(
context_to_parities: dict[tuple[Axis, int], tuple[float, float]],
) -> tuple[float, float]:
"""Estimate chi (with uncertainty) from a context_to_parities mapping."""
"""Estimate chi_BKS (with uncertainty) from a context_to_parities mapping."""
chi_mean = sum(
avg * (1 if axis == "row" else -1)
for (axis, _idx), (avg, _unc) in context_to_parities.items()
Expand Down
5 changes: 4 additions & 1 deletion recirq/contextuality/magic_square_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,13 @@
non-local correlations. The game serves as a "proof" of quantum contextuality, demonstrating that
the outcome of a measurement depends on the other measurements performed alongside it (its context).
In a classical world, each cell in the square would have a fixed, pre-existing value regardless
of whether it's being measured as part of a row or a column. However, the Mermin-Peres game
of whether it's being measured as part of a row or a column. However, the magic square game
proves that these values cannot exist independently of their measurement context,
as the algebraic requirements for the rows and columns are mathematically impossible to satisfy
simultaneously with fixed values.

See Google Quantum AI and Collaborators, Science 394, 870-874 (2026)
(https://doi.org/10.1126/science.aec3042).
"""

import dataclasses
Expand Down
54 changes: 27 additions & 27 deletions recirq/contextuality/shallow_circuits_experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
"""Builds and runs experiment for finding hidden linear functions (HLF) with shallow circuits.

This module provides the fundamental building blocks for generating, executing,
and analyzing results for finding HLF with shallow circuits experiment,
as described in https://arxiv.org/abs/2512.02284.
and analyzing results for the shallow-circuits HLF experiment described in
Google Quantum AI and Collaborators, Science 394, 870-874 (2026)
(https://doi.org/10.1126/science.aec3042).
"""

import math
Expand Down Expand Up @@ -324,12 +325,12 @@ class ShallowCircuitResults:
Attributes:
_probability_of_valid_outcomes: Dict mapping `n_qubits` to a list of fidelity scores
after matching the outcome of the experiment to the ideal outcome.
_effective_layers: Dict mapping `n_qubits` to a list of effective layer
counts. Calculated as `4 / probability`, this estimates the
equivalent number of noisy layers the hardware executed.
_classical_layers: Dict mapping `n_qubits` to the classical degrees of
freedom (DOF) for each circuit. Represents the problem complexity,
calculated as log2(total_dof = num_qubits + total possible CZ gates).
_classical_layers: Dict mapping `n_qubits` to the conjectured lower bound on classical
circuit depth, calculated as `ceil(log2(total_dof))` where
`total_dof = num_qubits + total possible CZ gates`.
_classical_bound: Dict mapping `n_qubits` to the conjectured classical
success-probability threshold (`min(1.0, 4 / classical_layers)`, Fig. 4B in the
paper; capped at `1.0` when `classical_layers <= 4`).
"""

def __init__(
Expand All @@ -346,8 +347,8 @@ def __init__(

# Attribute
self._probability_of_valid_outcomes: dict[int, list[float]] | None = None
self._effective_layers: dict[int, list[float]] | None = None
self._classical_layers: dict[int, int] | None = None
self._classical_bound: dict[int, float] | None = None

@staticmethod
def _preprocess_stim_circuit(circuit: stim.Circuit) -> tuple[stim.TableauSimulator, list[int]]:
Expand Down Expand Up @@ -393,15 +394,11 @@ def _is_output_possible(
return True

def _analyze(self) -> None:
"""Analyzes experiment results to compute the probability of valid outcomes.

Returns:
A dictionary mapping each qubit count to a list of scores (probabilities).
"""
"""Analyzes experiment results to compute valid-outcome probabilities and bounds."""

scores: dict[int, list[float]] = defaultdict(list)
eff_layers: dict[int, list[float]] = defaultdict(list)
classical_layers: dict[int, int] = {}
classical_bound: dict[int, float] = {}

for i, measurements in enumerate(tqdm(self.measurements, desc="Analyzing Circuits")):
n_qubits = self.n_qubits_map[i]
Expand All @@ -412,16 +409,18 @@ def _analyze(self) -> None:

score = np.mean([self._is_output_possible(sim, meas_qubits, m) for m in measurements])
scores[n_qubits].append(float(score))
if score > 0:
eff_layers[n_qubits].append(4 / float(score))

for num_qubits in self.total_dof.keys():
classical_layers[num_qubits] = math.ceil(np.log2(self.total_dof[num_qubits]))
n_classical = math.ceil(np.log2(self.total_dof[num_qubits]))
classical_layers[num_qubits] = n_classical
classical_bound[num_qubits] = (
min(1.0, 4.0 / n_classical) if n_classical > 0 else 1.0
)

print("Analysis complete.")
self._probability_of_valid_outcomes = scores
self._effective_layers = eff_layers
self._classical_layers = classical_layers
self._classical_bound = classical_bound

@property
def probability_of_valid_outcomes(self) -> dict[int, list[float]] | None:
Expand All @@ -430,16 +429,17 @@ def probability_of_valid_outcomes(self) -> dict[int, list[float]] | None:
self._analyze()
return self._probability_of_valid_outcomes

@property
def effective_layers(self) -> dict[int, list[float]] | None:
"""Effective number of layers required to solve the HLF problem for each circuit."""
if self._effective_layers is None:
self._analyze()
return self._effective_layers

@property
def classical_layers(self) -> dict[int, int] | None:
"""Lower bound on number of classical layers required to solve the HLF problem."""
"""Conjectured lower bound on classical circuit depth required to solve the HLF problem."""
if self._classical_layers is None:
self._analyze()
return self._classical_layers

@property
def classical_bound(self) -> dict[int, float]:
"""Conjectured classical success-probability threshold (min(1, 4 / classical_layers))."""
if self._classical_bound is None:
self._analyze()
assert self._classical_bound is not None
return self._classical_bound
41 changes: 32 additions & 9 deletions recirq/contextuality/shallow_circuits_experiment_test.py
Comment thread
mhucka marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ def test_experiment():
on a perfect simulator. It verifies that the results match theoretical
expectations for a noiseless execution:
- The probability of valid outcomes should be 1.0.
- The effective number of layers should be 4.0.
- The classical complexity should be greater than the effective layers.
- The conjectured classical bound should equal 4 / classical_layers.
- The valid-outcome probability should exceed the conjectured classical bound.
"""

n_qubits_list = np.arange(10, 15, 1)
Expand All @@ -108,17 +108,40 @@ def test_experiment():
results = hlf_experiment.run(sampler, n_repetitions)

probability_of_valid_outcomes = results.probability_of_valid_outcomes
effective_number_of_layers = results.effective_layers
classical_layers = results.classical_layers
classical_bound = results.classical_bound

# Running noiseless experiment, mean should be 1
assert (
classical_bound.keys()
== classical_layers.keys()
== probability_of_valid_outcomes.keys()
)
for key in probability_of_valid_outcomes.keys():
assert np.mean(probability_of_valid_outcomes[key]) == 1

# Running noiseless experiment, mean should be 4
for key in effective_number_of_layers.keys():
assert np.mean(effective_number_of_layers[key]) == 4

# Running noiseless experiment, classical layers should be more than the effective layers
# Conjectured classical probability threshold is 4 / classical_layers and below 1
for key in classical_layers.keys():
assert np.mean(effective_number_of_layers[key]) < classical_layers[key]
assert np.isclose(classical_bound[key], 4.0 / classical_layers[key])
assert np.mean(probability_of_valid_outcomes[key]) > classical_bound[key]
Comment thread
mhucka marked this conversation as resolved.
Resolved


def test_classical_bound_small_dof_and_lazy_init():
"""Tests small-DOF clamping (including total_dof=1) and lazy classical_bound init."""
results = hlf.ShallowCircuitResults(
circuits=[],
measurements=[],
n_qubits_map=[],
total_dof={1: 1, 4: 8, 7: 16, 9: 21},
)

# Access classical_bound first to exercise its lazy-initialization branch.
classical_bound = results.classical_bound
classical_layers = results.classical_layers

assert classical_bound.keys() == classical_layers.keys() == {1, 4, 7, 9}
assert classical_layers == {1: 0, 4: 3, 7: 4, 9: 5}
assert classical_bound[1] == 1.0
assert classical_bound[4] == 1.0
assert classical_bound[7] == 1.0
assert np.isclose(classical_bound[9], 0.8)
Loading