#simd-vector #vector #simd #distance #embedding #algorithm

floating-distance

在Rust中测量浮点向量的距离

3个版本 (破坏性更新)

0.3.1 2023年10月2日
0.2.0 2023年9月13日
0.1.0 2023年9月9日

算法中排名第1766

每月下载量25

MIT许可证

16KB
239

在Rust中测量浮点向量的距离

crates.io docs.rs coverage GitHub Actions

大家好!

这是一个Rust库。在这里,您可以做

  1. 将此crate作为Rust项目的依赖项添加
cargo add floating-distance
  1. 查看文档源代码(点击上面的徽章以获取更多信息)
  2. 克隆GitHub仓库并运行示例
cargo run --example default

示例

  1. 测量向量v0v1之间的余弦相似度
use floating_distance::*;

fn main() {
  let v0: &[f32] = &[1.0, 2.0, 2.0, 1.0, 2.0, 1.0, 1.0];
  let v1: &[f32] = &[2.0, 1.0, 1.0, 1.0, 2.0, 1.0, 2.0];
  let metric = Metric::Cosine;
  let result = metric.measure::<f32>(v0, v1);
  let expectation: f32 = 14.0 / (4.0 * 4.0);

  assert_eq!(result, expectation);
}

feature = ["simd"]

SIMD有什么特别之处?

SIMD是Single Instruction Multiple Data的缩写

现代CPU有特殊的指令。我们可以使用它们来加速向量计算!

如何启用SIMD?

您可以通过以下步骤在此crate中启用simd功能

  1. Cargo.toml清单中指定features = ["simd"]
[dependencies]
floating-distance = { version = "*", features = ["simd"] }
  1. 使用Rust nightly版本进行编译。您可以将此添加到rust-toolchain.toml,它与Cargo.toml相邻
[toolchain]
channel = "nightly"
  1. (可选)选择目标架构支持的SIMD指令集。您可以使用RUSTFLAGS环境变量和类似以下内容的编译器选项
RUSTFLAGS="-C target-feature=+ssse3" cargo build
RUSTFLAGS="-C target-feature=+avx,+sse3" cargo build --release

您可以通过这种方式找到Rust的所有目标功能

rustc --print target-features

SIMD有多强大?

我在我的笔记本电脑上运行了一个简单的基准测试(架构:aarch64-apple-darwin)。SIMD指令集是NEON。

让我们先看看结果!

  • SIMD与无SIMD(单精度浮点类型)比较
no_simd: 198,306 ns/iter (+/- 5,173)
simd:    18,430 ns/iter (+/- 655)
类型 平均时间(ns/iter) 速度(相对)
无SIMD 198306 1.00
SIMD 18430 10.76

如图所示,我们可以看到SIMD可以显著提高性能!

您也可以通过重复以下步骤进行基准测试

  1. 克隆仓库并将其更改到当前目录
  2. .cargo/config.toml 中检查目标特性
  3. 运行以下命令
(cargo +nightly bench -p benchmarks-no-simd &&
 cargo +nightly bench -p benchmarks-simd) 2> /dev/null

关于 SIMD 特性的说明

  1. 该特性是通过 Rust 标准库的实验性特性 portable-simd 构建的。
  2. 如果程序使用的是目标架构不支持的目标特性构建,可能会导致运行时错误。

依赖项

~155KB