Skip to content

Latest commit

 

History

History
281 lines (226 loc) · 8.84 KB

File metadata and controls

281 lines (226 loc) · 8.84 KB

PLAN.md — TRCE 计算库实现方案

项目定位

以 CPU 热力学硬件为计算主体、软件层仅做硬件控制 + 极轻量 Readout 的 AI 推理中间件。 不引入传统 ML 计算库。90% 代码是硬件控制,1% 是"计算"。


1. 核心理念

传统 ML 库:  软件算一切
TRCE 方案:  热力学硬件算一切,软件只做胶水 + Readout

软件层本质不是"计算库",而是热力学计算引擎的控制接口


2. 硬件拓扑(不可偏离)

组件 路径 维度 角色
热区 ×4 /sys/class/thermal/thermal_zone{0..3} 4-dim 储层状态向量
风扇 ×5 /sys/class/thermal/cooling_device{2..6} 5-dim 耗散执行器
硅晶热惯性 物理固有 时间记忆(遗忘门)

编号不固定,启动时运行时探测。


3. 计算边界

硬件层(热力学直接完成)

物理过程 触发方式 等效 ML 运算
CPU 死循环脉冲 inject_heat_pulse() 非线性特征投影
热传导扩散 自然发生 高维空间激活变换
热惯性衰减 自然发生 RNN/LSTM 隐藏状态
风扇耗散控制 set_fans() 遗忘门

软件层(仅 5 个函数)

运算 函数 复杂度
温度差分 gradient(prev, curr) O(1)
基线扣除 subtract_baseline(temp, baseline) O(1)
线性 Readout classify(state, weights) O(n)
OLS 回归 fit_readout(X, y) O(n³) 离线
移动平均 exp_moving_avg(data, α) O(n) 离线

4. 项目结构

TRCE/
├── AGENTS.md
├── PLAN.md
├── .gitignore
├── Cargo.toml
├── pyproject.toml
├── crates/
│   ├── trce-core/
│   │   ├── Cargo.toml
│   │   └── src/
│   │       ├── lib.rs
│   │       ├── engine.rs
│   │       ├── hardware/
│   │       │   ├── mod.rs
│   │       │   ├── thermal_zone.rs
│   │       │   ├── cooling_device.rs
│   │       │   ├── cpu_affinity.rs
│   │       │   ├── governor.rs
│   │       │   └── thermald.rs
│   │       ├── inference/
│   │       │   ├── mod.rs
│   │       │   ├── pulse.rs
│   │       │   ├── readout.rs
│   │       │   └── stream.rs
│   │       ├── training/
│   │       │   ├── mod.rs
│   │       │   ├── fingerprint.rs
│   │       │   └── fit.rs
│   │       ├── telemetry/
│   │       │   ├── mod.rs
│   │       │   ├── metrics.rs
│   │       │   └── watchdog.rs
│   │       └── serialization/
│   │           ├── mod.rs
│   │           └── weights.rs
│   └── trce-py/
│       ├── Cargo.toml
│       └── src/
│           └── lib.rs
├── python/
│   └── trce/
│       ├── __init__.py
│       ├── engine.py
│       ├── training.py
│       └── daemon.py
├── deploy/
│   └── trce.service
└── examples/
    └── basic_inference.py

5. Typestate 生命周期

Uninitialized ──init_hardware_harness()──▶ Calibrated
                                                │
                                        load_weights()
                                                │
                                                ▼
                                           Running ──release()──▶ Released

每个状态是零大小类型(ZST),状态转换消费 self 返回新类型。 未初始化就调推理 → 编译错误,非运行时 panic。


6. 4 类 API

6.1 生命周期与硬件霸权

方法 签名 说明
new() → ThermodynamicEngine<Uninitialized> 构造
init_hardware_harness() → Result<Calibrated> 锁 CPU 亲和性、锁 performance governor、停 thermald
calibrate_baseline(secs) → Result<Calibrated> 高频采样空载温度,算物理基准线
load_weights(path) → Result<Running> 加载 72 字节原生格式权重
release_hardware_harness() → Result<()> 恢复亲和性、风扇归零、重启 thermald

6.2 流式推理

方法 签名 说明
inject_and_predict(features) → Result<InferenceResult> 同步单次推理
create_inference_stream(cap) → (Sender, Receiver) tokio bounded MPSC 流式推理

6.3 训练拟合

方法 签名 说明
collect_fingerprints(engine, data, labels) → DesignMatrix 物理指纹采集
fit_readout(matrix, labels, method) → ReadoutWeights OLS / Ridge 回归

6.4 风控遥测

方法 签名 说明
get_telemetry_metrics() → EngineMetrics 温度、风扇、记忆残留率、延迟
start_watchdog(config) → WatchdogHandle 独立 OS 线程,超温熔断

7. 关键设计决策

决策 选择 原因
硬件探测 运行时扫描 sysfs type 字段 不同硬件编号不同
权重格式 原生字节 [u8; 72] 零依赖、纳秒级加载
Watchdog 独立 OS 线程 tokio 卡死时仍能熔断
生命周期 Typestate 模式 编译期强制阶段顺序
异步 I/O tokio + spawn_blocking sysfs 是阻塞 I/O
矩阵运算 无(8 维点积手写) 不引入 nalgebra/ndarray
sysfs 写入 O_SYNC + sync_all() 内核要求首次写入完整值
调用风格 嵌入式 HAL 风格 不像数学库,像硬件控制

8. 依赖清单

[dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "sync", "time", "macros"] }
pyo3 = { version = "0.25", features = ["extension-module"] }
core_affinity = "0.8.3"
anyhow = "1"
thiserror = "2"
tracing = "0.1"
tracing-subscriber = "0.3"

[dependencies.linfa-linear]
version = "0.8"
optional = true

[features]
training = ["linfa-linear"]

9. 实现阶段

阶段 内容 产出
P0 项目骨架 Cargo workspace + pyproject.toml + .gitignore
P1 硬件探测层 thermal_zone.rs + cooling_device.rs
P2 系统控制层 cpu_affinity.rs + governor.rs + thermald.rs
P3 Typestate 引擎主体 engine.rs + 状态转换
P4 发热脉冲 PWM pulse.rs
P5 Readout 分类器 readout.rs
P6 流式推理管线 stream.rs
P7 遥测 + Watchdog metrics.rs + watchdog.rs
P8 训练拟合 fingerprint.rs + fit.rs
P9 序列化 weights.rs
P10 PyO3 绑定 trce-py/src/lib.rs
P11 Python 封装 + 测试 engine.py + pytest

10. sysfs I/O 关键实现

// 读温度(毫度 → 摄氏度)
fn read_temp(zone_path: &Path) -> Result<f64> {
    let mut file = File::open(zone_path.join("temp"))?;
    let mut buf = [0u8; 16];
    let n = file.read(&mut buf)?;
    let raw = std::str::from_utf8(&buf[..n])?.trim();
    Ok(raw.parse::<f64>()? / 1000.0)
}

// 写风扇状态(O_SYNC 强制同步)
fn set_fan(device_path: &Path, state: u32) -> Result<()> {
    let mut file = File::options()
        .write(true)
        .custom_flags(libc::O_SYNC)
        .open(device_path.join("cur_state"))?;
    write!(file, "{}", state)?;
    file.sync_all()?;
    Ok(())
}

// 探测热区(按 type 字段筛选 CPU 相关的)
fn probe_thermal_zones() -> Vec<ThermalZone> {
    let mut zones = Vec::new();
    for i in 0..20 {
        let path = PathBuf::from(format!("/sys/class/thermal/thermal_zone{}", i));
        if !path.exists() { continue; }
        let type_name = fs::read_to_string(path.join("type")).unwrap_or_default();
        if type_name.trim().to_lowercase().contains("cpu") {
            zones.push(ThermalZone { id: i, path, type_name: type_name.trim().to_string() });
        }
    }
    zones
}

11. 风险登记

风险 等级 缓解措施
硬件热插拔 探测 HashMap + I/O 错误时重新探测
Governor 路径差异 先读 available_governors,fallback intel_pstate
无硬件无法测试 需要真实硬件环境
tokio runtime 卡死 sysfs 全部 spawn_blocking + 独立线程 watchdog
PyO3 GIL 竞争 py.allow_threads() 释放 GIL
温度读取延迟抖动 CLOCK_MONOTONIC 时间戳 + 紧凑循环

12. 调用风格总结

维度 风格
整体感觉 嵌入式 HAL,不是数学库
状态管理 Typestate(编译期)
错误处理 Result<T, TrceError>
异步模型 tokio + spawn_blocking
Python 封装 PyO3 1:1 映射
命名风格 驱动风格:init_harness, inject_pulse, read_zone