QLayer InterfaceΒΆ

SpinQit provides an abstract interface named QLayer to simplify the implementation of varational quantum algorithms and quantum machine learning algorithms. QLayer is an encapsulation of backend, backend configuration, measurement operation, gradient function and so on. QLayer can be defined via a decorator named to_qlayer. Developers use this decorator to wrap any function that returns a Circuit. With the to_qlayer decorator, the final result will be the measurement result of the quantum circuit from the wrapped function on the input backend. QLayer can also work with the optimizers in SpinQit and interfaces for classical machine learning frameworks. These optimizers and frameworks will call the gradient function specified in QLayer for gradient-based optimization. The following examples show how to use the to_qlayer decorator.

from spinqit.interface import to_qlayer
from spinqit.algorithm.loss import expval
op = expval(generate_hamiltonian_matrix([('ZI', 1)]))
@to_qlayer(backend_mode='spinq', grad_method='param_shift', measure=op, interface='torch')
def build_circuit(weights_shape, qubit_num):
    circ = Circuit()
    weight = circ.add_params(shape=weights_shape) 
    q = circ.allocateQubits(qubit_num)
    ...
    return circ

More configuration information can be provided via to_qlayer:

@to_qlayer(backend_mode='nmr', grad_method='param_shift', measure=expval(hamiltonian), interface='spinq', ip='192.168.8.176', port=55444, account=("user9", "123456"), shots=1024, task_name='nmrgradtest1', task_desc='nmr grad test')

The main parameters include:

backend_mode
The backend to execute the circuit, and the current options are 'spinq', 'torch', 'cloud', and 'nmr'
measure
This parameter must be a function creating a measurement operation. There are four types of measurement operations: states(), probs(mqubits=None), counts(shots=None, mqubits=None) and expval(hamiltonian). Here expval means the expectation value of a Hamiltonian, and the parameter hamiltonian is a scipy.sparse.csr_matrix or a list of (Pauli string, coefficient) pairs.
interface
There are four available interfaces: 'torch', 'tf', 'paddle', and 'spinq'. To avoid unnecessary conversion of data types, SpinQit provides interfaces to co-work with classical machine learning frameworks such as Pytorch, TensorFlow, and PaddlePaddle.
grad_method
Each backend supports one or more gradient functions. All the backends support 'param_shift'. In addition, 'torch' supports 'backprop' and 'spinq' supports 'adjoint_differentiation'.

The following table summarizes the gradient methods and measure operations supported by each kind of backend in QLayer.

Backend Mode Grad Method MeasureOp
spinq param_shift expval
adjoint_differentiation expval
torch param_shift expval
backprop expval, state
cloud param_shift expval
nmr param_shift expval