iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
Rust

30天解鎖 Rust 開發者工具箱系列 第 11

「Day 11」usls 包裝實現多種 AI 應用

  • 分享至 

  • xImage
  •  

前言

今天來介紹一個專案 -- uslshttps://github.com/jamjamjon/usls。與前幾日介紹的 ort 進行 onnx runtime 的 FFI binding 一樣,這個專案底層也是如此。USLS 是一個基於 ONNX Runtime 的跨平台 Rust 機器學習推理庫,專為高效推理最先進的視覺和多模態模型而設計(通常參數量在 1B 以下)。該庫提供了豐富的預訓練模型支援,涵蓋物件偵測、影像分類、語義分割、關鍵點檢測、文字識別等多個領域。

安裝

Cargo.toml

[dependencies]
# 推薦:使用 GitHub 版本
usls = { git = "https://github.com/jamjamjon/usls" }

# 或者:使用 crates.io 版本
usls = "latest-version"

除 CPU 外,多種硬體設備都能進行模型推理

# CPU 推理
cargo run -r --example yolo -- --task detect --ver 8 --scale n --dtype fp16

# NVIDIA CUDA 加速
cargo run -r -F cuda --example yolo -- --device cuda:0

# NVIDIA TensorRT 優化
cargo run -r -F tensorrt --example yolo -- --device tensorrt:0

# Apple Silicon CoreML
cargo run -r -F coreml --example yolo -- --device coreml

# Intel OpenVINO
cargo run -r -F openvino -F ort-load-dynamic --example yolo -- --device openvino:CPU

🤖 支援的 AI 模型

物件偵測 (Object Detection)

模型系列 主要功能
YOLO 物件偵測、實例分割、姿態估計
RT-DETR 即時 DETR 物件偵測
RF-DETR Roboflow DETR 物件偵測
D-FINE 高精度物件偵測
DEIM 動態早期退出推理模型
PP-PicoDet 輕量級物件偵測

影像分類 (Image Classification)

模型 描述
BEiT 雙向編碼器表示變換器
ConvNeXt 現代卷積神經網路
FastViT 快速視覺變換器
MobileOne 高效行動端模型
DeiT 資料高效影像變換器

語義分割 (Semantic Segmentation)

模型 功能
SAM Segment Anything 模型
SAM2 Segment Anything 2.0
MobileSAM 輕量級 SAM
EdgeSAM 邊緣裝置 SAM
FastSAM 快速實例分割

關鍵點檢測 (Keypoint Detection)

模型 應用場景
RTMPose 即時姿態估計
DWPose 全身姿態檢測
RTMW 全身關鍵點檢測
RTMO 多人姿態估計

視覺語言模型 (Vision-Language Models)

模型 功能
CLIP 視覺語言嵌入
BLIP 影像標題生成
Florence2 多任務視覺模型
Moondream2 視覺問答模型

文字識別 (Text Recognition)

模型 功能
DB 文字檢測
TrOCR 文字識別
SVTR 場景文字識別
SLANet 表格結構識別

影像處理 (Image Processing)

模型 功能
RMBG 背景移除
Swin2SR 超解析度重建
APISR 動漫影像超解析度

## ⚙️ 進階配置

### 硬體加速選項

USLS 支援多種硬體加速選項,可透過 Cargo features 啟用:

```toml
[dependencies]
usls = { 
    git = "https://github.com/jamjamjon/usls", 
    features = [
        "cuda",      # NVIDIA CUDA
        "tensorrt",  # NVIDIA TensorRT
        "coreml",    # Apple CoreML
        "openvino",  # Intel OpenVINO
        "directml",  # Microsoft DirectML
        "rocm",      # AMD ROCm
        "viewer",    # 視覺化工具
        "video"      # 影片處理
    ] 
}

模型配置範例

use usls::{models::YOLO, Config, DataLoader, Annotator};

// 建立 YOLOv8 配置
let config = Config::yolo_detect()
    .with_scale(Scale::N)
    .with_version(8.into())
    .with_model_device("cuda:0".parse()?)
    .with_model_dtype("fp16".parse()?)
    .with_nc(80)  // 類別數量
    .commit()?;

// 初始化模型
let mut model = YOLO::new(config)?;

// 載入影像
let xs = DataLoader::try_read_n(&["./assets/bus.jpg"])?;

// 執行推理
let ys = model.forward(&xs)?;

// 視覺化結果
let annotator = Annotator::default();
for (x, y) in xs.iter().zip(ys.iter()) {
    annotator.annotate(x, y)?.save("result.jpg")?;
}

上一篇
「Day 08」用 ort 打造 AI 物件辨識應用(三)
下一篇
「Day 12」candle 實現近乎純 Rust 神經網路模型框架
系列文
30天解鎖 Rust 開發者工具箱14
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言