1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
| namespace at::native {
// 加法算子的完整CPU实现(源码深度分析)
Tensor add_cpu(const Tensor& self, const Tensor& other, const Scalar& alpha) {
// 1. 类型检查和提升
auto common_type = promoteTypes(self.scalar_type(), other.scalar_type());
// 2. 创建输出张量
Tensor result = at::empty({0}, self.options().dtype(common_type));
// 3. 构建迭代器
auto iter = TensorIterator::Builder()
.add_output(result)
.add_input(self)
.add_input(other)
.build();
// 4. 分发到具体的内核实现
AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(
kBFloat16, kHalf, common_type, "add_cpu", [&] {
if (alpha.to<scalar_t>() == scalar_t(1)) {
// alpha=1的优化路径
cpu_kernel_vec(iter,
[=](scalar_t a, scalar_t b) -> scalar_t { return a + b; },
[=](Vectorized<scalar_t> a, Vectorized<scalar_t> b) { return a + b; });
} else {
// 通用路径:a + alpha * b
scalar_t alpha_val = alpha.to<scalar_t>();
cpu_kernel_vec(iter,
[=](scalar_t a, scalar_t b) -> scalar_t { return a + alpha_val * b; },
[=](Vectorized<scalar_t> a, Vectorized<scalar_t> b) {
return a + Vectorized<scalar_t>(alpha_val) * b;
});
}
});
return result;
}
// 矩阵乘法的优化实现(基于BLAS集成分析)
Tensor mm_cpu(const Tensor& self, const Tensor& mat2) {
// 1. 维度检查
TORCH_CHECK(self.dim() == 2 && mat2.dim() == 2, "tensors must be 2-D");
TORCH_CHECK(self.size(1) == mat2.size(0), "size mismatch");
// 2. 创建输出张量
auto result = at::empty({self.size(0), mat2.size(1)}, self.options());
// 3. 分发到BLAS实现或自定义内核
if (self.is_contiguous() && mat2.is_contiguous() && result.is_contiguous()) {
// 使用BLAS的快速路径
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(self.scalar_type(), "mm_cpu", [&] {
if constexpr (std::is_same_v<scalar_t, float>) {
// 使用OpenBLAS/MKL的SGEMM
cblas_sgemm(
CblasRowMajor, CblasNoTrans, CblasNoTrans,
self.size(0), mat2.size(1), self.size(1),
1.0f,
self.data_ptr<float>(), self.size(1),
mat2.data_ptr<float>(), mat2.size(1),
0.0f,
result.data_ptr<float>(), result.size(1)
);
} else if constexpr (std::is_same_v<scalar_t, double>) {
// 使用DGEMM
cblas_dgemm(/* 类似的参数 */);
} else {
// 其他类型回退到通用实现
generic_mm_impl(self, mat2, result);
}
});
} else {
// 非连续张量的通用实现
generic_mm_impl(self, mat2, result);
}
return result;
}
// 通用矩阵乘法实现(三重循环优化)
template<typename scalar_t>
void generic_mm_impl(const Tensor& a, const Tensor& b, Tensor& result) {
const int64_t M = a.size(0);
const int64_t N = b.size(1);
const int64_t K = a.size(1);
// 获取数据访问器
auto a_acc = a.accessor<scalar_t, 2>();
auto b_acc = b.accessor<scalar_t, 2>();
auto result_acc = result.accessor<scalar_t, 2>();
// 分块矩阵乘法优化缓存性能
constexpr int64_t kBlockSize = 64; // 缓存友好的块大小
for (int64_t m0 = 0; m0 < M; m0 += kBlockSize) {
for (int64_t n0 = 0; n0 < N; n0 += kBlockSize) {
for (int64_t k0 = 0; k0 < K; k0 += kBlockSize) {
// 处理当前块
int64_t m_end = std::min(m0 + kBlockSize, M);
int64_t n_end = std::min(n0 + kBlockSize, N);
int64_t k_end = std::min(k0 + kBlockSize, K);
for (int64_t m = m0; m < m_end; ++m) {
for (int64_t n = n0; n < n_end; ++n) {
scalar_t sum = (k0 == 0) ? scalar_t(0) : result_acc[m][n];
// 内积计算(编译器可以自动向量化)
for (int64_t k = k0; k < k_end; ++k) {
sum += a_acc[m][k] * b_acc[k][n];
}
result_acc[m][n] = sum;
}
}
}
}
}
}
// 卷积操作的CPU实现(基于im2col分析)
Tensor conv2d_cpu(
const Tensor& input, // [N, C_in, H_in, W_in]
const Tensor& weight, // [C_out, C_in, kH, kW]
const Tensor& bias, // [C_out]
IntArrayRef stride,
IntArrayRef padding,
IntArrayRef dilation,
int64_t groups) {
// 1. 参数验证
const int64_t ndim = input.dim();
TORCH_CHECK(ndim == 4, "conv2d expects 4D input");
// 2. 计算输出尺寸
const int64_t N = input.size(0);
const int64_t C_in = input.size(1);
const int64_t H_in = input.size(2);
const int64_t W_in = input.size(3);
const int64_t C_out = weight.size(0);
const int64_t kH = weight.size(2);
const int64_t kW = weight.size(3);
const int64_t H_out = (H_in + 2 * padding[0] - dilation[0] * (kH - 1) - 1) / stride[0] + 1;
const int64_t W_out = (W_in + 2 * padding[1] - dilation[1] * (kW - 1) - 1) / stride[1] + 1;
// 3. 创建输出张量
auto output = at::empty({N, C_out, H_out, W_out}, input.options());
// 4. 使用im2col + GEMM策略
AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "conv2d_cpu", [&] {
// im2col变换:将卷积转换为矩阵乘法
auto input_2d = im2col_cpu(input, {kH, kW}, stride, padding, dilation);
// input_2d: [N * H_out * W_out, C_in * kH * kW]
auto weight_2d = weight.view({C_out, -1});
// weight_2d: [C_out, C_in * kH * kW]
// 执行批量矩阵乘法
auto output_2d = at::mm(input_2d, weight_2d.t());
// output_2d: [N * H_out * W_out, C_out]
// 重塑为卷积输出形状
output = output_2d.view({N, H_out, W_out, C_out}).permute({0, 3, 1, 2});
// 添加偏置
if (bias.defined()) {
output.add_(bias.view({1, C_out, 1, 1}));
}
});
return output;
}
// im2col的高效实现
Tensor im2col_cpu(
const Tensor& input,
IntArrayRef kernel_size,
IntArrayRef stride,
IntArrayRef padding,
IntArrayRef dilation) {
const int64_t N = input.size(0);
const int64_t C = input.size(1);
const int64_t H = input.size(2);
const int64_t W = input.size(3);
const int64_t kH = kernel_size[0];
const int64_t kW = kernel_size[1];
const int64_t H_out = (H + 2 * padding[0] - dilation[0] * (kH - 1) - 1) / stride[0] + 1;
const int64_t W_out = (W + 2 * padding[1] - dilation[1] * (kW - 1) - 1) / stride[1] + 1;
// 输出:[N * H_out * W_out, C * kH * kW]
auto output = at::empty({N * H_out * W_out, C * kH * kW}, input.options());
AT_DISPATCH_ALL_TYPES(input.scalar_type(), "im2col_cpu", [&] {
auto input_acc = input.accessor<scalar_t, 4>();
auto output_acc = output.accessor<scalar_t, 2>();
// 并行处理每个输出位置
at::parallel_for(0, N * H_out * W_out, 0, [&](int64_t begin, int64_t end) {
for (int64_t index = begin; index < end; ++index) {
// 解码输出位置
int64_t w_out = index % W_out;
int64_t h_out = (index / W_out) % H_out;
int64_t n = index / (H_out * W_out);
// 计算输入位置
int64_t h_start = h_out * stride[0] - padding[0];
int64_t w_start = w_out * stride[1] - padding[1];
// 复制卷积窗口
int64_t col_idx = 0;
for (int64_t c = 0; c < C; ++c) {
for (int64_t kh = 0; kh < kH; ++kh) {
for (int64_t kw = 0; kw < kW; ++kw) {
int64_t h = h_start + kh * dilation[0];
int64_t w = w_start + kw * dilation[1];
if (h >= 0 && h < H && w >= 0 && w < W) {
output_acc[index][col_idx] = input_acc[n][c][h][w];
} else {
output_acc[index][col_idx] = scalar_t(0); // 填充
}
++col_idx;
}
}
}
}
});
});
return output;
}
} // namespace at::native
|