我目前正在构建自定义TensorFlow Op。它应该像Conv2D-Op一样工作,只是它使用自定义数据类型来完成。由于在Eigen中实现自定义数据类型相对容易,而在TensorFlow中则非常困难,因此我决定在TensorFlow调用Eigen之前使用我的自定义数据类型将Eigen张量复制到新的Eigen张量。将Eigen::TensorMap<Eigen::Tensor<float, 4, Eigen::RowMajor, Eigen::DenseIndex>, Eigen::Aligned>
转换为Eigen::TensorMap<Eigen::Tensor<CustomType, 4, Eigen::RowMajor, Eigen::DenseIndex>, Eigen::Aligned>
,运行计算,然后转换回float
。
我在conv_2d.h
的{{1}}的TensorFlows operator()
中添加了一些代码。我编写了两个辅助函数SpatialConvolution
和convertToCustomType
,它们应该为我完成转换。目前,我并不十分在意性能。
所以基本上我在这行之前和之后注入了两个转换函数:https://github.com/tensorflow/tensorflow/blob/r1.12/tensorflow/core/kernels/conv_2d.h#L72
convertFromCustomType
我还尝试分别遍历张量的所有4个维度,这似乎也不起作用。
template<typename T>
Eigen::Tensor<CustomType, 4, Eigen::RowMajor, Eigen::DenseIndex> convertToCustomType(T &input) {
Eigen::Tensor<CustomType, 4, Eigen::RowMajor, Eigen::DenseIndex> ret;
ret.resize(input.dimensions());
for (int a = 0; a < ret.size(); a++) {
ret(a) = input(a);
}
return ret;
}
template<typename T1, typename T2>
void convertFromCustomType(T1 &input, T2 &output) {
for (int a = 0; a < input.size(); a++) {
output(a) = input(a);
}
}
template<typename Device, typename T>
struct SpatialConvolution {
void operator()(const Device &d, typename TTypes<T, 4>::Tensor output,
typename TTypes<T, 4>::ConstTensor input,
typename TTypes<T, 4>::ConstTensor filter, int row_stride,
int col_stride, int row_dilation, int col_dilation,
const Eigen::PaddingType &padding) {
auto input_c = convertToCustomType(input);
auto filter_c = convertToCustomType(filter);
auto output_c = convertToCustomType(output);
SpatialConvolutionFunc(d, output_c, input_c, filter_c, row_stride, col_stride, row_dilation, col_dilation, padding);
convertFromCustomType(output_approx, output);
output.device(d) = output;
}
};
两个版本都可以编译,但是会产生不正确的结果。如果我使用此自定义Op运行我的整个TensorFlow网络,它将变得不确定,输出将在相同输入的不同运行中发生变化。
template <typename T>
Eigen::Tensor<ApproxType, 4, Eigen::RowMajor> convertToCustomType(T input) {
Eigen::Tensor<ApproxType, 4, Eigen::RowMajor> ret;
ret.resize(input.dimensions());
for (int a = 0; a < ret.dimension(0); a++) {
for (int b = 0; b < ret.dimension(1); b++) {
for (int c = 0; c < ret.dimension(2); c++) {
for (int d = 0; d < ret.dimension(3); d++) {
ret(a, b, c, d) = input(a, b, c, d);
}
}
}
}
return ret;
}
我应该如何更改本征张量的实际类型?
我注意到有一种类似0
[[-0.06590138]]
1
[[-0.04544453]]
2
[[-0.0286443]]
3
[[-0.06590138]]
4
[[-0.06590138]]
5
[[-0.04544453]]
的优雅方式,但是以Tensor::cast<T>()
为T
以外的任何其他名称进行调用都无法编译。我可能会丢失自定义类型的内容吗?
我知道这是一个非常具体的问题,但是任何想法我都会感激。
答案 0 :(得分:0)
显然,创建张量是不够的,例如,在填充之前必须先用ret.setZero()
进行初始化。