qml.tape.Unwrap

class Unwrap(*tapes, params=None)[source]

Bases: object

A context manager that unwraps multiple tapes with tensor-like parameters to NumPy arrays. In addition, this context manager also correctly infers the trainable parameters of the tapes.

Parameters
  • *tapes (QuantumTape) – a sequence of quantum tapes to unwrap

  • params (List[List[tensor_like or float]] or None) – Nested list of parameters for each tape in the input sequence. If provided, these parameter values will be applied to each tape within the context.

Returns

a sequence of unwrapped quantum tapes

Return type

Sequence[QuantumTape]

Example

Consider the following two tapes:

x = torch.tensor([0.1, 0.2, 0.3], requires_grad=True, dtype=torch.float64)
y = torch.tensor([0.5, 0.6], dtype=torch.float64)

with qml.tape.QuantumTape() as tape1:
    qml.RX(x[0], wires=0)
    qml.RY(y[1], wires=0)
    qml.RZ(x[2], wires=0)

with qml.tape.QuantumTape() as tape2:
    qml.RX(x[1], wires=0)
    qml.RY(x[1], wires=0)
    qml.RZ(y[0], wires=0)

We can use the Unwrap context manager to simultaneously unwrap the parameters of both tapes:

>>> with Unwrap(tape1, tape2):
...     print("Tape 1 trainable:", tape1.trainable_params)
...     print("Tape 1 params:", tape1.get_parameters())
...     print("Tape 2 trainable:", tape2.trainable_params)
...     print("Tape 2 params:", tape2.get_parameters())
Tape 1 trainable: {0, 2}
Tape 1 params: [0.1, 0.3]
Tape 2 trainable: {0, 1}
Tape 2 params: [0.2, 0.2]

Outside of the context, the original parameter types remain:

>>> print("Original parameters:", tape1.get_parameters())
Original parameters: [tensor(0.1000, dtype=torch.float64, grad_fn=<SelectBackward>),
  tensor(0.3000, dtype=torch.float64, grad_fn=<SelectBackward>)]