Performance Bottleneck: When running this loop on a CUDA-enabled session, active GPU utilization scales down completely to 0.00% while a single thread on the CPU spikes to 100%. If I remove the explicit `.cpu()` cast from the internal elements to force direct GPU execution, the framework runtime halts immediately with the following error layout:
import torch
import torch.nn as nn
import torch.optim as optim
import pennylane as qml
# 1. Global Simulation Environment (8 Wires)
n_qubits = 8
dev = qml.device("default.qubit", wires=n_qubits)
@qml.qnode(dev, interface="torch")
def batch_processing_circuit(inputs, weights):
# Standard Angle Embedding configuration
qml.AngleEmbedding(inputs, wires=range(n_qubits), rotation='X')
# Parameterized single-qubit rotations
for i in range(n_qubits):
qml.RX(weights[i], wires=i)
# Fixed entanglement chain
for i in range(0, n_qubits, 2):
qml.CNOT(wires=[i, (i + 1) % n_qubits])
return [qml.expval(qml.PauliZ(i)) for i in range(n_qubits)]
# 2. Hybrid Network Wrapper Architecture
class HybridModel(nn.Module):
def __init__(self):
super().__init__()
# Classical feature extractor
self.encoder = nn.Sequential(
nn.Flatten(),
nn.Linear(12 * 8 * 8, 64),
nn.ReLU(),
nn.Linear(64, n_qubits)
)
# Variational circuit weights
self.q_weights = nn.Parameter(torch.randn(12))
self.output_head = nn.Linear(n_qubits, 1000)
def forward(self, x):
# x arrives initialized on the GPU target
features = torch.tanh(self.encoder(x)) * 3.14
# Core Bottleneck Loop: Processing elements line-by-line via CPU fallback
quantum_outputs = []
for sample in features:
# Forcing data to .cpu() prevents cross-device tensor crashes,
# but completely stalls GPU utilization down to 0%
q_out = torch.stack(batch_processing_circuit(sample.cpu(), self.q_weights.cpu()))
quantum_outputs.append(q_out)
final_features = torch.stack(quantum_outputs).to(x.device).float()
return self.output_head(final_features)
# 3. Execution Harness (Simulates a single batch forward evaluation pass)
if __name__ == "__main__":
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Active Device Target: {device}")
model = HybridModel().to(device)
# Standard random noise mock tensor representing a 32-sample batch
mock_batch = torch.randn(32, 12, 8, 8).to(device)
output = model(mock_batch)
print("Forward pass finished.")
If you want help with diagnosing an error, please put the full error message below:
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
**
import** pennylane as qml
qml.about()
Name: pennylane
Version: 0.45.1
Summary: PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
Home-page:
Author:
License:
Location: /usr/local/lib/python3.12/dist-packages
Platform info: Linux-6.12.90+-x86_64-with-glibc2.35
Python version: 3.12.13
Numpy version: 2.0.2
Scipy version: 1.16.3
JAX version: 0.7.2
Catalyst version: None
Installed devices:
- default.clifford (pennylane-0.45.1)
- default.gaussian (pennylane-0.45.1)
- default.mixed (pennylane-0.45.1)
- default.qubit (pennylane-0.45.1)
- default.qutrit (pennylane-0.45.1)
- default.qutrit.mixed (pennylane-0.45.1)
- default.tensor (pennylane-0.45.1)
- null.qubit (pennylane-0.45.1)
- reference.qubit (pennylane-0.45.1)
- lightning.qubit (pennylane_lightning-0.45.0)