Generated banner for Pennylane
Generated logo for Pennylane

Pennylane

K-DenseCommunityCreated by K-Dense Inc.

  • Skill
  • Tool integration
  • Science and research
  • MIT
  • Low risk

From the author

Builds and differentiates PennyLane quantum circuits, hybrid PyTorch or JAX models, molecular VQE and QAOA workflows. Use for variational quantum algorithms, quantum machine learning, simulator validation, and moving validated circuits to provider plugins. For hardware-specific compilation use qiskit or cirq; for open-system dynamics use qutip.
— the description by K-Dense Inc.

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

PennyLane is a framework for quantum machine learning, quantum chemistry, and variational quantum algorithms. It enables the construction of differentiable quantum circuits that integrate seamlessly with classical machine learning libraries like PyTorch and JAX. This skill provides guidance on setting up PennyLane environments, building QNodes, performing gradient-based optimization, and validating circuits across various simulators and hardware provider plugins.

What it does

  • Builds and differentiates parameterized quantum circuits.
  • Integrates quantum circuits into hybrid PyTorch or JAX models.
  • Supports molecular VQE and QAOA workflows.
  • Facilitates simulator validation and hardware backend execution.
  • Provides tools for gradient-based optimization of quantum parameters.

When to use it

  • When developing variational quantum algorithms.
  • When building hybrid quantum-classical machine learning models.
  • When performing quantum chemistry simulations like VQE.
  • When you need to validate quantum circuits across different backends.

Advantages

  • Native differentiation of quantum circuits.
  • Seamless integration with popular ML frameworks.
  • Extensive support for various quantum simulators and hardware providers.
  • Standardized workflow for quantum-classical hybrid optimization.

Usage examples

“How do I define a simple parameterized quantum circuit in PennyLane and compute its gradient?”
The agent provides a code snippet using a QNode with a specified device, demonstrating the use of qml.grad to compute the gradient of an expectation value with respect to circuit parameters.
“Show me how to set up a VQE workflow for a molecular system.”
The agent outlines the steps to define the Hamiltonian, choose an ansatz, and use an optimizer to minimize the energy, including tips on handling units and particle sectors.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/k-dense-ai/pennylane/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip pennylane.zip -d .agents/skills

Documentation by K-Dense Inc.

PennyLane

When to use

Use PennyLane to optimize parameterized circuits, build hybrid quantum-classical models, estimate molecular energies, or compare a validated circuit across devices. This skill targets stable PennyLane 0.45.1. The local examples use small synthetic systems; successful optimization does not establish quantum advantage, molecular accuracy, or hardware fidelity.

Installation

Create a dedicated environment; provider plugins and compiler dependencies should be resolved separately from unrelated scientific packages:

uv venv --python 3.13 .venv-pennylane
uv pip install --python .venv-pennylane/bin/python "pennylane==0.45.1"

PennyLane 0.45 requires NumPy 2+. Core installation includes Lightning. For ML, use the tested JAX 0.7.1/JAXlib 0.7.1 pair or PyTorch; do not assume the latest JAX is supported by this PennyLane release. See device setup for optional plugin versions and their verification limits.

Workflow

  1. Fix the problem convention: feature ordering and label encoding for ML; Hamiltonian sign for optimization; units, charge, multiplicity, basis, active space and mapping for chemistry.

  2. Build a small analytic default.qubit circuit. Keep the quantum function separate from the QNode when reusing it on another backend.

  3. Check a known value and a gradient against an analytic or finite-difference result before training. Use trainable pennylane.numpy arrays for Autograd, framework-native tensors for Torch/JAX.

  4. Optimize while recording objective, gradient norm, seeds, ansatz shape and package versions. step_and_cost returns the cost before its update; evaluate the objective again for final reporting.

  5. Validate independently: held-out examples and classical baselines for ML; particle number and a sector-appropriate classical reference for VQE; enumerated small instances for QAOA.

  6. Introduce finite shots/noise, report uncertainty, inspect decomposed resources, then select a current accessible hardware backend and execution budget. Plugin portability does not guarantee identical gates, measurements or gradients.

Quick start: value, gradient and optimization

This self-contained example is executed by the skill's tests.

import pennylane as qml
from pennylane import numpy as np

dev = qml.device("default.qubit", wires=1)

@qml.qnode(dev, interface="autograd", diff_method="backprop")
def energy(theta):
    qml.RY(theta, wires=0)
    return qml.expval(qml.Z(0))

theta = np.array(0.3, requires_grad=True)
assert np.allclose(energy(theta), np.cos(theta))
assert np.allclose(qml.grad(energy)(theta), -np.sin(theta))
opt = qml.GradientDescentOptimizer(stepsize=0.2)
for _ in range(80):
    theta = opt.step(energy, theta)
final_energy = float(energy(theta))
assert final_energy < -0.999
print(f"[OK] final expectation = {final_energy:.6f}")

Load the relevant reference

  • Getting started: QNodes, shots, random streams, trainability, batched parameters and simulator selection.

  • Quantum circuits: controls, measurement feedback, wire ordering, QFT, transforms and current resource access.

  • Quantum ML: executed TorchLayer and JAX training, stable classifier loss, feature scaling and evaluation.

  • Quantum chemistry: H2 UCCSD, units, particle sector checks, dipoles, active spaces, geometry and excited-state caveats.

  • Devices: simulators, provider contracts, credentials, current target discovery and source-only integration boundaries.

  • Optimization: gradient checks, SPSA, QNG, MaxCut sign and exact QUBO-to-Ising conversion.

  • Advanced features: templates, noise, parametrized Hamiltonian evolution, Catalyst and error-correction examples.

Failure checks

  • Samples/counts require finite shots; states require a supporting simulator. Use qml.set_shots on the QNode rather than mutating device shots.

  • Mid-circuit measurement values are symbolic. Use qml.cond, not Python if m.

  • qml.specs in 0.45.1 returns CircuitSpecs; access .resources, not obsolete top-level dictionary keys. Record the transform level and account for split tapes.

  • qml.qaoa.maxcut produces negative cut size. Minimize it directly.

  • A zero/flat gradient can mean an unused parameter, symmetry, saturated encoding, shot noise or differentiation failure. It does not by itself diagnose a barren plateau.

  • Chemistry geometry defaults to bohr. State units explicitly; an unconstrained ansatz can leave the intended electron/spin sector.

  • A simulator seed initializes a random stream. Successive executions consume new draws; reconstructing an equally seeded device reproduces the stream.

Upstream references and verification

Reviewed the stable documentation, 0.45.1 source, deprecations, and linked per-topic API pages. Local simulator/ML examples have numerical tests. Provider hardware, GPU, Catalyst native compilation and external chemistry backends are explicitly illustrative/source-checked, with no authenticated jobs executed.

Citing Scientific Agent Skills

This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a manuscript, report, presentation, or code release, add the paper to the references or software section and tell the user you did so:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the latest arXiv version, so never append a version suffix such as v1. When network access is available, fetch https://arxiv.org/abs/2609.00065 (or http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take the author list, year, and version from that record. If the record lists a journal reference or publisher DOI, cite the published version instead.

Files

references/quantum_ml.md

Quantum machine learning

PennyLane 0.45.1 integrates with Autograd, PyTorch and JAX. TensorFlow maintenance ended in 0.44 and KerasLayer was removed. The examples below exercise small local models, not a claim of generalization or advantage over classical methods.

TorchLayer: correct batch shapes and end-to-end gradients

Tested with PyTorch 2.14.1. The QNode has an inputs argument; all other arguments are trainable weights with entries in weight_shapes. Avoid unrestricted *args or **kwargs. AngleEmbedding handles the leading batch dimension.

import pennylane as qml
import torch

torch.manual_seed(7)
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev, interface="torch", diff_method="backprop")
def qnode(inputs, weights):
    qml.AngleEmbedding(inputs, wires=[0, 1], rotation="Y")
    qml.StronglyEntanglingLayers(weights, wires=[0, 1])
    return [qml.expval(qml.Z(i)) for i in range(2)]

layer = qml.qnn.TorchLayer(qnode, {"weights": (2, 2, 3)})
model = torch.nn.Sequential(torch.nn.Linear(4, 2), layer, torch.nn.Linear(2, 2)).double()
X = torch.tensor([[0.2, 0.1, 0.4, -0.2], [-0.3, 0.2, -0.1, 0.4],
                  [0.5, 0.3, 0.0, -0.2], [-0.2, -0.3, 0.3, 0.5]], dtype=torch.float64)
y = torch.tensor([0, 1, 0, 1], dtype=torch.long)
optimizer = torch.optim.Adam(model.parameters(), lr=0.02)
optimizer.zero_grad()
logits = model(X)
assert logits.shape == (4, 2)
loss = torch.nn.functional.cross_entropy(logits, y)
loss.backward()
assert all(p.grad is not None and torch.isfinite(p.grad).all() for p in model.parameters())
optimizer.step()

A manual QNode can promote input float32 to float64; align a custom surrounding network's dtype. Do not convert trainable outputs through ordinary NumPy or torch.tensor(existing_tensor), which detaches gradients. Use torch.stack when combining tensor results. Save model state plus circuit/weight-shape configuration.

JAX: explicit dataset vectorization

Use the PennyLane-tested JAX/JAXlib 0.7.1 pair in a separate environment. JAX's latest release is not a compatibility claim for PennyLane. Use explicit precision and batch only the sample axis:

import pennylane as qml
import jax
import jax.numpy as jnp

jax.config.update("jax_enable_x64", True)
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev, interface="jax", diff_method="backprop")
def prediction(x, weights):
    qml.AngleEmbedding(x, wires=[0, 1], rotation="Y")
    qml.RY(weights[0], 0)
    qml.RY(weights[1], 1)
    qml.CNOT([0, 1])
    return qml.expval(qml.Z(1))

predict_batch = jax.vmap(prediction, in_axes=(0, None))
@jax.jit
def loss_fn(weights, X, y):
    return jnp.mean((predict_batch(X, weights) - y)**2)

X = jnp.array([[0.1, 0.3], [0.2, -0.4], [-0.3, 0.5]])
y = jnp.array([1.0, -1.0, 1.0])
weights = jnp.array([0.1, 0.2])
value, grad = jax.value_and_grad(loss_fn)(weights, X, y)
assert jnp.isfinite(value) and jnp.isfinite(grad).all()
assert predict_batch(X, weights).shape == (3,)
weights = weights - 0.05 * grad
assert loss_fn(weights, X, y) < value

Finite-shot JAX workflows additionally need explicit PRNG keys, split for new random draws. Validate the specific JIT, differentiation, measurement and device combination; not all combinations support vector-valued Jacobians. Catalyst's compiled quantum workflow is distinct from wrapping a simulator loss in jax.jit.

Autograd classifier and stable loss

import pennylane as qml
from pennylane import numpy as np

dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def classifier(x, weights):
    qml.AngleEmbedding(x, wires=[0, 1], rotation="Y")
    qml.StronglyEntanglingLayers(weights, wires=[0, 1])
    return qml.expval(qml.Z(0))

def binary_loss(weights, X, y):
    # Here P(y=1) = (1 + <Z>)/2 is an explicit label convention.
    z = np.stack([classifier(x, weights) for x in X])
    probability = np.clip((1 + z) / 2, 1e-8, 1 - 1e-8)
    return -np.mean(y * np.log(probability) + (1 - y) * np.log1p(-probability))

X = np.array([[0.1, 0.2], [0.9, -0.8]], requires_grad=False)
y = np.array([1.0, 0.0], requires_grad=False)
weights = np.array([[[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]], requires_grad=True)
grad = qml.grad(binary_loss)(weights, X, y)
assert grad.shape == weights.shape and np.isfinite(grad).all()

For labels defined as the probability of the measured |1> outcome, instead use (1 - <Z>)/2. Keep the convention consistent in training and scoring. Clipping avoids logarithms of zero but saturates gradients at the boundary. A multiclass model should return the promised number of logits/probabilities on allocated wires; three observables cannot use an only-two-wire device.

Encodings and model evaluation

  • Angle embedding needs at most one feature per allocated wire; scale using training data only. Angular periodicity can alias features.

  • Amplitude embedding needs a nonzero finite vector of size at most 2**n with declared padding/normalization. State preparation can be expensive and feature differentiation is generally limited by its classical preprocessing.

  • Basis embedding accepts binary vectors. IQP embedding includes feature-product phases; use the documented template when claiming that encoding.

  • ApproxTimeEvolution(H, time, n) is a Trotter approximation; noncommuting terms need convergence checks. Specify the Hamiltonian and approximation order/steps.

  • QCNN pooling must actually remove measured wires from later active-wire sets; allocating eight wires and measuring/discarding different indices is a different architecture. Recurrent models may return classical expectations as hidden state; distinguish that from persistent quantum memory.

  • For transfer learning, encode the input before frozen layers, freeze the intended parameters in the native framework, and match layer shapes. Fit preprocessing on training data and compare with the same classical feature extractor and head.

Record split/group leakage controls, seed repetitions, shots, hyperparameter budget, classical baselines and confidence intervals. A synthetic training loss decrease is a gradient smoke test, not predictive validation or quantum advantage.

Sources

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Needs network access, Needs Python

The author says: Requires Python 3.11+ and PennyLane 0.45.1 with NumPy 2+. Optional PyTorch, JAX or provider plugins need separate compatible environments. Local simulation needs no credentials; hardware requires provider credentials and network access.

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
K-Dense Inc.
Publisher
K-Dense (Community)
Source
K-Dense-AI/scientific-agent-skills · skills/pennylane · commit a25cf9e
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by K-Dense Inc. or K-Dense.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download pennylane.zip