我正在用 C++ 制作一个机器学习库,其学习目的是使用 Fastor Tensor 库。我正在优化我的代码,我发现我可以让每个功能都像这样:
这里有一堆复制了很多的代码:
//LogSoftMax
template<std::size_t batch_size, std::size_t output_features>
Fastor::Tensor<float, batch_size, output_features> logsoftmax(
const Fastor::Tensor<float, batch_size, output_features>& input
){
Fastor::Tensor<float, batch_size, output_features> output;
for(auto i = 0; i < batch_size; i++){
auto max_substraction = input(i,all) - max(input(i,all));
float log_sum_exp = log(sum(exp(max_substraction)));
output(i,all) = max_substraction - log_sum_exp;
}
return output;
}
这里我可以在 c++20 中使用 auto 关键字传递参数作为引用。
void logsoftmax(auto& input){
for(auto i = 0; i < batch_size; i++){
auto max_substraction = input(i,all) - max(input(i,all));
float log_sum_exp = log(sum(exp(max_substraction)));
input(i,all) = max_substraction - log_sum_exp;
}
}
我的意思是,它有效,但是这样做可以吗?这似乎是真的。
编辑:也许我没有解释清楚,Fastor 库是高度优化的,当你执行操作时它不会返回张量,它会返回一个视图以在之后进行操作,使用自动和引用我不会将张量传递给函数,但稍后会变成张量的对象,我问是因为这样做似乎很危险,我不知道你是否建议这样做。