mindquantum.nn.MindQuantumLayer

class mindquantum.nn.MindQuantumLayer(encoder_params_names, ansatz_params_names, circuit, hams, weight_init='normal', n_threads=1)[source]

A trainable Mindquantum layer.

A mindquantum layer simulate a parameterized quantum circuit and get the measurement result. The quantum circuit is construct by a encode circuit and a trainable ansatz circuit. The encode circuit will encode classical data into quantum state, and the trainable ansatz circuit apply on the quantum state.

Parameters
  • encoder_params_names (list[str]) – Parameters names of encoder circuit. The order of this parameters is the same as the order of data passed in construct.

  • ansatz_params_names (list[str]) – Parameters names of ansatz circuit. The order of this parameters is the same as the order of trainable parameters.

  • circuit (Circuit) – Quantum circuit construct by encode circuit and ansatz circuit.

  • hams (list[Hamiltonian]) – Hamiltonian or a list of Hamiltonian for measurement.

  • weight_init (Union[Tensor, str, Initializer, numbers.Number]) – The trainable weight_init parameter. The dtype is same as input x. The values of str refer to the function initializer. Default: ‘normal’.

  • n_threads (int) – Number of threads for data parallel. Default: 1.

Inputs:
  • input (Tensor) - Tensor of shape \((N, E_{in})\), where \(N\) is batch size, \(E_{in}\) is the number of parameters in encoder circuit.

Outputs:

Tensor of shape \((N, H_{out})\), where \(H_{out}\) is the number of hamiltonians.

Supported Platforms:

CPU

Examples

>>> from projectq.ops import QubitOperator
>>> from mindquantum.nn import MindQuantumLayer
>>> from mindquantum import Circuit, Hamiltonian
>>> import mindquantum.gate as G
>>> encoder_circ = Circuit([G.RX('a').on(0)])
>>> encoder_circ.no_grad()
>>> ansatz = Circuit([G.RY('b').on(0)])
>>> ham = Hamiltonian(QubitOperator('Z0'))
>>> net = MindQuantumLayer(['a'], ['b'], encoder_circ + ansatz, ham)
>>> res = net(Tensor(np.array([[1.0]]).astype(np.float32)))
>>> res.asnumpy()
array([[0.54030216]], dtype=float32)
final_state(encoder_data, ansatz_data=None, circuit=None, hams=None)[source]

Get the quantum state after evolution.

Parameters
  • encoder_data (Tensor) – A one dimension tensor for encoder circuit.

  • ansatz_data (Tensor) – A one dimension tensor for ansatz circuit. If ansatz_data is None, then the traind parameter will be used. Default: None.

  • circuit (Circuit) – Quantum circuit construct by encode circuit and ansatz circuit. If None, the circuit for train will be used. Default: None.

  • hams (list[Hamiltonian]) – Hamiltonian or a list of Hamiltonian for measurement. If None, the hamiltonians for train will be used. Default: None.

Returns

the final quantum state.

Return type

numpy.ndarray