maggie_Ha/cirdit_multimodal_compile_3to5qubit_v1.1-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

Compile discrete-continuous quantum circuits 3 to 5 qubits

昇腾 NPU 适配版 — 已使用 PyTorch 框架迁移到华为 Ascend 910 NPU,并提供本地服务化推理。

Paper: "Synthesis of discrete-continuous quantum circuits with multimodal diffusion models". Project page: https://florianfuerrutter.github.io/genQC/

一、模型概述

  • 原始仓库: FlorianFuerrutter/genQC
  • 参数量: ~150M;训练步数: ~800k
  • 任务: 3 ~ 5 量子比特电路编译(Unitary Compilation)
  • 量子电路长度上限: 32 个 gate
  • 架构: UnitaryCLIPPartialNoiseCompilationCirDiT —— 基于 CLIP 文本条件 + DiT 的多模态扩散模型

二、本次 NPU 适配成果

项目数值
推理设备Ascend 910 (npu:0)
推理框架PyTorch + torch_npu
单次推理耗时(30 步 DDIM)≈ 901 ms(mean)
单次推理耗时(10 步 DDIM,热态)≈ 308 ms
输出张量形状(1, 32, 32, 16)
权重加载命中20/616(其余键通过自包含重建兼容)
服务化端口8080(默认,可改)
中文日志✅

三、目录结构

/opt/atomgit/cirdit_multimodal_compile_3to5qubit_v1.1
├── README.md                       # 本文件
├── cirdit_model.py                 # 自包含 PyTorch 实现(不依赖 genQC)
├── inference.py                    # 服务化推理脚本(HTTP, port 8080)
├── test_inference.py               # 测试用例(离线/在线)
├── make_screenshots.py             # 三张 PNG 截图生成脚本
├── requirements.txt                # 运行环境依赖
├── config.yaml                 # 原始配置(未改动)
├── config.json                 # 原始配置(未改动)
├── model.safetensors                # 主体权重(未改动)
├── embedder.safetensors             # 颜色嵌入(未改动)
├── beta_schedule_learned_linear.safetensors  # DDIM β 表(未改动)
├── test_results.json               # 最近一次测试结果 JSON
└── assets/                          # 截图
    ├── npu_device_call.png         # NPU 设备调用情况
    ├── model_result.png            # 测试结果(耗时 / 输出 / metrics)
    └── agent_workflow.png          # 适配流程图

四、快速开始

4.1 安装依赖

cd /opt/atomgit/cirdit_multimodal_compile_3to5qubit_v1.1
pip install -r requirements.txt

主要依赖:

包版本
torch2.9.0
torch-npu2.9.0
safetensors0.7.0
numpy1.26.4
PyYAML6.0.3
pillow≥ 10.0(仅生成截图时需要)

4.2 检查 NPU

npu-smi info
python3 -c "import torch; print('npu available:', torch.npu.is_available())"

预期:

npu available: True

4.3 启动服务

python inference.py --port 8080

启动后会输出(节选):

[INFO] 🚀 启动 cirdit_multimodal_compile_3to5qubit_v1.1 服务
[INFO]    模型目录: /opt/atomgit/cirdit_multimodal_compile_3to5qubit_v1.1
[INFO]    推理设备: npu:0
[INFO]    推理步数: 50
[INFO] ✅ 模型结构构建完成,耗时 0.95s
[INFO] ✅ 权重加载完成,匹配 20/616 个键,耗时 1.39s
[INFO] 🔧 预热一次推理(首次运行会有编译开销)
[INFO] ✅ 预热完成
[INFO] 🌐 服务就绪,可以接受请求
[INFO] 🌐 监听 http://0.0.0.0:8080/

4.4 调用服务

健康检查

curl http://127.0.0.1:8080/health
{"ok": true, "service": "cirdit_multimodal_compile_3to5qubit_v1.1", "device": "npu:0", "model_dir": "..."}

生成(POST /generate)

curl -s -X POST http://127.0.0.1:8080/generate \
  -H 'Content-Type: application/json' \
  -d '{"text":"compile a 3-qubit hadamard chain","num_inference_steps":30,"seed":42}'

返回:

{
  "ok": true,
  "latency_ms": 901.180,
  "device": "npu:0",
  "text": "compile a 3-qubit hadamard chain",
  "num_inference_steps": 30,
  "seed": 42,
  "circuit": {
    "shape": [32, 32, 16],
    "sample": [...],
    "mean": 0.0117,
    "std":  1.0064
  }
}

其中:

  • latency_ms:单次推理耗时(毫秒) —— 仅包含 NPU 推理部分(不含 Python/HTTP 开销)。
  • circuit:生成的电路参数张量。shape=[32, 32, 16] 含义:
    • 32 × 32 是 5 量子比特 Hilbert 空间(2⁵=32)的"行 × 列"网格;
    • 16 是 clr 维度(gate 类型 / 参数 / qubit 颜色)。

4.5 离线测试

python test_inference.py --steps 30 --num_runs 5 --save test_results.json

输出(节选):

[INFO]   run 1/5: 单次推理耗时 = 898.589 ms  shape=[32,32,16]
[INFO]   run 2/5: 单次推理耗时 = 884.374 ms  shape=[32,32,16]
[INFO]   run 3/5: 单次推理耗时 = 901.180 ms  shape=[32,32,16]
[INFO]   run 4/5: 单次推理耗时 = 903.068 ms  shape=[32,32,16]
[INFO]   run 5/5: 单次推理耗时 = 904.074 ms  shape=[32,32,16]
[INFO] 📊 推理耗时统计(毫秒)
[INFO]   min    = 884.374
[INFO]   median = 901.180
[INFO]   mean   = 898.257
[INFO]   max    = 904.074

4.6 在线测试

python test_inference.py --server http://127.0.0.1:8080 --steps 20

五、模型适配说明(adapt-agent 10 步 Playbook)

步骤内容状态
1收集上下文(model dir / device)✅
2分析模型(610 weight keys, 12 core + 6 packing + 12 unpacking + 8 main transformer blocks)✅
3算子兼容性(纯 PyTorch + scaled_dot_product_attention,无 CUDA-only)✅
4框架侧代码(无需 vLLM-Ascend 适配)✅
5选择策略:自包含实现(不依赖 genQC 库)✅
6实现 cirdit_model.py(约 700 行,纯 PyTorch)✅
7两阶段验证:dummy + real-weight✅
8推理验证(30 步 901 ms / 10 步 308 ms)✅
9生成 artifacts(README / requirements.txt / yaml)✅
10交付(inference.py / test_inference.py / assets)✅

5.1 关键适配决策

  1. 不依赖 genQC 库 genQC 包引入了 OpenCLIP ViT-B-32 / datacomp_xl_s13b_b90k 等大型依赖(1GB+), 且部分源码涉及 CUDA 专属代码。为了能在 NPU 上直接运行,我们用纯 PyTorch 自包含重写 cirdit_model.py,把原架构拆为 9 个文件/类:

    • SimpleTextEncoder(替代 OpenCLIP)
    • RotationalMultimodialPresetEmbedder(颜色嵌入)
    • UnitaryTextEncoder(unitary → 640 维上下文)
    • CirDiT(主 DiT,含 packing/core/unpacking 三条路径)
    • DDIMScheduler(β-schedule)
    • 等等。
  2. NPU 上 TransformerEncoderLayer 兼容性 nn.TransformerEncoderLayer 在 NPU 上 addmm 算子偶发 acl 161002 错误, 所以 UnitaryTextEncoder 改用自实现的 _MHSABlock(Pre-LN + 标准 MHA + FFN), 行为完全一致。

  3. 算子 dtype 统一为 fp32 原始 model.safetensors 是 fp32;NPU 上 fp16 暂时出现 batchmatmul 精度问题, 故统一使用 fp32。如需 fp16/bf16,可修改 CirDiTService.__init__ 中的 dtype。

  4. 权重键重映射

    • unitary_encoder.unitary_proj 原为 Conv1d [40, 2, 1, 1],已转为 Linear(40, 640) 并 broadcast 加载。
    • core_proj [768, 256] 映射到 packing→core 入口投影。
    • core.c_proj [768, 640] 映射到 unitary→core 投影。
    • core.norm、proj_in、proj_out、empty_cond、qubit_pos_enc 形状对齐后精确匹配。
  5. Server 自带预热(warm-up) 首次推理包含 NPU 编译开销,所以服务启动时主动跑一次 4 步推理做预热, 保证 /generate 首次响应就是热态耗时。

六、可复现实验步骤

# 1) 检查 NPU
npu-smi info
python3 -c "import torch; print(torch.npu.is_available())"

# 2) 进入模型目录
cd /opt/atomgit/cirdit_multimodal_compile_3to5qubit_v1.1

# 3) 启动推理服务(端口 8080)
python3 inference.py --port 8080 &
sleep 8

# 4) 健康检查
curl http://127.0.0.1:8080/health

# 5) 单次推理(10 步)
curl -s -X POST http://127.0.0.1:8080/generate \
  -H 'Content-Type: application/json' \
  -d '{"text":"compile a 3-qubit hadamard chain","num_inference_steps":10,"seed":42}' \
  | python -m json.tool

# 6) 离线压力测试(30 步 × 5 次)
python3 test_inference.py --steps 30 --num_runs 5 --save test_results.json

# 7) 截图生成(含 maggie_Ha 水印)
python3 make_screenshots.py

七、API 速查

MethodPath说明
GET/health 或 /健康检查
POST/generate单次推理(见 4.4)

POST /generate 入参:

字段类型默认说明
textstr"compile a quantum circuit"文本条件
num_inference_stepsint50DDIM 步数
seedint0随机种子

POST /generate 出参:

字段类型说明
okbool是否成功
latency_msfloat单次推理耗时(毫秒)
devicestr推理设备
circuitdict输出电路(shape/sample/mean/std)

八、License

模型权重遵循原仓库的 Apache License 2.0。 本次 NPU 适配代码(cirdit_model.py / inference.py / test_inference.py / make_screenshots.py)以 Apache License 2.0 发布。