mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-05 15:58:53 +00:00
62 lines
3.1 KiB
C++
62 lines
3.1 KiB
C++
// tests/ling32/ling32_sy_topk_test.cpp - gpu::topk_rows (radix select, ties by lower index) against a host sort, for several vocab sizes, K and tie patterns.
|
|
#include "ling32_spec.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <cstdio>
|
|
#include <cmath>
|
|
#include <numeric>
|
|
#include <random>
|
|
#include <vector>
|
|
|
|
using namespace strata::ling32;
|
|
|
|
int main() {
|
|
int fail = 0, ncase = 0;
|
|
std::mt19937 g(11);
|
|
for (int V : {12, 100, 512, 1000, 5000, 157184}) {
|
|
for (int K : {1, 2, 5, 8, 16, 64}) {
|
|
if (K > V) continue;
|
|
for (int mode = 0; mode < 3; ++mode) { // 0: random normal, 1: many exact ties, 2: negative values with ties
|
|
const int rows = 3;
|
|
std::vector<float> x(static_cast<size_t>(rows) * V);
|
|
std::normal_distribution<float> nd(0.f, 3.f);
|
|
for (auto& v : x) {
|
|
v = nd(g);
|
|
if (mode >= 1) v = std::round(v * 2.0f) * 0.5f;
|
|
if (mode == 2) v = -std::fabs(v);
|
|
v += 0.0f; // -0 becomes +0 (the kernel orders -0 below +0 by their keys, the host sort calls them equal)
|
|
}
|
|
float* dx = nullptr; float* dv = nullptr; int* di = nullptr;
|
|
cudaMalloc(&dx, x.size() * 4);
|
|
cudaMalloc(&dv, static_cast<size_t>(rows) * K * 4);
|
|
cudaMalloc(&di, static_cast<size_t>(rows) * K * 4);
|
|
cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice);
|
|
gpu::topk_rows(dx, rows, V, V, K, dv, di, 0);
|
|
cudaDeviceSynchronize();
|
|
std::vector<float> ov(static_cast<size_t>(rows) * K);
|
|
std::vector<int> oi(static_cast<size_t>(rows) * K);
|
|
cudaMemcpy(ov.data(), dv, ov.size() * 4, cudaMemcpyDeviceToHost);
|
|
cudaMemcpy(oi.data(), di, oi.size() * 4, cudaMemcpyDeviceToHost);
|
|
bool ok = true;
|
|
for (int r = 0; r < rows && ok; ++r) {
|
|
std::vector<int> idx(V);
|
|
std::iota(idx.begin(), idx.end(), 0);
|
|
const float* row = x.data() + static_cast<size_t>(r) * V;
|
|
std::stable_sort(idx.begin(), idx.end(), [&](int a, int b) { return row[a] > row[b]; }); // value descending, ties lower index first
|
|
for (int k = 0; k < K; ++k)
|
|
if (oi[static_cast<size_t>(r) * K + k] != idx[k] || ov[static_cast<size_t>(r) * K + k] != row[idx[k]]) {
|
|
if (ok) std::printf(" mismatch V=%d K=%d mode=%d row %d rank %d: got id %d val %g, want id %d val %g\n", V, K, mode, r, k, oi[static_cast<size_t>(r) * K + k], ov[static_cast<size_t>(r) * K + k], idx[k], row[idx[k]]);
|
|
ok = false;
|
|
break;
|
|
}
|
|
}
|
|
++ncase;
|
|
if (!ok) ++fail;
|
|
cudaFree(dx); cudaFree(dv); cudaFree(di);
|
|
}
|
|
}
|
|
}
|
|
std::printf("topk_rows: %d cases, %d failed\n%s\n", ncase, fail, fail ? "FAIL" : "PASS");
|
|
return fail ? 1 : 0;
|
|
}
|