Bbaishanyanginit project
5f1c8c3b创建于 4 天前历史提交

OHOS Model Claw

Version Python Platform

HarmonyOS 模型转换工具集 - 提供 ONNX 到 MindSpore Lite (.ms) 格式转换、性能基准测试、代码生成和算子修复功能。通过 MCP (Model Context Protocol) 为 AI Agent 提供标准化工具接口。

目录

核心功能

功能 描述 使用场景
模型转换 ONNX → MindSpore Lite (.ms) 格式 HarmonyOS 设备部署
模型量化 支持 INT8 量化 减小模型体积、提升推理速度
FP16 优化 Float32 → Float16 优化 减小模型体积、加速推理
性能测试 CPU/GPU/NPU 推理性能基准测试 模型优化、设备性能评估
代码生成 生成 HarmonyOS 项目集成代码 快速集成到应用
算子修复 自动修复 MindSpore Lite 不兼容算子 解决转换失败问题
模型信息查询 检查 ONNX 模型输入输出、动态 shape 转换前检测
错误分析 运行时错误诊断和修复建议 推理失败排查

系统要求

  • 操作系统: Windows x64
  • Python: 3.8+ (需要 os.add_dll_directory() 支持)
  • 运行库: Visual C++ Redistributable
  • 磁盘空间: ~200MB (工具下载)

快速开始

1. 安装依赖

pip install -r ohos_model_claw/requirements.txt

2. 转换模型

# 基础转换
python -m ohos_model_claw.ohos_model_claw convert model.onnx --output_dir output

# INT8 量化转换
python -m ohos_model_claw.ohos_model_claw convert model.onnx --output_dir output --quant

3. 性能测试

python -m ohos_model_claw.ohos_model_claw benchmark model.ms --device CPU --threads 4

安装

依赖安装

pip install -r ohos_model_claw/requirements.txt

依赖列表:

requests>=2.28.0        # HTTP 下载工具包
mcp>=1.0.0              # MCP 协议实现
onnx>=1.14.0            # ONNX 模型操作
onnx_graphsurgeon>=0.3.0 # ONNX 图修改工具

工具自动安装

首次使用时,工具会自动从华为云镜像下载 MindSpore Lite Tools (~200MB) 到用户目录 ~/.ohos_model_claw/tools/

手动检查工具状态:

python -m ohos_model_claw.ohos_model_claw status

使用方式

MCP Server (推荐)

MCP Server 为 AI Agent 提供标准化工具接口,支持异步任务执行。

配置 opencode.json:

{
  "mcp": {
    "ohos_model_claw": {
      "type": "local",
      "command": ["python", "-m", "ohos_model_claw.mcp_server"],
      "enabled": true,
      "timeout": 60000
    }
  }
}

优势:

  • AI Agent 可直接调用工具
  • 支持异步任务执行
  • 自动错误分析和修复建议
  • 无需手动处理工具下载和配置

命令行工具 (CLI)

1. 模型转换

# 基础转换
python -m ohos_model_claw.ohos_model_claw convert model.onnx --output_dir output

# INT8 量化转换
python -m ohos_model_claw.ohos_model_claw convert model.onnx --output_dir output --quant

# FP16 优化转换
python -m ohos_model_claw.ohos_model_claw convert model.onnx --output_dir output --fp16 on

# 数据格式转换 (NHWC → NCHW)
python -m ohos_model_claw.ohos_model_claw convert model.onnx --output_dir output --inputDataFormat NCHW --outputDataFormat NCHW

# 动态 shape 固化
python -m ohos_model_claw.ohos_model_claw convert model.onnx --output_dir output --inputShape "input:1,3,224,224"

# GPU 优化
python -m ohos_model_claw.ohos_model_claw convert model.onnx --output_dir output --optimize gpu_oriented

# 组合使用所有参数
python -m ohos_model_claw.ohos_model_claw convert model.onnx --output_dir output --fp16 on --inputDataFormat NCHW --outputDataFormat NCHW --inputShape "input:1,3,224,224" --optimize general

参数说明:

参数 说明 默认值
--output_dir 输出目录 output
--quant 启用 INT8 量化 False
--fp16 on/off,Float16 优化 off
--inputDataFormat NHWC/NCHW 输入格式 -
--outputDataFormat NHWC/NCHW 输出格式 -
--inputShape 动态 shape 固化,格式: input:1,3,224,224 -
--optimize none/general/gpu_oriented/ascend_oriented general

2. 性能测试

# CPU 测试 (4线程)
python -m ohos_model_claw.ohos_model_claw benchmark model.ms --device CPU --threads 4

# GPU 测试
python -m ohos_model_claw.ohos_model_claw benchmark model.ms --device GPU

# NPU 测试
python -m ohos_model_claw.ohos_model_claw benchmark model.ms --device NPU

# 自定义迭代次数
python -m ohos_model_claw.ohos_model_claw benchmark model.ms --device CPU --loop_count 200

参数说明:

  • --device: 测试设备 (CPU, GPU, NPU)
  • --threads: CPU 线程数 (默认: 4)
  • --loop_count: 迭代次数 (默认: 100)

3. 代码生成

# 生成 HarmonyOS 项目代码
python -m ohos_model_claw.ohos_model_claw codegen model.ms --project_dir ./harmonyos_project --module entry

参数说明:

  • --project_dir: 项目输出目录
  • --module: HarmonyOS 模块名 (默认: entry)

4. 算子修复

# 自动检测并修复
python -m ohos_model_claw.ohos_model_claw op_fix model.onnx

# 指定算子类型
python -m ohos_model_claw.ohos_model_claw op_fix model.onnx --operators HardSigmoid HardSwish

# 指定输出文件
python -m ohos_model_claw.ohos_model_claw op_fix model.onnx --output_path model_fixed.onnx

参数说明:

  • --operators: 要替换的算子列表 (可选,默认自动检测)
  • --output_path: 输出文件路径 (可选)

5. 模型信息查询

# 查询模型信息
python -m ohos_model_claw.ohos_model_claw info model.onnx

# 输出示例:
# [INPUTS]
#   input: shape=[batch, 3, height, width], dtype=float32
# [OUTPUTS]
#   output: shape=[batch, 1000], dtype=float32
# [WARNING] 模型包含动态维度!
# [SUGGEST] --inputShape="input:1,3,224,224"

使用场景:

  • 转换前检查模型是否有动态 shape
  • 获取模型输入输出信息
  • 查看模型数据类型

6. 运行时错误分析

# 分析错误日志字符串
python -m ohos_model_claw.ohos_model_claw runtime_analyze "Load model failed: unsupported op type HSwish"

# 从文件读取错误日志
python -m ohos_model_claw.ohos_model_claw runtime_analyze error.log

# 指定模型和设备上下文
python -m ohos_model_claw.ohos_model_claw runtime_analyze error.log --ms_path model.ms --device CPU

参数说明:

  • error_log: 错误日志字符串或文件路径
  • --ms_path: 模型文件路径 (可选,用于上下文分析)
  • --device: 设备类型 (可选,CPU/GPU/NPU)

输出示例:

[unsupported_operator]
  Diagnosis: 模型包含不支持的算子
  Confidence: HIGH
  Suggestions:
    1. 使用 op_fix 替换算子
    2. 重新转换模型

MCP 工具详解

工具列表

工具名称 描述 异步支持
ohos_tool_status 检查/安装 MindSpore Lite 工具
ohos_convert ONNX 模型转换(支持 FP16、数据格式转换)
ohos_benchmark 性能基准测试
ohos_codegen 生成 HarmonyOS 集成代码
ohos_op_fix 修复不兼容算子
ohos_model_info 检查模型信息、动态 shape 检测
ohos_runtime_analyze 运行时错误分析
ohos_task_status 查询异步任务状态

工具调用示例

1. 检查工具状态

# 参数
{
    "install": true  # 如果工具未安装,自动下载安装
}

# 返回
{
    "installed": true,
    "converter_path": "C:/Users/.../converter_lite.exe",
    "benchmark_path": "C:/Users/.../benchmark.exe"
}

2. 转换模型

# 参数 (异步模式)
{
    "onnx_path": "model.onnx",
    "output_dir": "output",
    "quant": false,               # INT8 量化
    "fp16": "on",                 # Float16 优化
    "input_data_format": "NCHW",  # 输入数据格式
    "output_data_format": "NCHW", # 输出数据格式
    "input_shape": "input:1,3,224,224",  # 动态 shape 固化
    "optimize": "general",        # 优化类型
    "async_mode": true            # 默认 true
}

# 参数说明
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| fp16 | string | "off" | on/off,Float16 优化减小模型体积 |
| input_data_format | string | - | NHWC/NCHW 输入数据格式转换 |
| output_data_format | string | - | NHWC/NCHW 输出数据格式转换 |
| input_shape | string | - | 动态 shape 固化,格式: `input:1,3,224,224` |
| optimize | string | "general" | none/general/gpu_oriented/ascend_oriented |

# 返回
{
    "task_id": "abc12345",
    "status": "started"
}

# 查询状态
ohos_task_status({"task_id": "abc12345"})

# 返回
{
    "status": "completed",
    "output_file": "output/model.ms",
    "error_analysis": {
        "has_errors": false,
        "operators_detected": []
    }
}

3. 性能测试

# 参数
{
    "ms_path": "model.ms",
    "device": "CPU",      # CPU | GPU | NPU
    "threads": 4,         # CPU 线程数
    "loop_count": 100     # 迭代次数
}

# 返回
{
    "avg_time_ms": 15.23,
    "fps": 65.6,
    "device": "CPU"
}

4. 算子修复

# 参数
{
    "onnx_path": "model.onnx",
    "output_path": "model_fixed.onnx",  # 可选
    "operators": ["HardSigmoid", "HardSwish"]  # 可选
}

# 返回
{
    "status": "completed",
    "output_path": "model_fixed.onnx",
    "operators_replaced": {
        "HardSigmoid": 12,
        "HardSwish": 8
    }
}

5. 模型信息查询

# 参数
{
    "onnx_path": "model.onnx"
}

# 返回
{
    "has_dynamic": true,
    "dynamic_inputs": ["input"],
    "suggested_input_shape": "input:1,3,224,224",
    "input_info": [
        {
            "name": "input",
            "shape": ["batch", 3, 224, 224],
            "dtype": "float32",
            "is_dynamic": true
        }
    ],
    "quant_note": "INT8量化需指定典型输入shape进行校准",
    "fp16_note": "FP16转换不受动态shape影响"
}

6. 运行时错误分析

# 参数
{
    "error_log": "Load model failed: unsupported op type HSwish",
    "ms_path": "model.ms",     # 可选,用于上下文分析
    "device": "CPU"            # 可选
}

# 或从文件读取
{
    "error_log": "error.log",  # 错误日志文件路径
    "ms_path": "model.ms",
    "device": "GPU"
}

# 返回
{
    "has_errors": true,
    "total_matches": 2,
    "matched_errors": [
        {
            "error_type": "unsupported_operator",
            "diagnosis": "模型包含不支持的算子类型",
            "confidence": "HIGH",
            "matched_patterns": ["HSwish"],
            "suggestions": [
                "使用 op_fix 替换 HardSwish 算子",
                "重新转换模型"
            ]
        },
        {
            "error_type": "model_load_failed",
            "diagnosis": "模型文件加载失败",
            "confidence": "MEDIUM",
            "suggestions": [
                "检查模型文件路径是否正确",
                "验证模型格式是否有效"
            ]
        }
    ]
}

算子修复支持

支持的算子

算子 数学公式 替换方案 描述
HardSigmoid max(min(x*α+β, 1), 0) Mul → Add → Min → Max 硬化 Sigmoid 激活函数
HardSwish x * clip(x+3, 0, 6) / 6 Add → Clip → Div → Mul MobileNetV3 常用激活
Swish/SiLU x * sigmoid(x) Sigmoid → Mul 自门控激活函数
Mish x * tanh(ln(1+e^x)) Softplus → Tanh → Mul 平滑激活函数

修复流程

模型转换失败
    ↓
错误解析器检测问题算子
    ↓
建议使用 ohos_op_fix
    ↓
替换不兼容算子
    ↓
保存修复后的 ONNX
    ↓
重新转换
    ↓
成功输出 .ms 文件

自动修复示例

# 1. 转换失败
python -m ohos_model_claw.ohos_model_claw convert model.onnx
# 输出: [ERROR] Unsupported operator: HardSwish

# 2. 自动修复
python -m ohos_model_claw.ohos_model_claw op_fix model.onnx
# 输出: Replaced 8 HardSwish operators -> model_fixed.onnx

# 3. 重新转换
python -m ohos_model_claw.ohos_model_claw convert model_fixed.onnx
# 输出: Success! Output: model_fixed.ms

运行时错误分析

功能概述

运行时错误分析工具帮助诊断 MindSpore Lite 推理过程中的常见问题,提供针对性的修复建议。

支持的错误类型

错误类型 典型错误信息 诊断建议
模型加载失败 Load model failed 检查模型文件路径、格式是否正确
算子不支持 Unsupported op type 使用 op_fix 替换算子后重新转换
Shape 推理失败 Shape infer failed 使用 info 检查动态 shape,转换时指定 --inputShape
内存不足 Out of memory 减小 batch size,使用 FP16 或量化优化
设备不支持 Device not supported 确认设备支持 GPU/NPU,切换到 CPU 设备
量化失败 Quantization failed 检查校准数据,确保输入 shape 正确
输入输出不匹配 Input/output mismatch 检查数据格式(NHWC/NCHW),使用正确预处理
DLL 加载失败 DLL load failed 安装 VC++ Redistributable,检查环境变量

使用示例

CLI 使用

# 分析错误日志字符串
python -m ohos_model_claw.ohos_model_claw runtime_analyze "Load model failed: unsupported op type HSwish"

# 从文件读取错误日志
python -m ohos_model_claw.ohos_model_claw runtime_analyze runtime_error.log --ms_path model.ms --device GPU

MCP 使用

# 通过 MCP 调用
{
    "error_log": "Execute failed: shape infer error",
    "ms_path": "model.ms",
    "device": "CPU"
}

# 返回诊断结果
{
    "matched_errors": [
        {
            "error_type": "shape_infer_failed",
            "diagnosis": "输入数据 shape 与模型不匹配",
            "suggestions": [
                "使用 ohos_model_info 检查模型输入 shape",
                "benchmark 时使用 --inputShape 参数",
                "检查数据预处理流程"
            ]
        }
    ]
}

诊断流程

推理失败
    ↓
收集错误日志
    ↓
使用 runtime_analyze 分析
    ↓
识别错误类型
    ↓
┌─────┴─────┬─────────┬──────────┐
│           │         │          │
↓           ↓         ↓          ↓
算子不支持  Shape错误  设备错误   其他错误
│           │         │          │
↓           ↓         ↓          ↓
op_fix      inputShape 切换设备  查看建议
│           │         │          │
└─────┬─────┴─────────┴──────────┘
      ↓
重新推理
      ↓
成功

项目架构

目录结构

ohos_model_agent/
├── ohos_model_claw/              # 核心 Python 包
│   ├── __init__.py              # 包初始化
│   ├── mcp_server.py            # MCP 服务器实现
│   ├── ohos_model_claw.py       # CLI 命令行入口
│   ├── tool_manager.py          # MindSpore Lite 工具管理
│   ├── task_manager.py          # 异步任务管理
│   ├── error_parser.py          # 转换错误解析和算子检测
│   └── requirements.txt         # Python 依赖
│
├── .opencode/                    # OpenCode AI Agent 配置
│   ├── skills/                  # 技能定义目录
│   │   ├── onnx-converter-operator-fix/   # 转换算子修复技能
│   │   │   ├── SKILL.md         # 技能说明文档
│   │   │   └── scripts/
│   │   │       └── onnx_op_replace.py  # 算子替换实现
│   │   ├── onnx2ms-runtime-operator-fix/ # 运行时错误修复技能
│   │   │   ├── SKILL.md         # 技能说明文档
│   │   │   └── scripts/
│   │   │       └── runtime_error_analyzer.py  # 错误分析实现
│   │   ├── harmonyos-model-convert/  # 模型转换技能
│   │   │   └── SKILL.md
│   │   └── harmonyos-model-benchmark/  # 性能测试技能
│   │       └── SKILL.md
│   ├── opencode.json            # OpenCode 配置文件
│   └── package.json             # Node.js 依赖
│
├── tests/                        # 单元测试
│   ├── test_model_convert.py    # 模型转换测试
│   ├── test_model_benchmark.py  # 性能测试
│   ├── test_operator_fix.py     # 算子修复测试
│   ├── test_mcp_convert.py      # MCP 转换接口测试
│   ├── test_mcp_benchmark.py    # MCP benchmark 接口测试
│   ├── test_mcp_operator_fix.py # MCP 算子修复接口测试
│   ├── auto_test.py             # 自动化测试脚本
│   ├── model/                   # 测试模型
│   │   ├── convert/             # 转换测试模型
│   │   ├── benchmark/           # 性能测试模型
│   │   └── operator_fix/        # 算子修复测试模型
│   └── output/                  # 测试输出
│
├── input/                        # 输入目录 (用户模型)
├── output/                       # 输出目录 (转换结果)
│
└── README.md                    # 项目文档

核心模块

1. MCP Server (mcp_server.py)

提供 6 个 MCP 工具供 AI Agent 调用:

  • 工具状态检查
  • 模型转换(同步/异步)
  • 性能测试
  • 代码生成
  • 算子修复
  • 任务状态查询

2. Tool Manager (tool_manager.py)

MindSpore Lite 工具生命周期管理:

  • 自动下载工具包 (~200MB)
  • SHA256 哈希验证
  • 自动解压和安装
  • 环境变量配置
  • DLL 加载路径设置

3. Task Manager (task_manager.py)

异步任务执行和状态跟踪:

  • 任务创建和 UUID 生成
  • 后台线程执行
  • 状态管理 (PENDING/RUNNING/COMPLETED/FAILED)
  • 任务结果缓存

4. Error Parser (error_parser.py)

转换错误分析和算子检测:

  • 正则匹配错误模式
  • 自动识别问题算子
  • 生成修复建议

5. ONNX Op Replace (onnx_op_replace.py)

ONNX 图修改和算子替换:

  • 使用 onnx-graphsurgeon 进行图操作
  • 保持拓扑顺序
  • 自动清理悬空节点

架构图

用户/AI Agent
      ↓
  MCP Server
      ↓
┌─────┴─────┬─────────┬──────────┐
│           │         │          │
↓           ↓         ↓          ↓
Tool      Task    Error     Op Fix
Manager   Manager  Parser   Script
│           │         │          │
└─────┬─────┴─────────┴──────────┘
      ↓
  CLI Entry (ohos_model_claw.py)
      ↓
  MindSpore Lite Tools
      ↓
  .ms Model File

开发指南

环境搭建

# 克隆项目
git clone <repository-url>
cd ohos_model_agent

# 创建虚拟环境
python -m venv venv
source venv/bin/activate  # Linux/Mac
# 或
venv\Scripts\activate  # Windows

# 安装依赖
pip install -r ohos_model_claw/requirements.txt

# 安装开发依赖
pip install pytest black flake8

运行测试

# 运行所有测试
python -m pytest tests/

# 运行特定测试
python -m pytest tests/test_ohos_model_claw.py -v

# 测试覆盖率
python -m pytest tests/ --cov=ohos_model_claw

添加新的算子支持

  1. error_parser.py 中添加错误检测模式:
ERROR_PATTERNS = {
    # 添加新算子
    "new_op_error": {
        "pattern": r"Unsupported operator: NewOp",
        "operator": "NewOp"
    }
}
  1. onnx_op_replace.py 中添加替换函数:
def replace_new_op_equivalent(graph, node):
    """替换 NewOp 为等价子图"""
    # 实现替换逻辑
    pass
  1. fix_onnx_operators() 中注册:
OPERATOR_REPLACEMENTS = {
    "NewOp": replace_new_op_equivalent,
}

代码规范

# 格式化代码
black ohos_model_claw/

# 代码检查
flake8 ohos_model_claw/

# 类型检查 (如果使用)
mypy ohos_model_claw/

常见问题

1. 工具下载失败

问题: MindSpore Lite 工具下载超时或失败

解决:

# 手动下载
# 访问: https://ms-release.obs.cn-north-4.myhuaweicloud.com/2.5.0/MindSpore/lite/release/windows/
# 下载: mindspore-lite-2.5.0-win-x64.zip

# 解压到用户目录
~/.ohos_model_claw/tools/mindspore-lite-2.5.0-win-x64/

2. DLL 加载失败

问题: ImportError: DLL load failed

解决:

  • 安装 Visual C++ Redistributable
  • 确保 Python 版本 ≥ 3.8

3. 转换失败

问题: 模型转换时出现算子不支持错误

解决:

# 使用算子修复工具
python -m ohos_model_claw.ohos_model_claw op_fix model.onnx

# 重新转换
python -m ohos_model_claw.ohos_model_claw convert model_fixed.onnx

4. 异步任务超时

问题: MCP 异步任务超时

解决:

  • 增大 opencode.json 中的 timeout
  • 使用 CLI 同步模式执行

5. 性能测试失败

问题: GPU/NPU 性能测试失败

解决:

  • 确保设备支持 GPU/NPU
  • 检查驱动是否正确安装
  • 使用 CPU 模式测试

6. 动态 Shape 模型转换失败

问题: 转换或 benchmark 时提示 shape 错误

解决:

# 1. 查询模型信息,检测动态 shape
python -m ohos_model_claw.ohos_model_claw info model.onnx

# 2. 根据建议使用 inputShape 参数
python -m ohos_model_claw.ohos_model_claw convert model.onnx --inputShape "input:1,3,224,224"

# 3. benchmark 时也需要指定 inputShape
python -m ohos_model_claw.ohos_model_claw benchmark model.ms --inputShape "input:1,3,224,224"

7. 运行时推理失败

问题: .ms 模型推理时报错

解决:

# 1. 分析错误日志
python -m ohos_model_claw.ohos_model_claw runtime_analyze "error message"

# 或从文件读取
python -m ohos_model_claw.ohos_model_claw runtime_analyze error.log --ms_path model.ms --device CPU

# 2. 根据诊断建议修复
# - 算子不支持:使用 op_fix 修复
# - Shape 不匹配:检查数据预处理
# - 设备不支持:切换设备类型

贡献指南

欢迎贡献代码、报告问题或提出建议!

贡献流程

  1. Fork 本项目
  2. 创建功能分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 创建 Pull Request

代码贡献规范

  • 遵循 PEP 8 代码风格
  • 添加必要的单元测试
  • 更新相关文档
  • 确保所有测试通过

Bug 报告

请包含以下信息:

  • 操作系统和版本
  • Python 版本
  • 错误信息和堆栈跟踪
  • 复现步骤

许可证

本项目采用 MIT 许可证。详见 LICENSE 文件。

致谢

联系方式


注意: 本项目目前仅支持 Windows x64 平台。Linux 和 macOS 支持计划在未来版本中推出。