2
gcw_BOxvkDDf/compressionkit-ppg-4x
模型介绍
文件和版本
Pull Requests
讨论
分析

compressionkit-ppg-4x — 昇腾 NPU 适配 (Ascend NPU)

Ambiq/compressionkit-ppg-4x-v1.0 — PPG(光电容积脉搏波)信号的 4x 神经压缩编解码器 (Residual Vector Quantization / RVQ 自编码器),适配华为昇腾 NPU(torch_npu)。

  • 任务:输入 1-D PPG 波形 → 编码器压缩为 80×16 隐表示 → 4 级 RVQ 量化(4×256×16 码本,每索引 8 bit) → 解码器重建波形。标称压缩比 4x。
  • 原始权重:https://huggingface.co/Ambiq/compressionkit-ppg-4x-v1.0 (仓库以 Keras .keras / TFLite .tflite / C 头文件 + codebook.npz 形式发布,无 torch state dict)
  • 工程根目录:本目录

架构重建过程

原始仓库不包含 PyTorch 代码。适配时通过以下步骤重建:

  1. 用 tflite flatbuffer 解析 encoder_float32.tflite / decoder_float32.tflite 得到算子图;
  2. 用 h5py 读取 Keras encoder.keras / decoder.keras 的权重(权威来源), 按 Keras [kh,kw,in,out] 布局转置为 torch Conv1d [out,in,k];
  3. 编码器 BatchNormalization 以 eps=1e-5 折叠进卷积(与 TFLite 完全一致);
  4. 关键细节:
    • 编码器 stride-2 卷积使用 非对称 SAME padding(左 2 / 右 3),torch F.pad 实现;
    • Keras SeparableConv2D 的 bias 作用于 pointwise 卷积之后(depthwise bias = 0);
    • 解码器按 Keras UpSampling2D(nearest)语义用 repeat_interleave(2) 上采样;
    • 解码器尾部 LayerNorm 作用于通道维(axis=-1),eps=1e-5。
  5. 用 codebook.npz 的 4 级码本实现标准 residual 最近邻量化(F.embedding)。
  6. 用仓库自带 sample_stimulus.npz 的 inputs/reconstructions 对重建结果做了端到端校验: torch 重建与官方参考重建 MAE ≈ 0.005(近一致)。

模型结构

Encoder  : 320 点帧 (64 Hz) ──► Conv1d(1→48,k7,s2)+ReLU ──► Conv1d(48→64,k7,s2)+ReLU ──► Conv1d(64→16,k1)
                                                                                                │  [1,16,80]
RVQ      : 4 级 × 256×16 码本(残差最近邻量化) ──► 每时间步 4 个 8-bit 索引(共 320 索引)
                                                                                                │  [1,16,80]
Decoder  : repeat×2 ──► Conv1d(16→64,k7)+ReLU ──► DW(5) ──► Conv1d(64→64,1)+ReLU
        ──► repeat×2 ──► Conv1d(64→48,k7)+ReLU ──► DW(5) ──► Conv1d(48→48,1)+ReLU
        ──► LayerNorm(通道) ──► Conv1d(48→1,1) ──► 320 点重建帧

输入预处理:逐帧 LayerNorm(raw = norm·√(var+eps)+mean,eps=1e-3,见 codec_spec.json)。

使用

# 下载权重(缓存到 ./model_weights/Ambiq/compressionkit-ppg-4x-v1.0/)
python3 /opt/atomgit/adapt/_shared/download_weights.py Ambiq/compressionkit-ppg-4x-v1.0

# 1) CLI 单次推理(--img 为 --input 别名)
ASCEND_RT_VISIBLE_DEVICES=1 python3 inference.py --input sample_ppg.npy --num_workers 0

# 2) FastAPI 服务(端口 8001)
ASCEND_RT_VISIBLE_DEVICES=1 python3 inference.py --serve --port 8001
#   GET  /          → HTML 上传页(.npy/.csv/.txt 或 JSON 数组)
#   POST /predict   → 返回推理 JSON

输出指标(示例)

在样本 sample_ppg.npy(320 点 ≈ 5 s @ 64 Hz)上:

指标值
devicenpu:0
压缩比4.0x(320 索引 × 8 bit,对照输入 320×32 bit)
MSE≈ 1.09e-4
PSNR≈ 39.2 dB
相关系数≈ 0.998

工程 .py 全部运行于 npu:0,grep -rin cuda 无残留;NPU 不可用时回退 CPU。

许可

模型权重遵循 Ambiq Model Weights License(部署限于 Ambiq 硅器件);示例信号为合成波形。