Class session

Class Documentation

class session

A session of the Qristal SDK.

Unnamed Group

using ibounds = const std::pair<size_t, size_t>

Bounds on session parameters

using dbounds = const std::pair<double, double>
ibounds random_circuit_depth_bounds = {0, 1000}
ibounds sn_bounds = {1, 1000000000}
ibounds qn_bounds = {1, 10000}
ibounds max_bond_bounds = {1, 50000}
ibounds initial_bond_bounds = {1, 50000}
ibounds max_kraus_bounds = {1, 50000}
ibounds initial_kraus_bounds = {1, 50000}
dbounds svd_cutoff_bounds = {0, 1e9}
dbounds svdj_tol_bounds = {0, 1.0}
ibounds svdj_max_sweeps_bounds = {1, 10000}

Unnamed Group

static const std::unordered_set<std::string_view> EMULATOR_BACKENDS

Sets of recognised values for string-type session parameters.

Emulator backends

static const std::unordered_set<std::string_view> NON_EMULATOR_BACKENDS

Non-emulator backends.

static const std::unordered_set<std::string_view> GPU_BACKENDS

Backends that support GPU execution.

static const std::unordered_set<std::string_view> NOISY_BACKENDS

Backends that support noise.

static const std::unordered_set<std::string_view> EXCLUSIVELY_NOISY_BACKENDS

Backends that only support noise, i.e. will not run with noise = false.

static const std::unordered_set<std::string_view> VALID_AER_SIM_TYPES

Valid AER simulator types.

static const std::unordered_map<std::string_view, size_t> MAX_QUBITS_ACCS

Recommended maximum qubit number for selected accelerator type.

static const std::unordered_set<std::string_view> VALID_NOISE_MITIGATIONS

Recognised noise mitigation strategies.

static const std::unordered_set<std::string_view> VALID_HARDWARE_PLACEMENTS

Valid placement strategies.

static const std::unordered_set<std::string_view> VALID_MEASURE_SAMPLING_OPTIONS

Valid measurement sampling options.

static const std::unordered_set<std::string_view> VALID_SVD_TYPE_OPTIONS

Valid singular value decomposition type options.

Public Functions

session()

Construct a new session object.

Some parameters are uninitialized, e.g., number of qubits (qn). These parameters can be set manually.

session(const bool msb)

Construct a new session object using a specific ordering for all_bitstring_counts_ and associated QML-relevant outputs.

Parameters:

msb – MSB flag. If true, use MSB to determine ordering of all_bitstring_counts_ all_bitstring_probabilities and all_bitstring_probability_gradients table; else use LSB.

template<typename CudaQKernel, typename ...Args>
inline std::function<void()> bind_args_to_cudaq_kernel(CudaQKernel &&in_kernel, Args&&... args)

Create fully specified input CUDAQ kernel from a parameterised kernel and some argument values at which to evaluate it.

Parameters:
  • in_kernel – Input CUDAQ kernel (templated callable returning void)

  • args – Concrete argument values with which to call the CUDAQ kernel

const std::map<std::vector<bool>, int> &results() const

Get the output measurement counts as a map.

Returns:

Measurement counts map

const std::map<std::vector<bool>, int> &results_native() const

Get the native output measurement counts as a map.

Beware: The native results are only stored separately, if a confusion or correction matrix was supplied to session, enabling automatic SPAM correction!

Returns:

Native measurement counts map

const std::vector<std::complex<double>> &state_vec() const

Get the full state vector (works with qpp and aer backends only!)

Returns:

Full complex state vector as std::vector<std::complex<double>>

const std::vector<int> &all_bitstring_counts() const

Get the output measurement counts as a vector.

Returns:

Measurement counts vector

const std::vector<double> &all_bitstring_probabilities() const

Get the output probabilities.

Returns:

Measurement probabilities vector

const std::vector<std::vector<double>> &all_bitstring_probability_gradients() const

Get the output probability gradients.

Returns:

Table of probability jacobians w.r.t. runtime parameters

std::string transpiled_circuit() const

Get the output transpiled circuit.

Returns:

Output transpiled circuit as an OpenQASM string.

std::string qobj() const

Get the output Aer QObj JSON string.

Returns:

QObj Json string

std::string qbjson() const

Get the output QB JSON string (QB hardware JSON POST payload)

Returns:

QB Json string.

std::map<int, int> one_qubit_gate_depths() const

Get the number of one-qubit gates applied to each individual qubit.

Returns:

Keys: qubit indices; values: number of one-qubit gates.

std::map<int, int> two_qubit_gate_depths() const

Get the number of two-qubit gates applied to each individual qubit.

Returns:

Keys: qubit indices; values: number of two-qubit gates.

std::map<int, double> timing_estimates() const

Get estimated circuit execution times on hardware.

Returns:

Estimated hardware runtimes, in ms. Keys: 0: Total time 1: Initialisation component 2: Gate (max. depth) component 3: Readout component 4: Total time (from classical simulation) 5: PC transfer to controller time

double z_op_expectation() const

Get the output expected value in the Z basis, from the shot counts observed.

Returns:

Expected value in the Z basis

void set_SPAM_confusion_matrix(Eigen::MatrixXd mat)

Set the SPAM correction matrix by providing an equivalent SPAM confusion matrix.

Eigen::MatrixXd get_SPAM_confusion_matrix() const

Retrieve an equivalent confusion matrix from the SPAM correction matrix.

void validate()

Validate the run i.e. ensure all configurations are set in a valid manner.

void run_with_SPAM(size_t n_shots = 0)

Execute a standard SPAM benchmark, and use the measured confusion matrix to automatically correct SPAM errors in a consecutive run()

Arguments:

Parameters:

n_shots – : The number of shots to be used for the SPAM benchmark. Defaults to 0, taking the same number of shots as set in sns_.

std::shared_ptr<async_job_handle> run()

Execute all quantum tasks Returns a job handle if the job is posted to a remote accelerator (e.g. AWS Braket). Otherwise, returns null if this function completes the run locally.

void cancel_run()

Cancel any in-flight asynchronous execution of run()

size_t bitstring_index(const std::vector<bool> &bitvec)

Returns the (base-10) integer vector index for the probabilities/ counts vector, corresponding to a bitstring.

Parameters:

bitvec – The bit-vector to be converted to the vector index

std::vector<bool> draw_shot()

Randomly draw (and remove) a single shot from the results map.

Public Members

std::string infile

Full path to an input QASM source file.

std::string instring

An input QASM source string.

std::shared_ptr<xacc::CompositeInstruction> irtarget

Provides a xacc::CompositeInstruction IR target.

If the IR target is provided instead of QASM strings or files, the QASM compilation step will be skipped. The IR target can be manually constructed by building the IR tree using XACC.

std::vector<size_t> gpu_device_ids

List of GPU device numbers.

std::function<void()> cudaq_kernel

A CUDAQ kernel to execute, with any free parameters already fully specified.

std::string include_qb = QRISTAL_DIR + "/include/qristal/core/qristal.inc"

Path to an OpenQASM file to include at the beginning of every circuit Contains custom Quantum Brilliance gate definitions.

std::vector<double> circuit_parameters

Vector of circuit parameters to use for runtime substitution.

bool calc_gradients = false

Whether or not gradients will be calculated for parametrized circuits.

bool calc_all_bitstring_counts = false

Whether or not a non-compact output counts vector will be calculated.

std::string remote_backend_database_path = QRISTAL_DIR + "/remote_backends.yaml"

The path to the remote backend database yaml file. The path to a YAML file with configuration data for remote backends (including hardware).

std::string acc = "qpp"

Chosen backend accelerator.

std::string aer_sim_type = "statevector"

The simulator type for the AER backend accelerator.

size_t aer_omp_threads = 0

The maximum number of OpenMP threads that AER can use.

size_t random_circuit_depth = 0

The depth of random circuit to be generated.

circuit_language input_language = circuit_language::OpenQASM

The frontend language in which the input circuit is written.

bool noise = false

Enable noisy simulation.

std::string noise_mitigation

A noise mitigation method to apply.

Eigen::MatrixXd SPAM_correction_matrix

Correction matrix to use for SPAM error correction.

bool noplacement = true

Disable circuit placement IR transformations (both pure topological and noise-based placement).

std::string placement = "swap-shortest-path"

The name of the module to use for circuit placement IR transformation.

bool nooptimise = false

Disable circuit optimization IR transformations.

Passes circuit_opts

Circuit optimization passes to apply.

bool execute_circuit = true

Whether or not to actually execute the circuit upon calling run.

Set false to disable circuit simulation, for e.g., inspecting transpilation or resource estimation only.

bool calc_state_vec = false

Compute the state vector with qpp or aer.

bool output_oqm_enabled = true

Enable output transpilation and resource estimation.

bool notiming = false

Disable timing estimation.

size_t qn = 0

The number of qubits to simulate.

size_t sn = 0

The number of measurement shots to be performed.

size_t seed = 0

Seed value for the session’s random number generator. Zero indicates that the seed should be generated by std::random_device.

size_t initial_bond_dimension = 1

Initial bond dimension for tensor network simulators.

Note

This is only needed when using tensor network backend accelerators.

size_t max_bond_dimension = 256

Maximum bond dimension for tensor network simulators.

Note

This is only needed when using tensor network backend accelerators.

size_t initial_kraus_dimension = 1

Initial Kraus dimension for the purification simulator.

Note

This is only needed when using the emulator’s purification backend accelerator.

size_t max_kraus_dimension = 256

Maximum Kraus dimension for the purification simulator.

Note

This is only needed when using the emulator’s purification backend accelerator.

double svd_cutoff = 1.0e-8

Absolute SVD cutoff for tensor network simulators.

Note

This is only needed when using tensor network backend accelerators.

double rel_svd_cutoff = 1.0e-4

Relative SVD cutoff for tensor network simulators.

Note

This is only needed when using tensor network backend accelerators.

std::string measure_sample_method = "auto"

Set the measurement sampling method. Options: “cutensornet” uses the single-shot cutensorNet contraction method of the entire tensor network state. Program terminates with error meassage if cutensorNet fails. “cutensornet_multishot” uses the multi-shot cutensorNet contraction method. “sequential” uses the cutensor sequential contraction method. “auto” (default) uses the cutensorNet contraction method and automatically swithes to the cutensor sequential contraction method if the cutensorNet method fails.

Note

This is only needed if using a tensor network accelerator

std::string svd_type = "Jacobian"

Type of singular value decomposition (SVD) method. Options: “QR”: Iterative QR based SVD “Jacobian”: Jacobian based SVD.

Note

This is only needed if using a tensor network accelerator

double svdj_tol = 1.0e-3

Accuracy tolerance for Jacobian based SVD method.

size_t svdj_max_sweeps = 80

Maximum number of iterative sweeps for Jacobian based SVD method.

std::shared_ptr<NoiseModel> noise_model

Noise model to use when noise = true.

bool debug = false

Debug mode (verbose logging)

Private Types

enum class circuit_origin

Supported circuit input sources.

Values:

enumerator instring
enumerator infile
enumerator random_circuit
enumerator IR
enumerator CUDAQ

Private Functions

std::string random_circuit(const size_t n_q, const size_t depth)
circuit_origin deduce_circuit_origin()

Try to work out the form of the circuit input.

Forms checked first get precedence; fields associated with other forms get ignored as soon as a valid form is found.

void process_run_result(std::shared_ptr<xacc::CompositeInstruction> kernel_ir, std::shared_ptr<xacc::Accelerator> sim_qpu, const xacc::HeterogeneousMap &sim_qpu_configs, std::shared_ptr<xacc::AcceleratorBuffer> buffer_b, double runtime_ms, std::shared_ptr<qristal::backend> qb_transpiler)

Helper to populate result tables (e.g. counts, expectation values, resource estimations) post-execution.

std::shared_ptr<xacc::CompositeInstruction> compile_input(const std::string &in_source_string, int in_num_qubits, circuit_language in_source_type)

Util method to compile input source string into IR.

This method is thread-safe, thus can be used to compile multiple source strings in parallel.

std::string get_target_circuit_qasm_string(circuit_origin input_origin)

Retrieve the target circuit string. This will involve loading a file, generating a random circuit string, etc, depending on the value of input_origin.

Parameters:

input_origin – The origin of the input circuit.

Returns:

The target circuit as a std::string.

xacc::HeterogeneousMap configure_backend(const YAML::Node &rbdb)

Combine all backend options into a dict (xacc::HeterogeneousMap).

Returns:

A xacc::HeterogeneousMap containing the settings for the backend in use.

std::shared_ptr<xacc::Accelerator> get_sim_qpu(bool execute_on_hardware)

Get the simulator.

void run_gradients()

Calculate the gradients for the parametrized quantum task. This will calculate the gradients of the probabilities of all possible output bitstrings of the circuit, with respect to each circuit parameter. The session does this by creating two new session objects and using them to compute the gradients using the “parameter-shift” rule, where the circuit is run again using slightly shifted parameters.

void execute_on_simulator(std::shared_ptr<xacc::Accelerator> acc, std::shared_ptr<xacc::AcceleratorBuffer> buffer_b, std::shared_ptr<xacc::CompositeInstruction> &circuit)

Execute the circuit on a simulator.

template<typename CountMapT>
inline void populate_measure_counts_data(const CountMapT &measure_counts_map)

Populate a given counts map with results from QPU execution. Templated measure_counts_map to support different type of map-like data.

Private Members

bool all_bitstring_counts_ordered_by_MSB_ = false
YAML::Node remote_backend_database_
size_t shots_remaining_

The number of shots remaining to be drawn from results_ using draw_shot.

size_t sn_this_process

The number of shots to be run on the current process (differs from sn if running with multiple MPI processes).

size_t acc_uses_n_bit_
std::map<std::vector<bool>, int> results_

The results of a Quantum calculation. The map value (count) is the number of times the map key (Qubit states with the same bit indexation as the quantum processor registers) was measured after all shots were run.

Note

The Qubit states are represented as a vector of booleans for the reasons outlined below:

  • High qubit counts can quickly exhaust all possible values able to be encoded by even a 64-bit integer, causing integer overflow.

  • Values are agnostic with respect to both endianness and ordering because a vector with indices correspond unambiguously to the register number of each qubit. Specifically:

    • Ordering: if qubits were saved as e.g. a string “0010110”, a convention about whether the value of qubit 0 goes on the left of the string or the right of it must be chosen.

    • Endianness: if instead a maximally compact representation is opted for where an integer that corresponds to the whole bitstring is used (e.g. all_bitstring_counts_), a convention about whether bit 0 is the most or the least significant bit in encoding that integer must be chosen.

std::vector<int> all_bitstring_counts_

Provides counts for every possible combination of qubit measurements, ordered according to the selected encoding (MSB, LSB). Requires calc_all_bitstring_counts to be set to true.

E.g. If 2 qubits are used in the calculation, the out counts vector will contain the count of each result in the below order.

Encoding

Order of Results

MSB

00, 01, 10, 11

LSB

00, 10, 01, 11

Note

The mapping from bitstring to vector index can be obtained from the function bitstring_index.

std::vector<double> all_bitstring_probabilities_

Probability distribution of output results. Order of probabilities is identical to the order of the all_bitstring_counts_.

Note

The mapping from bitstring to vector index can be obtained from the function bitstring_index.

std::vector<std::vector<double>> all_bitstring_probability_gradients_

A 2D array of probability gradients with dimensions of the number of parameters by the number of qubits. Requires calc_gradients to be set to true.

This array stores gradients of the bitstring probabilities with respect to the circuit parameters, in the following format (where y is the probability list and x is the parameter list):

\[\begin{split} \begin{bmatrix} \frac{dy_0}{dx_0} & \frac{dy_0}{dx_1} & ... & \frac{dy_0}{dx_n} \\ \frac{dy_1}{dx_0} & \frac{dy_1}{dx_1} & ... & \frac{dy_1}{dx_n} \\ ... \\ \frac{dy_m}{dx_0} & \frac{dy_m}{dx_1} & ... & \frac{dy_m}{dx_n} \end{bmatrix} \end{split}\]

As the gradients are returned as a list-of-lists, they can be accessed in row major format, and indexing the above matrix can be done accordingly, i.e. all_bitstring_probability_gradients()[0][1] corresponds to the dy_0/dx_1 value. x_i correspond to the parameters set using circuit_parameters() (i.e. the parameters ordered by their first appearance in the circuit). y_i are the output probabilities of different bitstrings, indexed in the same manner as all_bitstring_counts_. Explicitly, the index i corresponding to a specific bitstring can be obtained by calling bitstring_index(bitstring), with bitstring given as a list of bit values.

std::string transpiled_circuit_
std::string qobj_
std::string qbjson_
bool acc_outputs_qbit0_left_
std::map<int, int> one_qubit_gate_depths_
std::map<int, int> two_qubit_gate_depths_
std::map<int, double> timing_estimates_
double z_op_expectation_
std::shared_ptr<xacc::Accelerator> qpu_ = nullptr

The XACC accelerator in use.

std::shared_ptr<std::vector<std::complex<double>>> state_vec_

State vector from qpp or aer.

bool perform_SPAM_correction_ = false

Whether or not to apply SPAM error mitigation.

std::map<std::vector<bool>, int> results_native_

When error mitigation is performed for the session, the raw results are stored in here.

See also

results_

Private Static Functions

static std::string convertRawOpenQasmToQBKernel(const std::string &in_rawQasm)

Wrap raw OpenQASM string in a QB Kernel:

  • Move qreg to a kernel argument

  • Denote the kernel name as ‘qristal_circuit’

Private Static Attributes

static std::mutex shared_mutex

A mutex to lock access to non-threadsafe operations.