Skip to content

Commit d23b9c3

Browse files
authored
Implement automatic qubit management (#1788)
**Context:** We wish to support automatic qubit management, i.e. when the user does not specify the number of wires in device initialization ```python @qjit def workflow(): dev = qml.device("lightning.qubit") # no wires here! @qml.qnode(dev) def circuit(): qml.PauliX(wires=0) return qml.probs(wires=[2,3]) # non qjit is [1,0,0,0] return circuit() ``` **Description of the Change:** A new unit attribute, `auto_qubit_management`, is added to the device init op. If no wires are specified during device init in user python, we trace to device init op with this attribute turned on. In runtime, when a new user wire index is encountered in `__catalyst__rt__array_get_element_ptr_1d`, if the device is in automatic management mode (as indicated by the `RTDevice` constructor, set from the new attribute we added), we allocate new device qubits so that this new user wire index is an available qubit. **Benefits:** The automatic qubit management feature is now supported. **Possible Drawbacks:** 1. Catalyst and Pennylane interprets wire labels differently. See #1800 2. Potential out-of-memory error might be encountered in runtime. [sc-86500]
1 parent 915a505 commit d23b9c3

File tree

18 files changed

+372
-67
lines changed

18 files changed

+372
-67
lines changed

doc/releases/changelog-dev.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,38 @@
7474
Array([0.25, 0.25, 0.25, 0.25], dtype=float64))
7575
```
7676

77+
* Catalyst now supports automatic qubit management.
78+
[(#1788)](https://github.com/PennyLaneAI/catalyst/pull/1788)
79+
80+
The number of wires does not need to be speficied during device initialization,
81+
and instead will be automatically managed by the Catalyst Runtime.
82+
83+
```python
84+
@qjit
85+
def workflow():
86+
dev = qml.device("lightning.qubit") # no wires here!
87+
@qml.qnode(dev)
88+
def circuit():
89+
qml.PauliX(wires=2)
90+
return qml.probs()
91+
return circuit()
92+
93+
print(workflow())
94+
```
95+
96+
```pycon
97+
[0. 1. 0. 0. 0. 0. 0. 0.]
98+
```
99+
100+
In this example, the number of wires is not specified at device initialization.
101+
When we encounter an X gate on `wires=2`, catalyst automatically expands the size
102+
of the qubit register to include the requested wire index.
103+
Here, the register will contain (at least) 3 qubits after the X operation.
104+
As a result, we can see the QNode returning the probabilities for the state |001>,
105+
meaning 3 wires were allocated in total.
106+
107+
This feature can be turned on by omitting the `wires` argument to the device.
108+
77109
<h3>Improvements 🛠</h3>
78110

79111
* The behaviour of measurement processes executed on `null.qubit` with QJIT is now more in line with

frontend/catalyst/device/qjit_device.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -548,14 +548,17 @@ def is_dynamic_wires(wires: qml.wires.Wires):
548548
If the number of wires is dynamic, the Wires object contains a single tracer that
549549
represents the number of wires.
550550
"""
551+
# Automatic qubit management mode should not encounter this query
552+
assert wires is not None
551553
return (len(wires) == 1) and (isinstance(wires[0], DynamicJaxprTracer))
552554

553555

554556
def check_device_wires(wires):
555557
"""Validate requirements Catalyst imposes on device wires."""
556558

557559
if wires is None:
558-
raise AttributeError("Catalyst does not support device instances without set wires.")
560+
# Automatic qubit management mode, nothing to check
561+
return
559562

560563
if len(wires) >= 2 or (not is_dynamic_wires(wires)):
561564
# A dynamic number of wires correspond to a single tracer for the number

frontend/catalyst/from_plxpr.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,11 @@ def __setattr__(self, __name: str, __value) -> None:
301301
def setup(self):
302302
"""Initialize the stateref and bind the device."""
303303
if self.stateref is None:
304-
device_init_p.bind(self._shots, **_get_device_kwargs(self._device))
304+
device_init_p.bind(
305+
self._shots,
306+
auto_qubit_management=(self._device.wires is None),
307+
**_get_device_kwargs(self._device),
308+
)
305309
self.stateref = {"qreg": qalloc_p.bind(len(self._device.wires)), "wire_map": {}}
306310

307311
# pylint: disable=attribute-defined-outside-init

frontend/catalyst/jax_primitives.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -813,12 +813,18 @@ def _zne_lowering(ctx, *args, folding, jaxpr, fn):
813813
# device_init
814814
#
815815
@device_init_p.def_abstract_eval
816-
def _device_init_abstract_eval(shots, rtd_lib, rtd_name, rtd_kwargs):
816+
def _device_init_abstract_eval(shots, auto_qubit_management, rtd_lib, rtd_name, rtd_kwargs):
817817
return ()
818818

819819

820+
# pylint: disable=too-many-arguments, too-many-positional-arguments
820821
def _device_init_lowering(
821-
jax_ctx: mlir.LoweringRuleContext, shots: ir.Value, rtd_lib, rtd_name, rtd_kwargs
822+
jax_ctx: mlir.LoweringRuleContext,
823+
shots: ir.Value,
824+
auto_qubit_management,
825+
rtd_lib,
826+
rtd_name,
827+
rtd_kwargs,
822828
):
823829
ctx = jax_ctx.module_context.context
824830
ctx.allow_unregistered_dialects = True
@@ -829,6 +835,7 @@ def _device_init_lowering(
829835
ir.StringAttr.get(rtd_name),
830836
ir.StringAttr.get(rtd_kwargs),
831837
shots=shots_value,
838+
auto_qubit_management=auto_qubit_management,
832839
)
833840

834841
return ()

frontend/catalyst/jax_tracer.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -985,11 +985,13 @@ def trace_quantum_measurements(
985985
"Use qml.sample() instead."
986986
)
987987

988-
d_wires = (
989-
num_qubits_p.bind()
990-
if catalyst.device.qjit_device.is_dynamic_wires(device.wires)
991-
else len(device.wires)
992-
)
988+
if device.wires is None:
989+
d_wires = num_qubits_p.bind()
990+
elif catalyst.device.qjit_device.is_dynamic_wires(device.wires):
991+
d_wires = num_qubits_p.bind()
992+
else:
993+
d_wires = len(device.wires)
994+
993995
m_wires = output.wires if output.wires else None
994996
obs_tracers, nqubits = trace_observables(output.obs, qrp, m_wires)
995997
nqubits = d_wires if nqubits is None else nqubits
@@ -1386,11 +1388,16 @@ def is_leaf(obj):
13861388
device_shots = get_device_shots(device) or 0
13871389
device_init_p.bind(
13881390
device_shots,
1391+
auto_qubit_management=(device.wires is None),
13891392
rtd_lib=device.backend_lib,
13901393
rtd_name=device.backend_name,
13911394
rtd_kwargs=str(device.backend_kwargs),
13921395
)
1393-
if catalyst.device.qjit_device.is_dynamic_wires(device.wires):
1396+
if device.wires is None:
1397+
# Automatic qubit management mode
1398+
# We start with 0 wires and allocate new wires in runtime as we encounter them.
1399+
qreg_in = qalloc_p.bind(0)
1400+
elif catalyst.device.qjit_device.is_dynamic_wires(device.wires):
13941401
# When device has dynamic wires, the device.wires iterable object
13951402
# has a single value, which is the tracer for the number of wires
13961403
qreg_in = qalloc_p.bind(device.wires[0])

frontend/test/lit/test_measurements.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -678,3 +678,26 @@ def circ():
678678

679679
state_dynamic(10)
680680
print(state_dynamic.mlir)
681+
682+
683+
# CHECK-LABEL: @automatic_qubit_management
684+
@qjit(target="mlir")
685+
def automatic_qubit_management():
686+
@qml.qnode(qml.device("lightning.qubit"))
687+
def circ():
688+
# CHECK: [[qreg:%.+]] = quantum.alloc( 0) : !quantum.reg
689+
# CHECK: [[in_qubit:%.+]] = quantum.extract [[qreg]][ 2] : !quantum.reg -> !quantum.bit
690+
# CHECK: [[out_qubit:%.+]] = quantum.custom "Hadamard"() [[in_qubit]] : !quantum.bit
691+
qml.Hadamard(wires=2)
692+
693+
# CHECK: [[nqubits:%.+]] = quantum.num_qubits : i64
694+
# CHECK: [[toTensor:%.+]] = tensor.from_elements [[nqubits]] : tensor<i64>
695+
# CHECK: [[probs_shape:%.+]] = stablehlo.shift_left {{%.+}}, [[toTensor]] : tensor<i64>
696+
# CHECK: [[deTensor:%.+]] = tensor.extract [[probs_shape]][] : tensor<i64>
697+
# CHECK: {{%.+}} = quantum.probs {{%.+}} shape [[deTensor]] : tensor<?xf64>
698+
return qml.probs()
699+
700+
return circ()
701+
702+
703+
print(automatic_qubit_management.mlir)
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
# Copyright 2025 Xanadu Quantum Technologies Inc.
2+
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""
16+
This file contains tests for automatic qubit management.
17+
Automatic qubit management refers to when the user does not specify the total number of wires
18+
during device initialization.
19+
20+
Note that, catalyst and pennylane handles device labels differently. For example, when a new label
21+
qml.gate_or_measurement(wires=1000)
22+
is encountered, core pennylane considers "1000" as a pure wire label, and interprets that as
23+
*one* new wire, with the label "1000". However in catalyst we do not associate wires with
24+
arbitrary labels and require wires to be continuous integers from zero, and we would interpret this
25+
as "allocate new wires until we have 1001 wires, and act on wire[1000]".
26+
27+
In other words, the reference runs of automatic qubit management should be qjit runs with wires
28+
specified during device initialization, instead of non qjit runs.
29+
"""
30+
31+
import numpy as np
32+
import pennylane as qml
33+
34+
from catalyst import qjit
35+
36+
37+
def test_partial_sample(backend):
38+
"""
39+
Test that a `sample` terminal measurement with wires specified can be executed
40+
correctly with automatic qubit management.
41+
"""
42+
43+
def circuit():
44+
qml.RX(0.0, wires=0)
45+
return qml.sample(wires=[0, 2])
46+
47+
wires = [4, None]
48+
devices = [qml.device(backend, shots=10, wires=wire) for wire in wires]
49+
ref, observed = (qjit(qml.qnode(dev)(circuit))() for dev in devices)
50+
assert ref.shape == observed.shape
51+
assert np.allclose(ref, observed)
52+
53+
54+
def test_partial_counts(backend):
55+
"""
56+
Test that a `counts` terminal measurement with wires specified can be executed
57+
correctly with automatic qubit management.
58+
"""
59+
60+
def circuit():
61+
qml.RX(0.0, wires=0)
62+
return qml.counts(wires=[0, 2])
63+
64+
wires = [4, None]
65+
devices = [qml.device(backend, shots=10, wires=wire) for wire in wires]
66+
ref, observed = (qjit(qml.qnode(dev)(circuit))() for dev in devices)
67+
assert (ref[i].shape == observed[i].shape for i in (0, 1))
68+
assert np.allclose(ref, observed)
69+
70+
71+
def test_partial_probs(backend):
72+
"""
73+
Test that a `probs` terminal measurement with wires specified can be executed
74+
correctly with automatic qubit management.
75+
"""
76+
77+
def circuit():
78+
qml.PauliX(wires=0)
79+
return qml.probs(wires=[0, 2])
80+
81+
wires = [4, None]
82+
devices = [qml.device(backend, wires=wire) for wire in wires]
83+
ref, observed = (qjit(qml.qnode(dev)(circuit))() for dev in devices)
84+
assert ref.shape == observed.shape
85+
assert np.allclose(ref, observed)
86+
87+
88+
def test_sample(backend):
89+
"""
90+
Test that a `sample` terminal measurement without wires specified can be executed
91+
correctly with automatic qubit management.
92+
"""
93+
94+
def circuit():
95+
qml.RX(0.0, wires=3)
96+
return qml.sample()
97+
98+
wires = [4, None]
99+
devices = [qml.device(backend, shots=10, wires=wire) for wire in wires]
100+
ref, observed = (qjit(qml.qnode(dev)(circuit))() for dev in devices)
101+
assert ref.shape == observed.shape
102+
assert np.allclose(ref, observed)
103+
104+
105+
def test_counts(backend):
106+
"""
107+
Test that a `counts` terminal measurement without wires specified can be executed
108+
correctly with automatic qubit management.
109+
"""
110+
111+
def circuit():
112+
qml.RX(0.0, wires=3)
113+
return qml.counts()
114+
115+
wires = [4, None]
116+
devices = [qml.device(backend, shots=10, wires=wire) for wire in wires]
117+
ref, observed = (qjit(qml.qnode(dev)(circuit))() for dev in devices)
118+
assert (ref[i].shape == observed[i].shape for i in (0, 1))
119+
assert np.allclose(ref, observed)
120+
121+
122+
def test_probs(backend):
123+
"""
124+
Test that a `probs` terminal measurement without wires specified can be executed
125+
correctly with automatic qubit management.
126+
"""
127+
128+
def circuit():
129+
qml.PauliX(wires=3)
130+
return qml.probs()
131+
132+
wires = [4, None]
133+
devices = [qml.device(backend, wires=wire) for wire in wires]
134+
ref, observed = (qjit(qml.qnode(dev)(circuit))() for dev in devices)
135+
assert ref.shape == observed.shape
136+
assert np.allclose(ref, observed)
137+
138+
139+
def test_state(backend):
140+
"""
141+
Test that a `state` terminal measurement without wires specified can be executed
142+
correctly with automatic qubit management.
143+
"""
144+
145+
def circuit():
146+
qml.PauliX(wires=3)
147+
return qml.state()
148+
149+
wires = [4, None]
150+
devices = [qml.device(backend, wires=wire) for wire in wires]
151+
ref, observed = (qjit(qml.qnode(dev)(circuit))() for dev in devices)
152+
assert ref.shape == observed.shape
153+
assert np.allclose(ref, observed)

frontend/test/pytest/test_device_api.py

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -56,17 +56,6 @@ def test_qjit_device():
5656
device_qjit.execute(10, 2)
5757

5858

59-
def test_qjit_device_no_wires():
60-
"""Test the qjit device from a device using the new api without wires set."""
61-
device = NullQubit(shots=2032)
62-
63-
with pytest.raises(
64-
AttributeError, match="Catalyst does not support device instances without set wires."
65-
):
66-
# Create qjit device
67-
QJITDevice(device)
68-
69-
7059
@pytest.mark.parametrize(
7160
"wires",
7261
(

mlir/include/Quantum/IR/QuantumOps.td

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ def DeviceInitOp : Quantum_Op<"device"> {
8181

8282
let arguments = (ins
8383
Optional<I64>:$shots,
84+
UnitAttr:$auto_qubit_management,
8485
StrAttr:$lib,
8586
StrAttr:$device_name,
8687
StrAttr:$kwargs
@@ -90,6 +91,18 @@ def DeviceInitOp : Quantum_Op<"device"> {
9091
(`shots` `(` $shots^ `)`)? `[` $lib `,` $device_name `,` $kwargs `]` attr-dict
9192
}];
9293

94+
let builders = [
95+
OpBuilder<
96+
// Convenience builder for a device not in automatic qubit management mode
97+
(ins
98+
"mlir::Value":$shots,
99+
"mlir::StringAttr":$lib,
100+
"mlir::StringAttr":$device_name,
101+
"mlir::StringAttr":$kwargs
102+
),[{
103+
DeviceInitOp::build($_builder, $_state, shots, false, lib, device_name, kwargs);
104+
}]>,
105+
];
93106
}
94107

95108
def DeviceReleaseOp : Quantum_Op<"device_release"> {

mlir/lib/Quantum/Transforms/ConversionPatterns.cpp

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,13 @@ struct DeviceInitOpPattern : public OpConversionPattern<DeviceInitOp> {
187187

188188
Type charPtrType = LLVM::LLVMPointerType::get(rewriter.getContext());
189189
Type int64Type = IntegerType::get(rewriter.getContext(), 64);
190+
Type int1Type = IntegerType::get(rewriter.getContext(), 1);
190191
Type qirSignature = LLVM::LLVMFunctionType::get(LLVM::LLVMVoidType::get(ctx),
191192
{/* rtd_lib = */ charPtrType,
192193
/* rtd_name = */ charPtrType,
193194
/* rtd_kwargs = */ charPtrType,
194-
/* shots = */ int64Type});
195+
/* shots = */ int64Type,
196+
/*auto_qubit_management = */ int1Type});
195197
LLVM::LLVMFuncOp fnDecl =
196198
catalyst::ensureFunctionDeclaration(rewriter, op, qirName, qirSignature);
197199

@@ -217,6 +219,10 @@ struct DeviceInitOpPattern : public OpConversionPattern<DeviceInitOp> {
217219
operands.push_back(shots);
218220
}
219221

222+
Value autoQubitManagement = rewriter.create<LLVM::ConstantOp>(loc, rewriter.getI1Type(),
223+
op.getAutoQubitManagement());
224+
operands.push_back(autoQubitManagement);
225+
220226
rewriter.create<LLVM::CallOp>(loc, fnDecl, operands);
221227

222228
rewriter.eraseOp(op);

0 commit comments

Comments
 (0)