File size: 1,982 Bytes
f63fb35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// 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));
}