KernelBench-M / tests /instancenorm_cpu_harness.cpp
Elfsong's picture
WIP: fix InstanceNorm large-mean cancellation; CUDA regeneration pending
f63fb35 verified
Raw History Blame
1.98 kB
// Numerical regression harness only: executes one CUDA block at a time on CPU.
// This checks the actual kernel body, but cannot validate GPU race behavior,
// CUDA compilation, approximate rsqrt, or performance.
#include <cmath>
#include <condition_variable>
#include <cstdlib>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
struct Dim { int x = 0; int y = 0; int z = 0; };
thread_local Dim blockIdx, threadIdx;
class BlockBarrier {
std::mutex mutex;
std::condition_variable ready;
int arrived = 0;
int generation = 0;
public:
void wait() {
std::unique_lock<std::mutex> lock(mutex);
int current = generation;
if (++arrived == 256) {
arrived = 0;
++generation;
ready.notify_all();
} else {
ready.wait(lock, [&] { return generation != current; });
}
}
};
BlockBarrier barrier;
#define __global__
#define __shared__ static
#define __syncthreads() barrier.wait()
float rsqrtf(float x) { return 1.0f / std::sqrt(x); }
// KERNEL_BODY
int main(int argc, char** argv) {
if (argc != 4) return 2;
int planes = std::atoi(argv[1]);
int height = std::atoi(argv[2]);
int width = std::atoi(argv[3]);
size_t count = size_t(planes) * height * width;
std::vector<float> x(count), out(count, NAN);
std::cin.read(reinterpret_cast<char*>(x.data()), count * sizeof(float));
if (!std::cin) return 3;
std::vector<std::thread> workers;
for (int tid = 0; tid < 256; ++tid) {
workers.emplace_back([&, tid] {
threadIdx.x = tid;
for (int plane = 0; plane < planes; ++plane) {
blockIdx.x = plane;
instancenorm_kernel(x.data(), out.data(), planes, height, width);
barrier.wait();
}
});
}
for (auto& worker : workers) worker.join();
std::cout.write(reinterpret_cast<const char*>(out.data()), count * sizeof(float));
}