我在 Rust 中使用
Array2
或 Array1
作为神经网络中的矩阵。 (是的,我知道有神经网络的库。我想用自己的学习代码来实现。这个问题独立于神经网络,但神经网络是一个合适的例子,因为在很多情况下,矩阵大小在编译时已知。)
当编译器在编译时知道
Array2
矩阵或 Array1
向量的大小时,它可以进行更好的优化吗?如何确保它认识他们?
这是我的神经网络层的代码,其中标记了一些行,我认为也许我们可以向编译器提供额外的信息。或者结构中甚至不需要它?
extern crate ndarray;
use ndarray::prelude::*;
use ndarray_rand::RandomExt;
use rand::distributions::Uniform;
struct LayerWithBias<const input_size: usize, const output_size: usize> {
/// weights
w: Array2<f32>, // do something with input_size and output_size here?
/// biases
b: Array1<f32>, // and do something with just output_size here?
}
impl<const input_size: usize, const output_size: usize>
LayerWithBias<input_size, output_size> {
fn new() -> Self {
let w = Array2::random((output_size, input_size), Uniform::new(-1.0, 1.0));
let b = Array1::zeros(output_size);
LayerWithBias { w, b }
}
}
不,您无法通过告诉编译器您的
ndarray
集合最终将保存的项目数量来启用任何特定的优化。
编译器“可能”利用此类信息的唯一方法是使用固定大小的数组,而 ndarray
的
Array1
和 Array2
则不然。即便如此,它可以进行的优化也适用于小型阵列,例如确保它们有效地填充缓存线。但是,如果您有足够多的数据值得使用ndarray
,那么这不会产生任何影响;您的数据是连续的,并将以最佳方式填充许多缓存行。