跳转至

ADR-009:RVF WASM 运行时用于边缘部署

状态

已提议

日期

2026-02-28

背景

当前 WASM 状态

wifi-densepose-wasm crate 提供基本的 WebAssembly 绑定,将 Rust 类型暴露给 JavaScript。它支持基于浏览器的可视化和轻量级推理,但存在显著限制:

  1. 无法自包含运行:WASM 模块依赖通过 fetch() 加载的外部模型文件。如果服务器不可达,该模块将毫无用处。

  2. 无持久状态:浏览器 WASM 没有为指纹数据库、模型权重或会话数据提供内置持久存储。

  3. 无离线能力:在没有网络访问的情况下,WASM 模块无法加载模型或发送结果。

  4. 二进制大小:当前 WASM 包未优化。完整推理 + 信号处理编译后约为 ~5-15 MB。

边缘部署需求

场景 平台 约束
浏览器仪表盘 Chrome/Firefox 下载量 <10 MB,无插件
IoT 传感器节点 ESP32/Raspberry Pi 256 KB - 4 GB RAM,电池供电
移动应用 iOS/Android WebView 后台执行受限
无人机载荷 Embedded Linux + WASM 重量/功耗受限,连接不稳定
现场平板 Android 平板 灾区离线运行

RuVector 的边缘运行时

RuVector 提供一个 5.5 KB 的 WASM 运行时,启动时间为 125ms,具备: - 自包含运行(模型 + 数据嵌入在 RVF 容器中) - 通过 RVF 容器实现持久存储(在浏览器中写入 IndexedDB,在原生环境中写入文件系统) - 离线优先架构 - 在可用时提供 SIMD 加速(WASM SIMD 提案)

决策

我们将用基于 RVF 的边缘运行时替换当前的 wifi-densepose-wasm 方案,该运行时将模型、指纹数据库和推理引擎打包为单个可部署的 RVF 容器。

边缘运行时架构

┌──────────────────────────────────────────────────────────────────┐
│                RVF Edge Deployment Container                      │
│                    (.rvf.edge file)                                │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐    │
│  │  WASM    │ │  VEC     │ │  INDEX   │ │  MODEL (ONNX)    │    │
│  │  Runtime │ │  CSI     │ │  HNSW    │ │  + LoRA deltas   │    │
│  │  (5.5KB) │ │  Finger- │ │  Graph   │ │                  │    │
│  │          │ │  prints  │ │          │ │                  │    │
│  └──────────┘ └──────────┘ └──────────┘ └──────────────────┘    │
│                                                                   │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐    │
│  │  CRYPTO  │ │  WITNESS │ │  COW_MAP │ │  CONFIG          │    │
│  │  Keys    │ │  Audit   │ │  Branches│ │  Runtime params  │    │
│  │          │ │  Chain   │ │          │ │                  │    │
│  └──────────┘ └──────────┘ └──────────┘ └──────────────────┘    │
│                                                                   │
│  Total container: 1-50 MB depending on model + fingerprint size  │
└──────────────────────────────────────────────────────────────────┘
        │
        │ Deploy to:
        ▼
┌───────────────────────────────────────────────────────────────┐
│                                                                │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────────────┐ │
│  │ Browser │  │   IoT   │  │ Mobile  │  │ Disaster Field  │ │
│  │         │  │ Device  │  │  App    │  │    Tablet       │ │
│  │ IndexedDB  │ Flash   │  │ App     │  │ Local FS        │ │
│  │ for state│  │ for     │  │ Sandbox │  │ for state       │ │
│  │         │  │ state   │  │ for     │  │                 │ │
│  │         │  │         │  │ state   │  │                 │ │
│  └─────────┘  └─────────┘  └─────────┘  └─────────────────┘ │
└───────────────────────────────────────────────────────────────┘

分层运行时配置

不同的部署目标使用不同的容器配置:

/// Edge runtime profiles
pub enum EdgeProfile {
    /// Full-featured browser deployment
    /// ~10 MB container, full inference + HNSW + SONA
    Browser {
        model_quantization: Quantization::Int8,
        max_fingerprints: 100_000,
        enable_sona: true,
        storage_backend: StorageBackend::IndexedDB,
    },

    /// Minimal IoT deployment
    /// ~1 MB container, lightweight inference only
    IoT {
        model_quantization: Quantization::Int4,
        max_fingerprints: 1_000,
        enable_sona: false,
        storage_backend: StorageBackend::Flash,
    },

    /// Mobile app deployment
    /// ~5 MB container, inference + HNSW, limited SONA
    Mobile {
        model_quantization: Quantization::Int8,
        max_fingerprints: 50_000,
        enable_sona: true,
        storage_backend: StorageBackend::AppSandbox,
    },

    /// Disaster field deployment (maximum capability)
    /// ~50 MB container, full stack including multi-AP consensus
    Field {
        model_quantization: Quantization::Float16,
        max_fingerprints: 1_000_000,
        enable_sona: true,
        storage_backend: StorageBackend::FileSystem,
    },
}

容器大小预算

组成部分 浏览器 IoT 移动 现场
WASM 运行时 5.5 KB 5.5 KB 5.5 KB 5.5 KB
模型(ONNX) 3 MB(int8) 0.5 MB(int4) 3 MB(int8) 12 MB(fp16)
HNSW 索引 4 MB 100 KB 2 MB 40 MB
指纹向量 2 MB 50 KB 1 MB 10 MB
配置 + 加密 50 KB 10 KB 50 KB 100 KB
总计 ~10 MB ~0.7 MB ~6 MB ~62 MB

离线优先数据流

┌────────────────────────────────────────────────────────────────────┐
│                    Offline-First Operation                          │
├────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  1. BOOT (125ms)                                                   │
│     ├── Open RVF container from local storage                      │
│     ├── Memory-map WASM runtime segment                            │
│     ├── Load HNSW index into memory                                │
│     └── Initialize inference engine with embedded model            │
│                                                                     │
│  2. OPERATE (continuous)                                           │
│     ├── Receive CSI data from local hardware interface             │
│     ├── Process through local pipeline (no network needed)         │
│     ├── Search HNSW index against local fingerprints              │
│     ├── Run SONA adaptation on local data                          │
│     ├── Append results to local witness chain                      │
│     └── Store updated vectors to local container                   │
│                                                                     │
│  3. SYNC (when connected)                                          │
│     ├── Push new vectors to central RVF container                  │
│     ├── Pull updated fingerprints from other nodes                 │
│     ├── Merge SONA deltas via Raft (ADR-008)                      │
│     ├── Extend witness chain with cross-node attestation           │
│     └── Update local container with merged state                   │
│                                                                     │
│  4. SLEEP (battery conservation)                                   │
│     ├── Flush pending writes to container                          │
│     ├── Close memory-mapped segments                               │
│     └── Resume from step 1 on wake                                │
└────────────────────────────────────────────────────────────────────┘

浏览器特定集成

/// Browser WASM entry point
#[wasm_bindgen]
pub struct WifiDensePoseEdge {
    container: RvfContainer,
    inference_engine: InferenceEngine,
    hnsw_index: HnswIndex,
    sona: Option<SonaAdapter>,
}

#[wasm_bindgen]
impl WifiDensePoseEdge {
    /// Initialize from an RVF container loaded via fetch or IndexedDB
    #[wasm_bindgen(constructor)]
    pub async fn new(container_bytes: &[u8]) -> Result<WifiDensePoseEdge, JsValue> {
        let container = RvfContainer::from_bytes(container_bytes)?;
        let engine = InferenceEngine::from_container(&container)?;
        let index = HnswIndex::from_container(&container)?;
        let sona = SonaAdapter::from_container(&container).ok();

        Ok(Self { container, inference_engine: engine, hnsw_index: index, sona })
    }

    /// Process a single CSI frame (called from JavaScript)
    #[wasm_bindgen]
    pub fn process_frame(&mut self, csi_json: &str) -> Result<String, JsValue> {
        let csi_data: CsiData = serde_json::from_str(csi_json)
            .map_err(|e| JsValue::from_str(&e.to_string()))?;

        let features = self.extract_features(&csi_data)?;
        let detection = self.detect(&features)?;
        let pose = if detection.human_detected {
            Some(self.estimate_pose(&features)?)
        } else {
            None
        };

        serde_json::to_string(&PoseResult { detection, pose })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// Save current state to IndexedDB
    #[wasm_bindgen]
    pub async fn persist(&self) -> Result<(), JsValue> {
        let bytes = self.container.serialize()?;
        // Write to IndexedDB via web-sys
        save_to_indexeddb("wifi-densepose-state", &bytes).await
    }
}

模型量化策略

量化 体积缩减 精度损失 适用场景
Float32(基线) 1x 0% 服务器/桌面端
Float16 2x <0.5% 现场平板、GPU
Int8(PTQ) 4x <2% 浏览器、移动端
Int4(GPTQ) 8x <5% IoT、超受限设备
Binary(1-bit) 32x ~15% MCU/超边缘(实验性)

影响

积极影响

  • 单文件部署:复制一个 .rvf.edge 文件即可部署到任意位置
  • 离线运行:无需网络连接即可具备完整功能
  • 125ms 启动:紧急场景下近乎即时就绪
  • 平台通用:浏览器、IoT、移动端和服务器使用相同容器格式
  • 省电:离线模式下不进行网络轮询

消极影响

  • 容器大小:即使压缩后,现场容器仍超过 50 MB
  • WASM 性能:对于计算密集型操作,比原生 Rust 慢 2-5 倍
  • 浏览器限制:IndexedDB 存在存储配额;WASM SIMD 支持情况不一
  • 更新延迟:离线设备在重新连接前无法获取更新
  • 量化精度:Int4/Int8 模型会损失部分检测灵敏度

参考资料

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 wi/RuView