Agent skill

Mq Variational Training

by mindspore-ai in mindspore-ai/mindquantum

Build and train variational quantum algorithms (VQE, QAOA, QML, QNN) with MindQuantum.

Apache-2.0Auto-check passedResearch & Science

Install Mq Variational Training

skills CLI
$ npx skills add mindspore-ai/mindquantum --skill mq-variational-training -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install mindspore-ai/mindquantum mq-variational-training --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/mindspore-ai/mindquantum.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/mq-variational-training .claude/skills/mq-variational-training && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
mq-variational-training
GitHub stars
102
Token cost
~2.5k tokens
SKILL.md length
178 words
Files
2
Skills in repo
6
Repo updated
First seen
Licence
Apache-2.0

At a glance

Build and train variational quantum algorithms (VQE, QAOA, QML, QNN) with MindQuantum.

  • The user wants to train a parameterized quantum circuit
  • SKILL.md covers The MindQuantum Variational…, Pattern 1: SciPy Optimization…, Pattern 2: MindSpore MQLayer… and Pattern 3: MQAnsatzOnlyLayer…, plus 6 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Build a quantum neural network

What it does

Mq Variational Training is an agent skill from mindspore-ai/mindquantum. Build and train variational quantum algorithms (VQE, QAOA, QML, QNN) with MindQuantum. Covers the encoder/ansatz circuit pattern, getexpectationwithgrad, gradient-based optimization with SciPy or MindSpore MQLayer, and hybrid quantum-classical training loops. Use whenever the user wants to train a parameterized quantum circuit, run VQE, implement QAOA, build a quantum neural network, compute quantum gradients, use MQLayer, optimize circuit parameters, or do any hybrid quantum-classical machine learning with…

Its SKILL.md is about 2.5k tokens, which your agent loads only when the skill is triggered. The skill folder holds 2 other files (for example `reference/ansatz-catalog.md`).

It sits in Research & Science, covering Quantum computing, Deep learning and Machine learning. The repository describes itself as: MindQuantum is a quantum machine learning library that can be used to build and train different quantum neural networks. The licence is Apache-2.0.

When your agent uses it

  • The user wants to train a parameterized quantum circuit
  • Build a quantum neural network
  • Compute quantum gradients
  • Optimize circuit parameters

Example prompts

  • “/mq-variational-training”

Requirements

  • Python 3

What it can do on your machine

Read from SKILL.md and the folder at commit 2a0ca08. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are python).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Mq Variational Training loads about 2.5k tokens when it runs. Until then it costs about 138 tokens; SKILL.md has 178 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~138
When it runs · the whole SKILL.md, loaded when a task matches
~2.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from mindspore-ai/mindquantum at commit 2a0ca08, republished under its Apache-2.0 licence (© mindspore-ai). 178 words, ~2,499 tokens.

Download SKILL.mdSave it as .claude/skills/mq-variational-training/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
mq-variational-training
description
Build and train variational quantum algorithms (VQE, QAOA, QML, QNN) with MindQuantum. Covers the encoder/ansatz circuit pattern, get_expectation_with_grad, gradient-based optimization with SciPy or MindSpore MQLayer, and hybrid quantum-classical training loops. Use whenever the user wants to train a parameterized quantum circuit, run VQE, implement QAOA, build a quantum neural network, compute quantum gradients, use MQLayer, optimize circuit parameters, or do any hybrid quantum-classical machine learning with MindQuantum.

Variational Training with MindQuantum

This skill covers common workflows for training parameterized quantum circuits, from circuit design through optimization to result extraction.

The MindQuantum Variational Pipeline

Common MindQuantum variational workflows use this pipeline:

text
Circuit Design → Hamiltonian → Simulator.get_expectation_with_grad → Optimization Loop → Results
     │                │                      │                              │
  encoder +        QubitOperator →       GradOpsWrapper              SciPy or MindSpore
  ansatz           Hamiltonian           encoder+ansatz: f,g_enc,g_ans
                                       ansatz-only: f,g

Pattern 1: SciPy Optimization (No MindSpore Required)

Use this pattern when the objective is a scalar expectation value and you want a plain NumPy/SciPy optimization loop.

python
import numpy as np
from scipy.optimize import minimize
from mindquantum.core.circuit import Circuit
from mindquantum.core.gates import H, RY, RX, CNOT
from mindquantum.core.operators import QubitOperator, Hamiltonian
from mindquantum.simulator import Simulator

# 1. Build ansatz (no encoder — pure variational)
n_qubits = 4
ansatz = Circuit()
for i in range(n_qubits):
    ansatz += RY(f"p{i}").on(i)
for i in range(n_qubits - 1):
    ansatz += CNOT.on(i + 1, i)
for i in range(n_qubits):
    ansatz += RY(f"q{i}").on(i)

# 2. Define Hamiltonian
ham = Hamiltonian(
    QubitOperator("Z0 Z1", -1.0)
    + QubitOperator("Z1 Z2", -1.0)
    + QubitOperator("Z2 Z3", -1.0)
    + QubitOperator("X0", -0.5)
)

# 3. Create gradient operator
sim = Simulator("mqvector", n_qubits)
grad_ops = sim.get_expectation_with_grad(ham, ansatz)


# 4. Wrap for SciPy (value + gradient)
def fun(params):
    f, g = grad_ops(params)
    return np.real(f)[0, 0], np.real(g)[0, 0]


# 5. Optimize
x0 = np.random.uniform(-np.pi, np.pi, len(ansatz.params_name))
result = minimize(fun, x0, method="BFGS", jac=True)
print(f"Ground state energy: {result.fun:.6f}")

Pattern 2: MindSpore MQLayer Training

Use this pattern when a parameterized quantum circuit is part of a MindSpore model. Requires MindSpore.

python
import numpy as np
import mindspore as ms
from mindspore import nn
from mindquantum.core.circuit import Circuit
from mindquantum.core.gates import RY, CNOT
from mindquantum.core.operators import QubitOperator, Hamiltonian
from mindquantum.framework import MQLayer
from mindquantum.simulator import Simulator

ms.set_device("CPU")
ms.set_context(mode=ms.PYNATIVE_MODE)

# 1. Encoder: data → quantum state
encoder = Circuit()
for i in range(4):
    encoder += RY(f"x{i}").on(i)
encoder.as_encoder()

# 2. Ansatz: trainable weights
ansatz = Circuit()
for i in range(4):
    ansatz += RY(f"w{i}").on(i)
for i in range(3):
    ansatz += CNOT.on(i + 1, i)
ansatz.as_ansatz()

circuit = encoder + ansatz

# 3. Hamiltonian and gradient operator
ham = Hamiltonian(QubitOperator("Z0"))
sim = Simulator("mqvector", circuit.n_qubits)
grad_ops = sim.get_expectation_with_grad(ham, circuit)

# 4. Create MQLayer (acts as a MindSpore nn.Cell)
qnet = MQLayer(grad_ops)

# 5. Standard MindSpore training.
# MQLayer returns the circuit expectation; wrap it with a loss cell for supervised tasks.
opti = nn.Adam(qnet.trainable_params(), learning_rate=0.1)
train_net = nn.TrainOneStepCell(qnet, opti)

# Training loop
for epoch in range(100):
    encoder_data = ms.Tensor(np.random.uniform(0, np.pi, (1, 4)).astype(np.float32))
    loss = train_net(encoder_data)
    if epoch % 20 == 0:
        print(f"Epoch {epoch}: loss = {float(loss.asnumpy().mean()):.4f}")

# 6. Extract trained parameters
print(dict(zip(ansatz.params_name, qnet.weight.asnumpy())))

Pattern 3: MQAnsatzOnlyLayer (No Encoder Data)

For VQE and QAOA where there is no classical input data:

python
from mindquantum.framework import MQAnsatzOnlyLayer

# Circuit has only ansatz parameters (no encoder)
grad_ops = sim.get_expectation_with_grad(ham, ansatz_circuit)
net = MQAnsatzOnlyLayer(grad_ops)

opti = nn.Adam(net.trainable_params(), learning_rate=0.05)
train_net = nn.TrainOneStepCell(net, opti)

for i in range(300):
    loss = train_net()
    if i % 50 == 0:
        print(f"Step {i}: E = {loss.asnumpy():.6f}")

VQE Workflow

python
from mindquantum.core.circuit import Circuit
from mindquantum.core.gates import H, RY, RX, CNOT
from mindquantum.core.operators import QubitOperator, Hamiltonian
from mindquantum.simulator import Simulator
import numpy as np
from scipy.optimize import minimize

# Hamiltonian for H2 (simplified)
ham_str = (
    QubitOperator("", -0.8)
    + QubitOperator("Z0", 0.17)
    + QubitOperator("Z1", 0.17)
    + QubitOperator("Z0 Z1", 0.16)
    + QubitOperator("X0 X1", 0.04)
    + QubitOperator("Y0 Y1", 0.04)
)
ham = Hamiltonian(ham_str)

# Hardware-efficient ansatz
ansatz = Circuit()
ansatz += RY("a0").on(0)
ansatz += RY("a1").on(1)
ansatz += CNOT.on(1, 0)
ansatz += RY("a2").on(0)
ansatz += RY("a3").on(1)

sim = Simulator("mqvector", 2)
grad_ops = sim.get_expectation_with_grad(ham, ansatz)


def energy_and_grad(params):
    f, g = grad_ops(params)
    return np.real(f)[0, 0], np.real(g)[0, 0]


x0 = np.zeros(4)
result = minimize(energy_and_grad, x0, method="BFGS", jac=True)
print(f"VQE Energy: {result.fun:.6f} Ha")

QAOA Workflow

python
from mindquantum.core.circuit import Circuit, UN
from mindquantum.core.gates import H, Rzz, RX
from mindquantum.core.operators import QubitOperator, Hamiltonian
from mindquantum.simulator import Simulator
import networkx as nx
import numpy as np
from scipy.optimize import minimize

# 1. Problem: Max-Cut on a graph
g = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)])
n = g.number_of_nodes()

# 2. Cost Hamiltonian from edges
ham = QubitOperator()
for u, v in g.edges:
    ham += QubitOperator(f"Z{u} Z{v}")

# 3. QAOA circuit
p = 3  # number of layers
init = Circuit(UN(H, range(n)))
ansatz = Circuit()
for layer in range(p):
    for u, v in g.edges:
        ansatz += Rzz(f"g{layer}").on([u, v])
    for node in range(n):
        ansatz += RX(f"b{layer}").on(node)

circuit = init + ansatz

# 4. Optimize
sim = Simulator("mqvector", n)
grad_ops = sim.get_expectation_with_grad(Hamiltonian(ham), circuit)


def cost(params):
    f, g = grad_ops(params)
    return np.real(f)[0, 0], np.real(g)[0, 0]


result = minimize(cost, np.random.uniform(-np.pi, np.pi, 2 * p), method="BFGS", jac=True)

# 5. Extract solution
pr = dict(zip(circuit.params_name, result.x))
sim.reset()
sim.apply_circuit(circuit, pr)
state = sim.get_qs()
probs = np.abs(state) ** 2
best = np.argmax(probs)
print(f"Most probable bitstring: {bin(best)[2:].zfill(n)}, Cost: {result.fun:.4f}")

QML Classification Workflow

python
from mindquantum.core.circuit import Circuit
from mindquantum.core.gates import RY, CNOT
from mindquantum.core.operators import QubitOperator, Hamiltonian
from mindquantum.framework import MQLayer
from mindquantum.simulator import Simulator
import mindspore as ms
from mindspore import nn
import numpy as np

ms.set_device("CPU")
ms.set_context(mode=ms.PYNATIVE_MODE)

n_features = 4
n_qubits = 4

# Encoder: amplitude encoding via rotations
encoder = Circuit()
for i in range(n_features):
    encoder += RY(f"f{i}").on(i)
encoder.as_encoder()

# Ansatz: entangling layers
ansatz = Circuit()
for i in range(n_qubits):
    ansatz += RY(f"w{i}").on(i)
for i in range(n_qubits - 1):
    ansatz += CNOT.on(i + 1, i)
for i in range(n_qubits):
    ansatz += RY(f"v{i}").on(i)

# Measurement: Z expectation as prediction
ham = Hamiltonian(QubitOperator("Z0"))
sim = Simulator("mqvector", n_qubits)
grad_ops = sim.get_expectation_with_grad(ham, encoder + ansatz)


# Hybrid model: quantum layer inside classical network
class HybridQNN(nn.Cell):
    def __init__(self):
        super().__init__()
        self.qnn = MQLayer(grad_ops)
        self.dense = nn.Dense(1, 2)  # map expectation → 2 classes

    def construct(self, x):
        q_out = self.qnn(x)
        return self.dense(q_out)


model = HybridQNN()
loss_fn = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
opti = nn.Adam(model.trainable_params(), learning_rate=0.05)
train_net = nn.TrainOneStepCell(nn.WithLossCell(model, loss_fn), opti)

# Train on data
# train_features: [batch, 4], train_labels: [batch]
# for epoch in range(20):
#     train_net(train_features, train_labels)

Optimizer Notes

ScenarioAPI-compatible options
SciPy with gradients from get_expectation_with_gradBFGS, L-BFGS-B, or another SciPy method accepting jac=True
SciPy without using gradientsGradient-free SciPy methods such as Nelder-Mead or COBYLA
MindSpore trainingMindSpore optimizers such as nn.Adam or nn.SGD over MQLayer / MQAnsatzOnlyLayer trainable parameters

Barren Plateau Awareness

MindQuantum exposes ansatz_variance for checking gradient variance of a selected parameter.

python
from mindquantum.algorithm.nisq import ansatz_variance

# Check one trainable parameter before training
var = ansatz_variance(
    ansatz,
    ham,
    focus=ansatz.params_name[0],
    init_batch=100,
    sim=sim,
)
print(var)

Reference Files

FileWhen to Read
reference/ansatz-catalog.mdChoosing between built-in ansätze (HEA, UCCSD, QAOA, StronglyEntangling, etc.)

© mindspore-ai, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file in skills/mq-variational-training of mindspore-ai/mindquantum.

  • SKILL.md
  • reference/ansatz-catalog.md

Open the folder on GitHubat commit 2a0ca08

Compare with similar skills

Mq Variational Training next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Mq Variational Training compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Mq Variational Training this skillmindspore-ai/mindquantum102—~2.5kAutomated safety check: PassApache-2.0
Qiskit 2.x Quantum ML Referenceaiming-lab/AutoResearchClaw15k—~4.7kAutomated safety check: PassMIT
tangermeme Genomic Model Analysisjmschrei/tangermeme318—~1.6kAutomated safety check: PassMIT
PyHealth Clinical ML Toolkitdavila7/claude-code-templates33k11 repos~4.4kAutomated safety check: PassMIT
Deepchemdavila7/claude-code-templates33k10 repos~4.4kAutomated safety check: PassMIT
Pennylanedavila7/claude-code-templates33k7 repos~1.9kAutomated safety check: PassMIT

Similar skills

  • Qiskit 2.x Quantum ML Reference

    aiming-lab/AutoResearchClaw

    Reference patterns for writing qiskit 2.x code for variational quantum machine learning: feature maps, VQC training, VQE for chemistry, MPS circuits and noise models.

    15k GitHub stars~4.7k tokensUpdated 1 mo ago
    Research & ScienceAuto-check passed
  • Routes agents to the right tangermeme reference for analyzing trained genomic deep learning models, from attributions and motif experiments to variant effects and design.

    318 GitHub stars~1.6k tokensUpdated 3 days ago
    Research & ScienceAuto-check passed
  • PyHealth Clinical ML Toolkit

    davila7/claude-code-templates

    Builds machine learning pipelines on clinical data with PyHealth: EHR datasets, prediction tasks, medical code mapping, healthcare models and evaluation.

    33k GitHub starsUsed in 11 repos~4.4k tokens
    Research & ScienceAuto-check passed
  • Deepchem

    davila7/claude-code-templates

    Molecular machine learning toolkit. An agent skill from davila7/claude-code-templates.

    33k GitHub starsUsed in 10 repos~4.4k tokens
    Research & ScienceAuto-check passed
  • Pennylane

    davila7/claude-code-templates

    Cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry.

    33k GitHub starsUsed in 7 repos~1.9k tokens
    Research & ScienceAuto-check passed
  • Scaffold Example

    comet-ml/comet-examples

    Scaffold a brand-new Comet example in this repo from the canonical template under templates/integration-example/.

    174 GitHub stars~1k tokensUpdated 1 mo ago
    AI & LLM EngineeringAuto-check passed

More from mindspore-ai/mindquantum

  • Mindquantum

    mindspore-ai/mindquantum

    Build, simulate, and analyze quantum circuits with MindQuantum.

    102 GitHub stars~2.3k tokensUpdated 19 days ago
    Auto-check passed
  • Mq Circuit Compiler

    mindspore-ai/mindquantum

    Compile and optimize quantum circuits for hardware execution using MindQuantum's compiler pipeline.

    102 GitHub stars~1.7k tokensUpdated 19 days ago
    Auto-check passed
  • Mq Noisy Simulation

    mindspore-ai/mindquantum

    Simulate noisy quantum circuits with MindQuantum. An agent skill from mindspore-ai/mindquantum.

    102 GitHub stars~2.2k tokensUpdated 19 days ago
    Auto-check passed
  • Mq Qaia Solver

    mindspore-ai/mindquantum

    Solve Ising/QUBO-style combinatorial optimization problems using MindQuantum's Quantum Annealing-Inspired Algorithms (QAIA).

    102 GitHub stars~2.2k tokensUpdated 19 days ago
    Auto-check passed
  • Mq Quantum Chemistry

    mindspore-ai/mindquantum

    Run quantum chemistry simulations with MindQuantum. An agent skill from mindspore-ai/mindquantum.

    102 GitHub stars~2.2k tokensUpdated 19 days ago
    Auto-check passed

Questions about Mq Variational Training

What does Mq Variational Training do?

Build and train variational quantum algorithms (VQE, QAOA, QML, QNN) with MindQuantum. Mq Variational Training is an agent skill from mindspore-ai/mindquantum. Build and train variational quantum algorithms (VQE, QAOA, QML, QNN) with MindQuantum.

When should I use Mq Variational Training?

Mq Variational Training fits situations like: the user wants to train a parameterized quantum circuit; build a quantum neural network; compute quantum gradients; optimize circuit parameters.

How do I install Mq Variational Training in Claude Code?

Run `npx skills add mindspore-ai/mindquantum --skill mq-variational-training -a claude-code`. Or copy the skill folder (skills/mq-variational-training in mindspore-ai/mindquantum) into .claude/skills/mq-variational-training in your project. Claude Code loads it when a task matches its description.

How do I install Mq Variational Training in Codex?

Run `npx skills add mindspore-ai/mindquantum --skill mq-variational-training -a codex`. Or copy the skill folder (skills/mq-variational-training in mindspore-ai/mindquantum) into .agents/skills/mq-variational-training in your project. Codex loads it when a task matches its description.

Can I use Mq Variational Training in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add mindspore-ai/mindquantum --skill mq-variational-training -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/mq-variational-training, .gemini/skills/mq-variational-training, .github/skills/mq-variational-training and .opencode/skills/mq-variational-training in your project.

What does Mq Variational Training need to run?

SKILL.md names no scripts, command-line tools or credentials: Mq Variational Training is instructions for the agent only. Our summary lists: Python 3.

Does Mq Variational Training access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Mq Variational Training safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Mq Variational Training use?

Mq Variational Training is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Mq Variational Training use?

About 2.5k tokens (SKILL.md is roughly 10k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Mq Variational Training?

Skills that share tags, products or a category with Mq Variational Training: Qiskit 2.x Quantum ML Reference (aiming-lab/AutoResearchClaw, 15k stars), tangermeme Genomic Model Analysis (jmschrei/tangermeme, 318 stars), PyHealth Clinical ML Toolkit (davila7/claude-code-templates, 33k stars) and Deepchem (davila7/claude-code-templates, 33k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Mq Variational Training?

mindspore-ai (a GitHub organization) maintains it in mindspore-ai/mindquantum, which has 102 GitHub stars. The repository holds 6 skills in this directory. The repository was last updated on September 21, 2026.

Source: mindspore-ai/mindquantum on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.