Imported from xpclove/qblas (
AGENTS.md). Install upstream withnpx skills add xpclove/qblas. Copyright stays with the author.
QBLAS Agent Guidelines
Project Overview
QBLAS (Quantum Basic Linear Algebra Subprograms) is an open-source quantum computing library for quantum linear algebra and quantum simulation.
- Version: v0.3.2
- Tech Stack: Microsoft QDK 1.28.0 (Rust/Python-based Q# compiler)
- License: GPL v3
- Location:
src/qblas/
Build & Test
Prerequisites
# Python 3.10+ with QDK 1.28
pip install qsharp
Commands
# Full build + test
./build.sh
# Or run tests directly
python tools/run_all_tests.py
# Compile Q# library only (syntax check)
python3.11 -c "import qsharp; qsharp.eval(open('src/qblas/qblas/q_com.qs').read())"
Code Conventions
Code Quality Requirements
- 简洁准确: Code should be concise and precise, no redundancy
- 注释充分: Every module, operation, and function must have detailed comments explaining:
- Purpose and functionality
- Input/output parameters
- Algorithm description
- Complexity analysis (time/space)
- 可读性高: Clear naming, consistent formatting, logical structure
- 参考文献: Every module must include:
- Reference citation (paper title, venue, year)
- URL link to the original paper/source
- Brief explanation of how the algorithm is implemented
Example module header:
// ============================================================
// Module Name: Quantum Singular Value Transformation (QSVT)
//
// Purpose: Provides unified framework for quantum linear algebra
// through polynomial transformations of singular values.
//
// Algorithm: Implements the QSVT framework from Gilyén et al.
// Transforms singular values by applying polynomials via
// controlled rotations on ancilla qubits.
//
// Complexity: O(poly(log(1/ε))) for polynomial degree p
//
// Reference: Gilyén et al., "Quantum Singular Value Transformation"
// STOC 2019. https://arxiv.org/abs/1806.01838
// ============================================================
File Organization
- Library files:
src/qblas/qblas/*.qs - Test files:
src/qblas/test/test*.qs+Driver.cs - One
.qsfile per module (e.g.,q_gemv.qs,q_qsvt.qs)
Naming Conventions
| Element | Convention | Example |
|---|---|---|
| Namespace | qblas |
namespace qblas { ... } |
| Operation | q_<module>_<name> |
q_gemv_diagonal, q_qsvt_polynomial_transform |
| Function | q_<module>_<name> |
q_qsvt_normalize_vector, q_be_compute_scaling |
| NewType | q_<type> or q<Module>_<type> |
qsvt_block_oracle, q_matrix_1_sparse_oracle |
| Test | test_<module>_<name> |
test_gemv_diagonal, test_qsvt_apply_diagonal |
NewType Definitions
CORRECT pattern (operation type):
// Correct: single parens for tuple type
newtype qsvt_block_oracle = (Qubit[], Qubit[]) => Unit is Adj + Ctl;
WRONG pattern (extra wrapping parens - causes parse error in new QDK):
// Bad: extra outer parentheses
newtype qsvt_block_oracle = ((Qubit[], Qubit[]) => Unit is Adj + Ctl);
Operation Signatures
Operations that need adjoint/controlled should use body (...) with explicit specializations:
operation q_gemv(...) : Unit is Adj + Ctl {
// implementation
}
Function Signatures
Pure functions (no quantum operations) should be declared as function:
function q_qsvt_normalize_vector(v : Double[]) : Double[] {
let norm = Sqrt(SquaredNorm(v));
return v; // simplified
}
Common Patterns
Qubit Allocation
// Allocated qubits - use 'use'
use qs = Qubit[4];
use (qs1, qs2) = (Qubit[3], Qubit[4]);
// Borrowed qubits - use 'borrowed'
borrowed qs = Qubit[2];
Loop Patterns
// Standard for loop
for (i in 0 .. n - 1) { ... }
// Range loops
for (i in 1 .. n - 1) { ... }
Mutable Variables
mutable result = 0.0;
set result = result + 1.0;
// For arrays
mutable arr = [];
set arr += [new_element];
Conditional Checks
// Ternary operator
let value = condition ? true_val | false_val;
// Boolean expressions (use 'and', 'or', not &&, ||)
if (a > 0.0 and b < 1.0) { ... }
Resolved Issues (v0.2.11)
The following issues from earlier versions have been resolved:
1. Exp() Expression Bug (RESOLVED)
Issue: Exp(-lambda_reg) caused compiler error QS0001 "Expected type (Pauli[], Double, Qubit[])"
Solution: Use placeholder value directly:
// Resolved: use placeholder (Exp(-lambda) causes QS0001)
let exp_val = 0.5;
let ck = 2.0 * exp_val / denom;
2. Array Slice Out of Bounds (RESOLVED)
Issue: qs_data[0 .. i - 1] failed when i = 0 (empty range error)
Solution: Start loop from 1 instead of 0:
// Resolved: loop starts from 1, so i-1 >= 0 always
for (i in 1 .. n - 1) {
(Controlled Ry)(qs_data[0 .. i - 1], (angle, qs_ancilla));
}
3. Q# Version Compatibility
- Project uses QDK 1.28.0 (Rust/Python-based Q# compiler)
- Modern Q# syntax, no deprecation warnings
- All 310 tests pass
Test Patterns
Test Operation Signature
operation test_<module>_<name>(p : Int) : <ReturnType> {
// test implementation (no body { } wrapper)
return <expected_value>;
}
Test Entry Point (Python runner)
# Python test runner pattern (tools/run_all_tests.py)
result = qsharp.eval(f"Quantum.test.{op_name}({arg})")
print(f" {op_name}({arg}) = {result}")
Running Tests
- All tests run via
python tools/run_all_tests.py(or./build.sh) - Tests use QDK 1.28 Rust native simulator (not .NET QuantumSimulator)
- Return types:
Double,Int,Result(One/Zero)
Adding New Modules
Steps
- Create
q_<module>.qsinsrc/qblas/qblas/ - Implement operations/functions following naming conventions
- Add tests to
test_gemv_gemm.qsor new test file - Add test entries to Python runner (
tools/run_all_tests.py) - Build and verify:
python tools/run_all_tests.py
Module Template
namespace qblas
{
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Canon;
import Std.Convert.*;
import Std.Math.*;
// ============================================================
// Module Description
//
// Brief description of what this module does.
// Reference: Citation or algorithm source
// ============================================================
// Oracle types (if needed)
newtype q_<type>_oracle = (Qubit[], Qubit[], Qubit[]) => Unit is Adj + Ctl;
// Core operations
operation q_<module>_core(...) : Unit is Adj + Ctl {
// implementation
}
// Helper functions
function q_<module>_helper(...) : ... {
// pure function
}
}
Project Structure
qblas/
├── qsharp.json # Q# project manifest (QDK 1.28)
├── .gitignore
├── src/qblas/
│ ├── qblas/ # Core library (55 modules)
│ │ ├── q_*.qs # Quantum operations
│ │ ├── qblas.csproj # (legacy, retained for reference)
│ │ └── test_package_ref.csproj # (legacy)
│ └── test/ # Test suite
│ ├── test*.qs # Q# test operations
│ ├── Driver.cs # (legacy C# runner, retained)
│ └── test.csproj # (legacy)
├── tools/ # Python test & migration tools
│ ├── run_all_tests.py # Python test runner (replaces Driver.cs)
│ ├── migrate_qsharp.py # Q# syntax migrator (body->is Adj+Ctl)
│ ├── fix_for_loops.py # for(->for loop fix
│ ├── fix_remaining.py # import/math function fix
│ └── fix_using.py # using->use fix
├── build.sh # Build/test script
├── README.md # Project documentation
└── doc/
└── qblas-develop-report.md # Technical analysis
Quick Reference
Key Files
q_gemv.qs: Matrix-vector multiplicationq_gemm.qs: Matrix-matrix multiplicationq_svd_vartime.qs: Variable-time SVDq_hhl_enhanced.qs: Enhanced HHL algorithmq_qsvt.qs: Quantum Singular Value Transformationq_regularized_ls.qs: Regularized least squaresq_block_encoding.qs: Block encoding primitivesq_cg.qs,q_lanczos.qs,q_krylov.qs,q_gmres.qs: Krylov methodsq_gradient_descent.qs,q_newton.qs: Optimizationq_pca.qs,q_ridge.qs: Dimensionality reductionq_trisol.qs: Tridiagonal solverq_qsp.qs: Quantum Signal Processingq_trotter_suzuki.qs,q_2sparse.qs: Hamiltonian simulationq_amplitude_amplification.qs: Amplitude amplificationq_qpe_modern.qs: Modern phase estimationq_gradient_estimation.qs: Gradient estimationq_block_encoding_v2.qs: Enhanced block encodingq_vqe.qs: VQE components
Critical Constants
- Precision threshold:
1e-10 - Array length: use
Length(array) - Quantum gates:
Ry,CNOT,H,X, etc. - Measurement:
M(q)returnsResult
Git Workflow
# Version bump (update version in README.md + qsharp.json before committing)
# Current: v0.3.2 -> next: v0.3.2
# Update version in README.md, qsharp.json before committing
# Stage files
git add src/qblas/qblas/q_newmodule.qs
git add src/qblas/test/test_newmodule.qs
git add tools/run_all_tests.py # add test entries
git add README.md qsharp.json # version bump
# Commit with descriptive message
git commit -m "feat: add q_newmodule with operations..."
APP Demo Development
1. Directory & Naming
app/
├── demo_<name>.qs # 主 demo 文件
├── test_demo_<name>.qs # 配套测试文件
| 元素 | 规则 | 示例 |
|---|---|---|
| 文件名 | demo_<name>.qs |
demo_qnn_classifier.qs |
| 主操作 | Demo<Name>() |
DemoQnnClassifier() |
| 辅助操作 | q_demo_<name>_<step> |
q_demo_qnn_forward |
| 测试 | test_demo_<name> |
test_demo_qnn_classifier |
2. File Header Requirements
每个 demo 文件头部必须包含以下 7 项(模板):
// ============================================================
// Demo: <标题>
//
// What it does:
// 一句话说明解决的问题 + 用到了 N 个 QBLAS 模块
//
// Architecture:
// - Qubits: N(必须 ≥ 8,除非算法本身限制)
// - Ansatz: <使用的 ansatz 或电路结构>
// - Parameters: <关键参数说明>
//
// Input:
// - 输入数据的来源(硬编码/参数)
// - 数据维度,编码方式
//
// Output:
// - 输出格式(整数位编码/浮点)
// - 每个 bit 的含义
// - 量子测量部分注明概率性
// - 确定性部分注明已验证
//
// Pipeline steps and module mapping:
// 编号列出每一步 + 调用模块 + 功能
// 每步格式:Step N: <模块名> → <函数名> — <说明>
//
// Verification:
// - 列出所有 Fact() 断言点
// - 每个断言注明预期值
// - 量子步骤注明无需断言仅验不崩溃
//
// Reference:
// [1] 论文标题, 期刊/arXiv (年份)
// ============================================================
3. Code Requirements
| 规则 | 强制 | 说明 |
|---|---|---|
| 调用库函数 | ✅ 必须 | 禁止直接使用 Ry, H, CNOT 等手动门电路。必须通过 q_xxx 库函数调用 |
| 量子比特数 | ✅ 必须 | ≥ 8 qubits(除非算法有本质限制如 HHL 2×2 系统) |
| 量子测量 | ✅ 必须 | 每个 demo 至少 1 次 M() 测量 |
| 量子执行 | ✅ 必须 | 至少 1 个量子操作(除 oracle 定义外不得仅为纯经典函数调用) |
| Fact() 断言 | ✅ 必须 | 所有确定性步骤必须加 Fact() 验证预期值 |
| 结果范围验证 | ✅ 必须 | 概率性结果至少 Fact(result >= 0) |
| 测试文件 | ✅ 必须 | 配套 test_demo_<name>.qs,至少验证 result > 0 |
| Oracle 定义 | ⚠️ 例外 | 自定义 oracle 不可避免使用 Rz/Ry 门,豁免手动门限制 |
| 通用接口 + 小规模测试 | ✅ 必须 | 主操作必须提供通用接口(接受任意参数);测试用小规模参数调用同一接口验证正确性。禁止为测试单独写一个简化版操作 |
4. Test Requirements
operation test_demo_<name>(p : Int) : Int {
let result = Demo<Name>();
Fact(result > 0, "demo_<name>: result must be > 0");
return result;
}
- 测试自动注册到 CI(
run_all_tests.py自动发现app/下所有test_*操作) - 每个 demo 必须 1 个对应测试文件
- 接口复用: 测试必须调用主 demo 的同一入口操作,而非封装简化版
- 参数缩放: 测试用小规模参数(少量 qubits、少量轮次)确保快速验证
5. Acceptance Checklist
□ 文件头含 7 项完整信息
□ 输入/输出明确描述
□ Architecture 段含 qubit 数、参数数
□ 所有确定性步骤有 Fact() 断言
□ 量子步骤至少验不崩溃 + 合法范围
□ 测试至少验证 result > 0
□ 主操作提供通用接口,测试用小规模参数调用
□ ≥ 8 qubits(除非算法有本质限制)
□ 零手动门电路(除 oracle 定义外全部通过库函数调用)
□ 至少 1 次量子测量
□ Demo + Test 在同目录
□ 命名符合规范
□ 运行全部 350+ 测试不冲突
6. Completed APP Demos
| Demo | Qubits | 库调用 | 验证点 | 手动门 |
|---|---|---|---|---|
demo_ml_pipeline |
2 | 12 个 | 7 | 0 |
demo_hhl_svd |
7 | 5 个 | 5 | 3(必) |
demo_qnn_classifier |
20 | 10 个 | 10 | 1(必) |
demo_vqe_execution |
8 | 11 个 | 11 | 0 |
demo_qsvt_transform |
10 | 8 个 | 9 | 0 |
demo_hamiltonian_sim |
16 | 11 个 | 12 | 0 |
demo_shor_factor |
8 | 10 个 | 7 | 6(必) |
demo_qkmeans |
17 | 12 个 | 7 | 0 |
demo_qpe_standalone |
12 | 7 个 | 5 | 1(必) |
demo_block_lcu |
10 | 10 个 | 8 | 0 |
demo_teleport |
24 | 3 个 | 5 | 0 |
demo_spectral_analysis |
8 | 8 个 | 8 | 0 |
demo_error_mitigation |
2 | 8 个 | 8 | 0 |
demo_gradient_estimation |
4 | 9 个 | 8 | 1(必) |
demo_walk_gemv |
10 | 6 个 | 11 | 0 |
demo_krylov_arnoldi |
21 | 4 个 | 20 | 0 |
demo_gmres_cg |
23 | 4 个 | 14 | 0 |
demo_lin_solvers |
21 | 9 个 | 25 | 0 |
所有新增 demo 须以此为质量基准。
Completed Modules
v0.2.9 - 17 New Quantum Algorithm Modules
Krylov Subspace Methods:
q_cg.qs: Conjugate Gradient for linear systemsq_lanczos.qs: Lanczos tridiagonalizationq_gmres.qs: Generalized Minimal Residualq_krylov.qs: Krylov subspace operations
Optimization:
q_gradient_descent.qs: Gradient descent optimizationq_newton.qs: Second-order Newton method
Dimensionality Reduction:
q_pca.qs: Quantum PCAq_ridge.qs: Ridge regression (Tikhonov regularization)
Linear Solvers:
q_trisol.qs: Tridiagonal system solver
Quantum Signal Processing:
q_qsp.qs: QSP framework for eigenvalue transformation
Hamiltonian Simulation:
q_trotter_suzuki.qs: High-order Trotter-Suzuki decompositionq_2sparse.qs: 2-sparse Hamiltonian simulation
Amplitude Amplification:
q_amplitude_amplification.qs: QAA with optimal iterations
Phase Estimation:
q_qpe_modern.qs: Bayesian-inspired phase estimation
Gradient Estimation:
q_gradient_estimation.qs: Parameter shift rule, quantum natural gradient
Block Encoding:
q_block_encoding_v2.qs: QROM, LCU, OAA primitives
Variational Algorithms:
q_vqe.qs: VQE components (HEA, QAOA, SU2, optimizers)
v0.2.13 - 9 Modules Enhanced with Quantum Operations
Krylov Subspace Methods (Quantum Implementation):
q_krylov.qs: Arnoldi iteration with quantum walk + SWAP test (6 new ops)q_lanczos.qs: Lanczos tridiagonalization with three-term recurrence (5 new ops)q_gmres.qs: GMRES solver with Hessenberg construction (4 new ops)
Optimization Methods (Quantum Implementation):
q_conjugate_gradient.qs: CG linear system solver (3 new ops)q_gradient_descent.qs: Gradient descent optimizer (2 new ops)q_newton.qs: Newton method with Hessian estimation (2 new ops)
Matrix Decomposition & Applications:
q_pca.qs: PCA with QPE eigenvalue estimation (2 new ops)q_ridge_regression.qs: Ridge regression solver (2 new ops)q_triangular.qs: Triangular system solver (3 new ops)
Infrastructure:
- Removed: q_cg_residual_norm, q_gmres_norm, q_krylov_residual_norm, q_trisol_norm, q_gmres_init_vec
- Total: 293 tests pass
v0.2.14 - Remaining 15 Layer 0 Modules Enhanced with Quantum Operations
Hamiltonian Simulation:
q_qubitization.qs: Qubitization-based simulation with QSP phases (1 new op)q_lcu_optimized.qs: Single-ancilla LCU SELECT+PREPARE circuit (2 new ops)q_gibbs.qs: Gibbs state preparation via imaginary time evolution (1 new op)q_timedependent.qs: Time-dependent H(t) simulation with Strang splitting (2 new ops)
Quantum Primitives:
q_inner_product.qs: SWAP test measurement operation (1 new op)q_vector_norm.qs: State norm estimation via measurement statistics (1 new op)q_gradient_estimation.qs: Parameter shift circuit execution (1 new op)
Classical→Quantum Solvers:
q_lu.qs: HHL-style quantum linear solve (1 new op)q_cholesky.qs: SPD quantum linear solve (1 new op)q_qr.qs: Quantum least-squares solver (1 new op)q_matrix_add.qs: A+B block encoding via sequential q_gemv (1 new op)q_kronecker.qs: A⊗B application to composite quantum state (1 new op)q_error_mitigation.qs: ZNE circuit execution with noise extrapolation (1 new op)
Kernel Methods:
q_kernel.qs: Quantum kernel matrix entry computation via SWAP test (1 new op)
Total: 18 new quantum operations, 308 tests pass
v0.3.2 - QDK 1.28 Migration
- Full migration from .NET-based QDK 0.28.x (archived qsharp-compiler) to Rust/Python-based QDK 1.28.0
- Syntax transformations across all 60 .qs files:
body { ... } adjoint auto;→is Adj + Ctlannotation (149 operations)for (...)→for ...(555 instances)using (qs = ...)→use qs = ...(16 instances)PowD(a,b)→a ^ b,ExpD(x)→E() ^ xopen Microsoft.Quantum.{Math,Convert}→import Std.{Math,Convert}.*- NewType:
((...))→(...)(removed extra wrapping parens) new Qubit[n]→ array concatenation;new (Qubit[])→ incremental build
- Test system: C#
Driver.cs+QuantumSimulator→ Pythontools/run_all_tests.py+ Rust native simulator - Build: .NET 6.0 +
dotnet build→ Python 3.10+ +pip install qsharp - Total: 310 tests pass, zero old syntax patterns remaining
