#machine-learning #deep-learning #tensor #hugging-face

rai-opt

Rust中的ML框架,具有直观的API

8个版本 (破坏性)

0.11.0 2024年5月14日
0.10.0 2024年3月26日
0.9.0 2024年2月24日
0.8.0 2024年2月20日
0.4.0 2024年1月4日

#847 in 机器学习


用于 3 个crate(通过 rai

MIT/Apache

305KB
9K SLoC

RAI

Rust Docs Status Latest Version Discord

具有直观API的Rust机器学习框架。具有类似JAX的懒计算和可组合转换。

安装

cargo add rai

代码片段

函数转换(jvp、vjp、grad、value_and_grad)

use rai::{grad, Cpu, Tensor, F32};

fn f(x: &Tensor) -> Tensor {
    x.sin()
}

fn main() {
    let grad_fn = grad(grad(f));
    let x = &Tensor::ones([1], F32, &Cpu);
    let grad = grad_fn(x);
    println!("{}", grad.dot_graph());
    println!("{}", grad);
}

神经网络模块、优化器和损失函数

fn loss_fn<M: TrainableModule<Input = Tensor, Output = Tensor>>(
    model: &M,
    input: &Tensor,
    labels: &Tensor,
) -> (Tensor, Aux<Tensor>) {
    let logits = model.forward(input);
    let loss = softmax_cross_entropy(&logits, labels).mean(..);
    (loss, Aux(logits))
}

fn train_step<M: TrainableModule<Input = Tensor, Output = Tensor>, O: Optimizer>(
    optimizer: &mut O,
    model: &M,
    input: &Tensor,
    labels: &Tensor,
) {
    let vg_fn = value_and_grad(loss_fn);
    let ((_loss, Aux(_logits)), (grads, ..)) = vg_fn((model, input, labels));
    let mut params = optimizer.step(&grads);
    eval(&params);
    model.update_params(&mut params);
}

示例

  • 线性回归
    • cargo运行 --bin线性回归 --发布
  • mnist
    • cargo运行 --binmnist --发布
    • cargo运行 --binmnist --发布 --特性=cuda
  • mnist-cnn
    • cargo运行 --binmnist-cnn --发布
    • cargo运行 --binmnist-cnn --发布 --特性=cuda
  • phi2
    • cargo运行 --binphi2 --发布
    • cargo运行 --binphi2 --发布 --特性=cuda
  • phi3
    • cargo运行 --binphi3 --发布
    • cargo运行 --binphi3 --发布 --特性=cuda
  • qwen2
    • cargo运行 --binqwen2 --发布
    • cargo运行 --binqwen2 --发布 --特性=cuda
  • gemma
    • https://hugging-face.cn/google/gemma-2b上接受许可协议
    • pip install huggingface_hub
    • 登录hf huggingface-cli login
    • cargo运行 --bingemma --发布
    • cargo运行 --bingemma --发布 --特性=cuda
  • vit
    • cargo运行 --binvit --发布
    • cargo运行 --binvit --发布 --特性=cuda

授权协议

本项目采用以下授权协议之一:

任选其一。

依赖项

~4–17MB
~252K SLoC