前回に引き続き軽量価値ネットワークの推論処理をSIMDで実装する。
前回は全結合の推論処理を実装したが、今回は畳み込み層を実装する。
畳み込み層
実装中の軽量価値ネットワークは、9x1と1x9のカーネルを並列で適用を行う。
入力サイズは9x9で固定のため、片方の軸方向にはストライドは発生しない。
また、パディングも不要である。
その特定を活かすことで、処理を高速化できる。
SIMDによる実装
今回も、o3-mini-highと、Claude 3.7に修正がなくなるまで指摘をさせあって、実装した。
実装したコードは、以下の通り。
入力が固定長であることを活かして、フラットなベクトルにしてから内積を計算することで高速化されている。
#include <immintrin.h> #include <cstddef> // ============================================================================= // horizontal_sum_avx2: // 説明: AVX2命令を使用して、256ビットベクトル内の全要素の水平加算を行います。 // ベクトル内の8個のfloat値の合計を返します。 // ============================================================================= inline float horizontal_sum_avx2(__m256 vec) { __m256 t1 = _mm256_hadd_ps(vec, vec); __m256 t2 = _mm256_hadd_ps(t1, t1); __m128 t3 = _mm256_extractf128_ps(t2, 1); __m128 t4 = _mm_add_ss(_mm256_castps256_ps128(t2), t3); return _mm_cvtss_f32(t4); } // ============================================================================= // prefetch_distance: // 説明: プリフェッチ時に使用する距離を、要素オフセット単位で指定します。 // (バイト単位ではなく、配列インデックスのオフセットとして扱います) // ============================================================================= constexpr int prefetch_distance = 64; // ============================================================================= // conv9x1_avx2: // 説明: 入力データに対して 9x1 の畳み込み演算をAVX2命令で高速に実行します。 // ・入力: input[InChannels][9][9](CHWレイアウト、固定サイズ 9x9) // ・カーネル: 9x1(縦方向9、横方向1)。パディングは不要。 // ・重み: weights[OutChannels][InChannels*9](各出力チャネルごとに InChannels×9 個の重み。 // 内部では8要素単位にパディングされる場合がある) // ・出力: output[OutChannels][9](各出力チャネルについて、1行9列分の結果をフラットに格納) // テンプレートパラメータ: // InChannels - 入力チャネル数 // OutChannels - 出力チャネル数 // 最適化ポイント: // ・ループ内で9要素分を完全アンローリングすることでループオーバーヘッドを削減 // ・AVX2のFMA命令を用いたベクトル演算で高速化 // ・プリフェッチ命令により、次のデータを事前に読み込んでメモリアクセスの遅延を低減 // ============================================================================= template <int InChannels, int OutChannels> void conv9x1_avx2(const float* __restrict input, const float* __restrict weights, float* __restrict output) { constexpr int KERNEL_SIZE = 9; constexpr int inner_size = InChannels * KERNEL_SIZE; // 内積計算用のサイズは8要素単位にパディング(inner_sizeは多くの場合既に8の倍数) constexpr int padded_inner_size = ((inner_size + 7) / 8) * 8; // 出力は各チャネルにつき1行(9列分)となるため、横方向に9回ループ for (int w = 0; w < 9; ++w) { // patch: 各入力チャネルからw列目の縦方向9要素を格納するテンポラリバッファ alignas(32) float patch[inner_size]; for (int ic = 0; ic < InChannels; ++ic) { const float* in_channel = input + ic * 81; // 各チャネルは9x9=81要素 int base = ic * KERNEL_SIZE; // カーネルサイズが固定のため、完全にアンローリングして各要素をコピー patch[base + 0] = in_channel[0 * 9 + w]; patch[base + 1] = in_channel[1 * 9 + w]; patch[base + 2] = in_channel[2 * 9 + w]; patch[base + 3] = in_channel[3 * 9 + w]; patch[base + 4] = in_channel[4 * 9 + w]; patch[base + 5] = in_channel[5 * 9 + w]; patch[base + 6] = in_channel[6 * 9 + w]; patch[base + 7] = in_channel[7 * 9 + w]; patch[base + 8] = in_channel[8 * 9 + w]; } int oc = 0; constexpr int unroll_factor = 4; int main_loop_count = (OutChannels / unroll_factor) * unroll_factor; // 出力チャネルをunroll_factor個ずつ処理 for (; oc < main_loop_count; oc += unroll_factor) { __m256 sum0 = _mm256_setzero_ps(); __m256 sum1 = _mm256_setzero_ps(); __m256 sum2 = _mm256_setzero_ps(); __m256 sum3 = _mm256_setzero_ps(); const float* w_ptr0 = weights + (oc + 0) * padded_inner_size; const float* w_ptr1 = weights + (oc + 1) * padded_inner_size; const float* w_ptr2 = weights + (oc + 2) * padded_inner_size; const float* w_ptr3 = weights + (oc + 3) * padded_inner_size; int i = 0; // ベクトル演算:8要素ずつ処理 for (; i <= inner_size - 8; i += 8) { // プリフェッチにより次のデータを先読み if (i + prefetch_distance < inner_size) { _mm_prefetch(reinterpret_cast<const char*>(patch + i + prefetch_distance), _MM_HINT_T0); _mm_prefetch(reinterpret_cast<const char*>(w_ptr0 + i + prefetch_distance), _MM_HINT_T0); _mm_prefetch(reinterpret_cast<const char*>(w_ptr1 + i + prefetch_distance), _MM_HINT_T0); _mm_prefetch(reinterpret_cast<const char*>(w_ptr2 + i + prefetch_distance), _MM_HINT_T0); _mm_prefetch(reinterpret_cast<const char*>(w_ptr3 + i + prefetch_distance), _MM_HINT_T0); } __m256 patch_vec = _mm256_load_ps(patch + i); __m256 w0 = _mm256_load_ps(w_ptr0 + i); __m256 w1 = _mm256_load_ps(w_ptr1 + i); __m256 w2 = _mm256_load_ps(w_ptr2 + i); __m256 w3 = _mm256_load_ps(w_ptr3 + i); sum0 = _mm256_fmadd_ps(patch_vec, w0, sum0); sum1 = _mm256_fmadd_ps(patch_vec, w1, sum1); sum2 = _mm256_fmadd_ps(patch_vec, w2, sum2); sum3 = _mm256_fmadd_ps(patch_vec, w3, sum3); } // AVX2内での水平加算で部分和を計算 float dot0 = horizontal_sum_avx2(sum0); float dot1 = horizontal_sum_avx2(sum1); float dot2 = horizontal_sum_avx2(sum2); float dot3 = horizontal_sum_avx2(sum3); // 余りの要素はスカラー演算で加算 for (; i < inner_size; ++i) { dot0 += patch[i] * w_ptr0[i]; dot1 += patch[i] * w_ptr1[i]; dot2 += patch[i] * w_ptr2[i]; dot3 += patch[i] * w_ptr3[i]; } // 出力は [OutChannels][1][9](各チャネル1行9列)としてフラットに格納 output[(oc + 0) * 9 + w] = dot0; output[(oc + 1) * 9 + w] = dot1; output[(oc + 2) * 9 + w] = dot2; output[(oc + 3) * 9 + w] = dot3; } // 残りの出力チャネルを処理 for (; oc < OutChannels; ++oc) { __m256 sum = _mm256_setzero_ps(); const float* w_ptr = weights + oc * padded_inner_size; int i = 0; for (; i <= inner_size - 8; i += 8) { if (i + prefetch_distance < inner_size) { _mm_prefetch(reinterpret_cast<const char*>(patch + i + prefetch_distance), _MM_HINT_T0); _mm_prefetch(reinterpret_cast<const char*>(w_ptr + i + prefetch_distance), _MM_HINT_T0); } __m256 patch_vec = _mm256_load_ps(patch + i); __m256 w_vec = _mm256_load_ps(w_ptr + i); sum = _mm256_fmadd_ps(patch_vec, w_vec, sum); } float dot = horizontal_sum_avx2(sum); for (; i < inner_size; ++i) { dot += patch[i] * w_ptr[i]; } output[oc * 9 + w] = dot; } } } // ============================================================================= // conv1x9_avx2: // 説明: 入力データに対して 1x9 の畳み込み演算をAVX2命令で高速に実行します。 // ・入力: input[InChannels][9][9](CHWレイアウト、固定サイズ 9x9) // ・カーネル: 1x9(横方向9、縦方向1)。パディングは不要。 // ・重み: weights[OutChannels][InChannels*9](各出力チャネルごとに InChannels×9 個の重み。 // 内部では8要素単位にパディングされる場合がある) // ・出力: output[OutChannels][9](各出力チャネルについて、9行1列の結果をフラットに格納) // テンプレートパラメータ: // InChannels - 入力チャネル数 // OutChannels - 出力チャネル数 // 最適化ポイント: // ・アンローリングとAVX2/FMA命令を用いて、ベクトル演算を高速化 // ・プリフェッチ命令でメモリアクセスの遅延を低減 // ============================================================================= template <int InChannels, int OutChannels> void conv1x9_avx2(const float* __restrict input, const float* __restrict weights, float* __restrict output) { constexpr int KERNEL_SIZE = 9; constexpr int inner_size = InChannels * KERNEL_SIZE; constexpr int padded_inner_size = ((inner_size + 7) / 8) * 8; // 出力は各チャネルにつき9行(1列分)となるため、縦方向に9回ループ for (int h = 0; h < 9; ++h) { // patch: 各入力チャネルからh行目の横方向9要素を格納するテンポラリバッファ alignas(32) float patch[inner_size]; for (int ic = 0; ic < InChannels; ++ic) { const float* in_channel = input + ic * 81; int base = ic * KERNEL_SIZE; // 完全アンローリングして各要素をコピー patch[base + 0] = in_channel[h * 9 + 0]; patch[base + 1] = in_channel[h * 9 + 1]; patch[base + 2] = in_channel[h * 9 + 2]; patch[base + 3] = in_channel[h * 9 + 3]; patch[base + 4] = in_channel[h * 9 + 4]; patch[base + 5] = in_channel[h * 9 + 5]; patch[base + 6] = in_channel[h * 9 + 6]; patch[base + 7] = in_channel[h * 9 + 7]; patch[base + 8] = in_channel[h * 9 + 8]; } int oc = 0; constexpr int unroll_factor = 4; int main_loop_count = (OutChannels / unroll_factor) * unroll_factor; // 出力チャネルをunroll_factor個ずつ処理 for (; oc < main_loop_count; oc += unroll_factor) { __m256 sum0 = _mm256_setzero_ps(); __m256 sum1 = _mm256_setzero_ps(); __m256 sum2 = _mm256_setzero_ps(); __m256 sum3 = _mm256_setzero_ps(); const float* w_ptr0 = weights + (oc + 0) * padded_inner_size; const float* w_ptr1 = weights + (oc + 1) * padded_inner_size; const float* w_ptr2 = weights + (oc + 2) * padded_inner_size; const float* w_ptr3 = weights + (oc + 3) * padded_inner_size; int i = 0; for (; i <= inner_size - 8; i += 8) { if (i + prefetch_distance < inner_size) { _mm_prefetch(reinterpret_cast<const char*>(patch + i + prefetch_distance), _MM_HINT_T0); _mm_prefetch(reinterpret_cast<const char*>(w_ptr0 + i + prefetch_distance), _MM_HINT_T0); _mm_prefetch(reinterpret_cast<const char*>(w_ptr1 + i + prefetch_distance), _MM_HINT_T0); _mm_prefetch(reinterpret_cast<const char*>(w_ptr2 + i + prefetch_distance), _MM_HINT_T0); _mm_prefetch(reinterpret_cast<const char*>(w_ptr3 + i + prefetch_distance), _MM_HINT_T0); } __m256 patch_vec = _mm256_load_ps(patch + i); __m256 w0 = _mm256_load_ps(w_ptr0 + i); __m256 w1 = _mm256_load_ps(w_ptr1 + i); __m256 w2 = _mm256_load_ps(w_ptr2 + i); __m256 w3 = _mm256_load_ps(w_ptr3 + i); sum0 = _mm256_fmadd_ps(patch_vec, w0, sum0); sum1 = _mm256_fmadd_ps(patch_vec, w1, sum1); sum2 = _mm256_fmadd_ps(patch_vec, w2, sum2); sum3 = _mm256_fmadd_ps(patch_vec, w3, sum3); } float dot0 = horizontal_sum_avx2(sum0); float dot1 = horizontal_sum_avx2(sum1); float dot2 = horizontal_sum_avx2(sum2); float dot3 = horizontal_sum_avx2(sum3); for (; i < inner_size; ++i) { dot0 += patch[i] * w_ptr0[i]; dot1 += patch[i] * w_ptr1[i]; dot2 += patch[i] * w_ptr2[i]; dot3 += patch[i] * w_ptr3[i]; } // 出力は [OutChannels][9][1](各チャネル9行1列)として、フラットに格納 output[(oc + 0) * 9 + h] = dot0; output[(oc + 1) * 9 + h] = dot1; output[(oc + 2) * 9 + h] = dot2; output[(oc + 3) * 9 + h] = dot3; } // 残りの出力チャネルを処理 for (; oc < OutChannels; ++oc) { __m256 sum = _mm256_setzero_ps(); const float* w_ptr = weights + oc * padded_inner_size; int i = 0; for (; i <= inner_size - 8; i += 8) { if (i + prefetch_distance < inner_size) { _mm_prefetch(reinterpret_cast<const char*>(patch + i + prefetch_distance), _MM_HINT_T0); _mm_prefetch(reinterpret_cast<const char*>(w_ptr + i + prefetch_distance), _MM_HINT_T0); } __m256 patch_vec = _mm256_load_ps(patch + i); __m256 w_vec = _mm256_load_ps(w_ptr + i); sum = _mm256_fmadd_ps(patch_vec, w_vec, sum); } float dot = horizontal_sum_avx2(sum); for (; i < inner_size; ++i) { dot += patch[i] * w_ptr[i]; } output[oc * 9 + h] = dot; } } }
以下の点が高速化のために工夫されている。
入力サイズ9x9とカーネルサイズ9x1または1x9という制約を前提に、不要なストライド処理やパディング処理を排除した効率化:
- 固定サイズに依存した完全アンローリング
9x9という固定サイズなので、各チャネル内の9要素のコピー処理をループを使わずに明示的に記述(完全アンローリング)し、ループオーバーヘッドを削減している。
カーネルが9x1または1x9であるため、もう一方の軸は1要素となり、ストライド処理や複雑なウィンドウ操作が不要になり、単一方向のベクトル内積計算に特化できる。
- 境界処理不要による実装の簡素化
入力サイズが固定でパディングが不要なため、端部の特別な処理を省略でき、計算処理のフローがシンプルかつ効率的になっている。
- テンポラリバッファへの効率的なデータ配置
各出力位置ごとに固定サイズのデータ(9要素または9チャネル分)をテンポラリバッファにアンローリングしてコピーすることで、連続したメモリアクセスとSIMDベクトル演算が容易に行えるよう工夫されている。
その他の高速化テクニック:
- SIMD命令による並列計算
AVX2命令(_mm256_load_ps、_mm256_fmadd_ps、_mm256_hadd_psなど)を用いて、複数のfloat値を一度に処理している。
- FMA(乗算加算)命令の活用
_mm256_fmadd_ps命令により、乗算と加算を一命令で行うことで、演算回数を削減し高速化している。
- ループの完全アンローリング
・入力データからテンポラリバッファへのコピーで、9要素を明示的にコピーすることでループオーバーヘッドを排除している。
・出力チャネルの処理でも、unroll_factor=4でまとめて計算している。
- メモリプリフェッチ
_mm_prefetch命令を使用して、次に必要となるデータを事前にキャッシュに読み込むことで、メモリアクセス遅延を低減している。
- データアライメント
32バイト境界に合わせたアラインメント(alignas(32))を行い、SIMDロード命令が高速に動作するようにしている。
- パディングによるベクトル化の最適化
内部サイズ(InChannels×9)が8の倍数になるようパディングし、AVX2での8要素単位の処理が安全に行えるようにしている。
- __restrictキーワードの利用
ポインタが重なっていないことを明示することで、コンパイラによる最適化(メモリアクセスの再順序化など)を促進している。
- テンプレートパラメータによる定数伝搬
InChannelsやOutChannelsをテンプレートパラメータとして渡すことで、コンパイル時に定数として扱われ最適化が容易になっている。
結果の検証
以下の通り、9x1、1x9の畳み込みそれぞれについて、入力チャネル16、出力チャネル4の畳み込み層をランダム初期値で推論するベンチマークコードを実装した。
結果は、バイナリで出力して、Pythonのnumpyで検証できるようにする。
#include <iostream> #include <chrono> #include <random> #include <algorithm> #include <fstream> // ============================================================================= // main: // 説明: 畳み込み層の推論処理のベンチマークを実行します。 // ・ランダムな入力データと重みを用いて、conv9x1_avx2およびconv1x9_avx2の処理を複数回実行 // ・実行時間、1イテレーションあたりの平均時間、GFLOPSを計測・表示 // ・入力、重み、出力のデータをバイナリファイルとして保存 // ============================================================================= int main() { // 定数設定 constexpr int InChannels = 16; constexpr int OutChannels = 4; constexpr int input_h = 9; constexpr int input_w = 9; constexpr int input_size = InChannels * input_h * input_w; // 16 * 81 = 1296 constexpr int kernel_size = 9; constexpr int inner_size = InChannels * kernel_size; // 16 * 9 = 144 constexpr int padded_inner_size = ((inner_size + 7) / 8) * 8; constexpr int num_iterations = 10000; // 入力、重み、出力バッファの確保(32バイト境界アラインメント) alignas(32) float input[input_size]; alignas(32) float weights_conv9x1[OutChannels * padded_inner_size]; alignas(32) float weights_conv1x9[OutChannels * padded_inner_size]; alignas(32) float output_conv9x1[OutChannels * kernel_size]; alignas(32) float output_conv1x9[OutChannels * kernel_size]; // 乱数による初期化 std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<float> dist(-1.0f, 1.0f); for (int i = 0; i < input_size; ++i) { input[i] = dist(gen); } for (int oc = 0; oc < OutChannels; ++oc) { int offset = oc * padded_inner_size; for (int i = 0; i < inner_size; ++i) { weights_conv9x1[offset + i] = dist(gen); weights_conv1x9[offset + i] = dist(gen); } // パディング部は0で初期化 for (int i = inner_size; i < padded_inner_size; ++i) { weights_conv9x1[offset + i] = 0.f; weights_conv1x9[offset + i] = 0.f; } } // --------------------------- // conv9x1 のベンチマーク // --------------------------- auto start9x1 = std::chrono::high_resolution_clock::now(); for (int iter = 0; iter < num_iterations; ++iter) { conv9x1_avx2<InChannels, OutChannels>(input, weights_conv9x1, output_conv9x1); } auto end9x1 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> elapsed9x1 = end9x1 - start9x1; std::cout << "conv9x1: " << num_iterations << " iterations in " << elapsed9x1.count() << " ms\n"; std::cout << "Average time per iteration: " << elapsed9x1.count() / num_iterations << " ms\n"; double flops_conv9x1 = 2.0 * inner_size * (OutChannels * kernel_size) * num_iterations; std::cout << "GFLOPS (conv9x1): " << flops_conv9x1 / (elapsed9x1.count() * 1e6) << "\n"; std::cout << "First few outputs (conv9x1): "; for (int i = 0; i < std::min(OutChannels * kernel_size, 8); ++i) { std::cout << output_conv9x1[i] << " "; } std::cout << "\n"; // --------------------------- // conv1x9 のベンチマーク // --------------------------- auto start1x9 = std::chrono::high_resolution_clock::now(); for (int iter = 0; iter < num_iterations; ++iter) { conv1x9_avx2<InChannels, OutChannels>(input, weights_conv1x9, output_conv1x9); } auto end1x9 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> elapsed1x9 = end1x9 - start1x9; std::cout << "conv1x9: " << num_iterations << " iterations in " << elapsed1x9.count() << " ms\n"; std::cout << "Average time per iteration: " << elapsed1x9.count() / num_iterations << " ms\n"; double flops_conv1x9 = 2.0 * inner_size * (OutChannels * kernel_size) * num_iterations; std::cout << "GFLOPS (conv1x9): " << flops_conv1x9 / (elapsed1x9.count() * 1e6) << "\n"; std::cout << "First few outputs (conv1x9): "; for (int i = 0; i < std::min(OutChannels * kernel_size, 8); ++i) { std::cout << output_conv1x9[i] << " "; } std::cout << "\n"; // --------------------------- // バイナリファイル出力(共通の入力、conv9x1, conv1x9) // --------------------------- { std::ofstream fout("input_conv.bin", std::ios::binary); fout.write(reinterpret_cast<const char*>(input), sizeof(float) * input_size); } { std::ofstream fout("weights_conv9x1.bin", std::ios::binary); fout.write(reinterpret_cast<const char*>(weights_conv9x1), sizeof(float) * OutChannels * padded_inner_size); } { std::ofstream fout("output_conv9x1.bin", std::ios::binary); fout.write(reinterpret_cast<const char*>(output_conv9x1), sizeof(float) * OutChannels * kernel_size); } { std::ofstream fout("meta_conv9x1.txt"); fout << "InChannels " << InChannels << "\n"; fout << "OutChannels " << OutChannels << "\n"; fout << "InputH " << input_h << "\n"; fout << "InputW " << input_w << "\n"; fout << "KernelSize " << kernel_size << "\n"; fout << "PaddedInnerSize " << padded_inner_size << "\n"; fout << "ConvolutionType conv9x1\n"; } { std::ofstream fout("weights_conv1x9.bin", std::ios::binary); fout.write(reinterpret_cast<const char*>(weights_conv1x9), sizeof(float) * OutChannels * padded_inner_size); } { std::ofstream fout("output_conv1x9.bin", std::ios::binary); fout.write(reinterpret_cast<const char*>(output_conv1x9), sizeof(float) * OutChannels * kernel_size); } { std::ofstream fout("meta_conv1x9.txt"); fout << "InChannels " << InChannels << "\n"; fout << "OutChannels " << OutChannels << "\n"; fout << "InputH " << input_h << "\n"; fout << "InputW " << input_w << "\n"; fout << "KernelSize " << kernel_size << "\n"; fout << "PaddedInnerSize " << padded_inner_size << "\n"; fout << "ConvolutionType conv1x9\n"; } return 0; }
実行結果
conv9x1: 10000 iterations in 5.3137 ms Average time per iteration: 0.00053137 ms GFLOPS (conv9x1): 19.5118 First few outputs (conv9x1): 1.56416 5.25566 3.26333 -2.63085 -6.98382 -0.485052 -3.90017 5.75143 conv1x9: 10000 iterations in 5.2833 ms Average time per iteration: 0.00052833 ms GFLOPS (conv1x9): 19.6241 First few outputs (conv1x9): 0.561724 0.980677 -1.02801 0.47801 0.917243 -3.74033 1.89193 -1.32741
十分に高速に推論できている。
結果検証
Pythonのnumpyで結果を検証した。
import numpy as np # --- パラメータ設定 --- InChannels = 16 OutChannels = 4 input_h = 9 input_w = 9 kernel_size = 9 inner_size = InChannels * kernel_size # 144 # inner_size が既に8の倍数の場合、padded_inner_size は inner_size と同じ padded_inner_size = ((inner_size + 7) // 8) * 8 # --- 入力データの読み込み --- input_data = np.fromfile('../input_conv.bin', dtype=np.float32).reshape(InChannels, input_h, input_w) # ============================ # conv9x1 の検証 # ============================ weights_conv9x1 = np.fromfile('../weights_conv9x1.bin', dtype=np.float32).reshape(OutChannels, padded_inner_size) output_conv9x1_cpp = np.fromfile('../output_conv9x1.bin', dtype=np.float32).reshape(OutChannels, kernel_size) # conv9x1 の numpy 再現:各列 (w) ごとに、各チャネルの w 列(9要素)をフラット化して内積計算 output_conv9x1_np = np.empty((OutChannels, kernel_size), dtype=np.float32) for w in range(kernel_size): # 各チャネルの w 列(9要素)を連結してパッチを作成 patch = np.concatenate([input_data[ic, :, w] for ic in range(InChannels)]) for oc in range(OutChannels): output_conv9x1_np[oc, w] = np.dot(patch, weights_conv9x1[oc, :inner_size]) print("=== Conv9x1 検証 ===") print("Numpy computed output (conv9x1):\n", output_conv9x1_np) print("C++ output (conv9x1):\n", output_conv9x1_cpp) print("Absolute difference (conv9x1):\n", np.abs(output_conv9x1_np - output_conv9x1_cpp)) # ============================ # conv1x9 の検証 # ============================ weights_conv1x9 = np.fromfile('../weights_conv1x9.bin', dtype=np.float32).reshape(OutChannels, padded_inner_size) output_conv1x9_cpp = np.fromfile('../output_conv1x9.bin', dtype=np.float32).reshape(OutChannels, kernel_size) # conv1x9 の numpy 再現:各行 (h) ごとに、各チャネルの h 行(9要素)を連結して内積計算 output_conv1x9_np = np.empty((OutChannels, kernel_size), dtype=np.float32) for h in range(kernel_size): patch = np.concatenate([input_data[ic, h, :] for ic in range(InChannels)]) for oc in range(OutChannels): output_conv1x9_np[oc, h] = np.dot(patch, weights_conv1x9[oc, :inner_size]) print("\n=== Conv1x9 検証 ===") print("Numpy computed output (conv1x9):\n", output_conv1x9_np) print("C++ output (conv1x9):\n", output_conv1x9_cpp) print("Absolute difference (conv1x9):\n", np.abs(output_conv1x9_np - output_conv1x9_cpp))
結果:
=== Conv9x1 検証 === Numpy computed output (conv9x1): [[ 1.5641618 5.2556643 3.2633276 -2.6308546 -6.9838204 -0.485052 -3.9001722 5.7514305 -2.2857516 ] [ 2.091999 3.1177278 -3.373773 -3.425416 6.924945 -0.92384076 0.15555573 -1.2977498 -3.8498452 ] [-5.8451557 1.8362662 -5.873499 2.0092218 5.032731 -8.113145 7.337962 5.8462534 0.44874334] [-6.347689 -1.781589 3.2830534 -2.149039 1.1098552 -5.9498563 3.8585086 2.9592352 -2.3028638 ]] C++ output (conv9x1): [[ 1.5641612 5.2556643 3.2633276 -2.6308546 -6.98382 -0.48505235 -3.9001725 5.7514315 -2.2857516 ] [ 2.0919995 3.1177275 -3.3737736 -3.4254158 6.924944 -0.9238405 0.15555578 -1.2977495 -3.849845 ] [-5.8451557 1.8362666 -5.8735 2.009222 5.032731 -8.113144 7.337962 5.8462534 0.44874382] [-6.34769 -1.7815894 3.2830536 -2.1490395 1.1098549 -5.9498563 3.8585072 2.9592357 -2.302864 ]] Absolute difference (conv9x1): [[5.9604645e-07 0.0000000e+00 0.0000000e+00 0.0000000e+00 4.7683716e-07 3.5762787e-07 2.3841858e-07 9.5367432e-07 0.0000000e+00] [4.7683716e-07 2.3841858e-07 4.7683716e-07 2.3841858e-07 9.5367432e-07 2.3841858e-07 5.9604645e-08 2.3841858e-07 2.3841858e-07] [0.0000000e+00 4.7683716e-07 9.5367432e-07 2.3841858e-07 0.0000000e+00 9.5367432e-07 0.0000000e+00 0.0000000e+00 4.7683716e-07] [9.5367432e-07 3.5762787e-07 2.3841858e-07 4.7683716e-07 2.3841858e-07 0.0000000e+00 1.4305115e-06 4.7683716e-07 2.3841858e-07]] === Conv1x9 検証 === Numpy computed output (conv1x9): [[ 0.5617237 0.98067653 -1.0280063 0.47800952 0.9172429 -3.7403288 1.8919289 -1.3274052 0.9078865 ] [-0.22470355 -2.672614 6.4978876 -0.15231991 -0.5035653 -1.8699042 0.37124968 2.650444 1.3350382 ] [-0.71244425 -3.6045957 2.354258 2.9495811 -0.41683948 -3.4634871 -8.761951 -5.1912813 5.7042556 ] [-6.1926374 0.9113717 -1.1350325 -1.1799362 -2.5543666 -1.1106915 1.5124403 -2.0711913 5.021366 ]] C++ output (conv1x9): [[ 0.5617238 0.980677 -1.028006 0.47801006 0.9172425 -3.7403293 1.8919287 -1.3274058 0.907887 ] [-0.22470367 -2.672614 6.4978876 -0.15231991 -0.50356543 -1.8699036 0.3712492 2.6504433 1.3350382 ] [-0.7124448 -3.6045954 2.3542576 2.949581 -0.41683888 -3.4634876 -8.7619505 -5.1912804 5.704255 ] [-6.1926374 0.91137147 -1.1350325 -1.1799364 -2.554367 -1.1106912 1.5124396 -2.0711915 5.021367 ]] Absolute difference (conv1x9): [[1.1920929e-07 4.7683716e-07 3.5762787e-07 5.3644180e-07 3.5762787e-07 4.7683716e-07 2.3841858e-07 5.9604645e-07 4.7683716e-07] [1.1920929e-07 0.0000000e+00 0.0000000e+00 0.0000000e+00 1.1920929e-07 5.9604645e-07 4.7683716e-07 7.1525574e-07 0.0000000e+00] [5.3644180e-07 2.3841858e-07 4.7683716e-07 2.3841858e-07 5.9604645e-07 4.7683716e-07 9.5367432e-07 9.5367432e-07 4.7683716e-07] [0.0000000e+00 2.3841858e-07 0.0000000e+00 2.3841858e-07 4.7683716e-07 3.5762787e-07 7.1525574e-07 2.3841858e-07 9.5367432e-07]]
わずかなずれがあるが、計算順序の違いによる浮動小数点の誤差で、無視できる程度である。