Prototype selective CUDA staging for KAR rows

This commit is contained in:
Pavlo Ratushnyi
2026-10-03 10:21:06 +02:00
parent a0c4e7c311
commit fc36acdba5
4 changed files with 284 additions and 0 deletions
+265
View File
@@ -0,0 +1,265 @@
#include "libkar.h"
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
namespace {
bool cuda_ok(cudaError_t status, const char* where) {
if (status == cudaSuccess) return true;
std::fprintf(stderr, "%s: %s\n", where, cudaGetErrorString(status));
return false;
}
bool kar_ok(kar_status status, const char* where) {
if (status == KAR_OK) return true;
std::fprintf(stderr, "%s: %s: %s\n", where, kar_strerror(status), kar_last_error());
return false;
}
bool parse_u32(const char* text, uint32_t& value) {
if (!text || !*text || *text == '-') return false;
char* end = nullptr;
errno = 0;
const auto parsed = std::strtoul(text, &end, 10);
if (errno || *end || parsed > std::numeric_limits<uint32_t>::max()) return false;
value = static_cast<uint32_t>(parsed);
return true;
}
bool within(uint64_t offset, uint64_t size, uint64_t file_size) {
return offset <= file_size && size <= file_size - offset;
}
uint64_t align4(uint64_t n) { return (n + 3u) & ~uint64_t{3}; }
uint64_t fnv1a64(const float* values, size_t count) {
auto hash = uint64_t{0xcbf29ce484222325};
const auto* bytes = reinterpret_cast<const unsigned char*>(values);
for (size_t i = 0; i < count * sizeof(float); ++i)
hash = (hash ^ bytes[i]) * uint64_t{0x100000001b3};
return hash;
}
float median(std::vector<float>& values) {
std::sort(values.begin(), values.end());
return values[values.size() / 2];
}
// One output word comes from one compact scale and one word from each plane.
// The source tensor's distant row addresses were resolved on the host.
__global__ void sparse_decode(const uint8_t* packet, float* output,
uint32_t words, uint32_t level,
uint32_t scale_offset, uint32_t plane_offset) {
const uint32_t word = blockIdx.x * blockDim.x + threadIdx.x;
if (word >= words) return;
const auto* book = reinterpret_cast<const __half*>(packet);
const auto* scales = reinterpret_cast<const __half*>(packet + scale_offset);
const auto* planes = reinterpret_cast<const uint32_t*>(packet + plane_offset);
const float scale = __half2float(scales[word]);
uint32_t bits[8];
for (uint32_t p = 0; p < level; ++p) bits[p] = planes[p * words + word];
for (uint32_t bit = 0; bit < 32; ++bit) {
uint32_t index = 0;
for (uint32_t p = 0; p < level; ++p)
index = (index << 1) | ((bits[p] >> bit) & 1u);
output[uint64_t(word) * 32 + bit] = __half2float(book[index]) * scale;
}
}
struct MappedFile {
int fd = -1;
const uint8_t* data = nullptr;
size_t size = 0;
~MappedFile() {
if (data) munmap(const_cast<uint8_t*>(data), size);
if (fd >= 0) close(fd);
}
bool open_read(const char* path) {
fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return false;
struct stat info {};
if (fstat(fd, &info) || info.st_size <= 0) return false;
size = static_cast<size_t>(info.st_size);
void* mapped = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapped == MAP_FAILED) return false;
data = static_cast<const uint8_t*>(mapped);
return true;
}
};
} // namespace
int main(int argc, char** argv) {
if (argc < 6) {
std::fprintf(stderr, "usage: strata-kar-sparse-row-smoke ARCHIVE.kar TENSOR LEVEL ITERATIONS ROW_ID [ROW_ID ...]\n");
return 2;
}
uint32_t level = 0, iterations = 0;
if (!parse_u32(argv[3], level) || !parse_u32(argv[4], iterations) ||
level < 1 || level > 8 || iterations < 1 || iterations > 1000 || argc - 5 > 128) {
std::fprintf(stderr, "level must be 1..8, iterations 1..1000, rows 1..128\n");
return 2;
}
std::vector<uint32_t> row_ids;
for (int i = 5; i < argc; ++i) {
uint32_t row = 0;
if (!parse_u32(argv[i], row)) return 2;
row_ids.push_back(row);
}
kar_archive* raw = nullptr;
if (!kar_ok(kar_open(argv[1], KAR_OPEN_VERIFY_PAYLOAD, &raw), "kar_open")) return 1;
std::unique_ptr<kar_archive, decltype(&kar_close)> archive(raw, kar_close);
const int index = kar_find(archive.get(), argv[2]);
if (index < 0) {
std::fprintf(stderr, "tensor not found\n");
return 1;
}
const kar_tensor_info* tensor = kar_tensor(archive.get(), static_cast<uint32_t>(index));
if (tensor->storage_class != KAR_NESTED || tensor->row_words == 0 ||
tensor->group < 32 || tensor->group % 32 ||
level < tensor->planes_min || level > tensor->planes_max) {
std::fprintf(stderr, "record is not a supported compressed row tensor at this level\n");
return 1;
}
for (uint32_t row : row_ids)
if (uint64_t(row) >= tensor->row_count) {
std::fprintf(stderr, "row ID exceeds record bounds\n");
return 1;
}
const uint64_t word_count64 = uint64_t(row_ids.size()) * tensor->row_words;
const uint64_t value_count64 = word_count64 * 32;
if (word_count64 == 0 || word_count64 > 1'000'000 || value_count64 > 100'000'000) return 1;
const auto words = static_cast<uint32_t>(word_count64);
const auto values = static_cast<size_t>(value_count64);
const uint64_t book_bytes = uint64_t{1} << level;
const uint64_t book_size = book_bytes * 2;
const uint64_t scale_offset64 = book_size;
const uint64_t plane_offset64 = align4(scale_offset64 + word_count64 * 2);
const uint64_t packet_bytes64 = plane_offset64 + word_count64 * level * 4;
if (packet_bytes64 > std::numeric_limits<uint32_t>::max()) return 1;
const auto packet_bytes = static_cast<size_t>(packet_bytes64);
const auto scale_offset = static_cast<uint32_t>(scale_offset64);
const auto plane_offset = static_cast<uint32_t>(plane_offset64);
MappedFile file;
if (!file.open_read(argv[1]) || file.size != kar_info(archive.get())->archive_bytes) {
std::fprintf(stderr, "cannot map verified archive at its expected length\n");
return 1;
}
const uint64_t book_source = tensor->books_offset + ((uint64_t{1} << level) - 2u) * 2u;
if (!within(book_source, book_size, file.size)) return 1;
std::vector<uint8_t> packet(packet_bytes, 0);
std::memcpy(packet.data(), file.data + book_source, book_size);
for (size_t row_position = 0; row_position < row_ids.size(); ++row_position) {
const uint64_t first_word = uint64_t(row_ids[row_position]) * tensor->row_words;
for (uint32_t col = 0; col < tensor->row_words; ++col) {
const uint64_t source_word = first_word + col;
const uint64_t packed_word = uint64_t(row_position) * tensor->row_words + col;
const uint64_t scale_source = tensor->scales_offset +
(source_word / (tensor->group / 32)) * 2;
if (!within(scale_source, 2, file.size)) return 1;
std::memcpy(packet.data() + scale_offset + packed_word * 2,
file.data + scale_source, 2);
for (uint32_t plane = 0; plane < level; ++plane) {
const uint64_t word_source = tensor->planes_offset +
uint64_t(plane) * tensor->plane_stride_bytes + source_word * 4;
if (!within(word_source, 4, file.size)) return 1;
const uint64_t packed_offset = plane_offset +
(uint64_t(plane) * word_count64 + packed_word) * 4;
std::memcpy(packet.data() + packed_offset, file.data + word_source, 4);
}
}
}
size_t free_bytes = 0, total_bytes = 0;
if (!cuda_ok(cudaMemGetInfo(&free_bytes, &total_bytes), "cudaMemGetInfo")) return 1;
const uint64_t headroom = std::max<uint64_t>(512ull << 20, total_bytes / 16);
const uint64_t needed = packet_bytes64 + value_count64 * sizeof(float);
if (free_bytes <= headroom || needed > free_bytes - headroom) {
std::fprintf(stderr, "insufficient GPU memory for sparse row smoke\n");
return 1;
}
uint8_t* pinned = nullptr;
uint8_t* device_packet = nullptr;
float* device_output = nullptr;
cudaStream_t stream = nullptr;
cudaEvent_t start = nullptr, middle = nullptr, stop = nullptr;
int result = 1;
do {
if (!cuda_ok(cudaHostAlloc(&pinned, packet_bytes, cudaHostAllocDefault), "cudaHostAlloc") ||
!cuda_ok(cudaMalloc(&device_packet, packet_bytes), "cudaMalloc packet") ||
!cuda_ok(cudaMalloc(&device_output, values * sizeof(float)), "cudaMalloc output") ||
!cuda_ok(cudaStreamCreate(&stream), "cudaStreamCreate") ||
!cuda_ok(cudaEventCreate(&start), "cudaEventCreate start") ||
!cuda_ok(cudaEventCreate(&middle), "cudaEventCreate middle") ||
!cuda_ok(cudaEventCreate(&stop), "cudaEventCreate stop")) break;
std::memcpy(pinned, packet.data(), packet_bytes);
std::vector<float> transfers, decodes;
transfers.reserve(iterations);
decodes.reserve(iterations);
bool failed = false;
for (uint32_t repeat = 0; repeat <= iterations; ++repeat) {
if (!cuda_ok(cudaEventRecord(start, stream), "event start") ||
!cuda_ok(cudaMemcpyAsync(device_packet, pinned, packet_bytes,
cudaMemcpyHostToDevice, stream), "row packet transfer") ||
!cuda_ok(cudaEventRecord(middle, stream), "event middle")) { failed = true; break; }
sparse_decode<<<(words + 255) / 256, 256, 0, stream>>>(
device_packet, device_output, words, level, scale_offset, plane_offset);
if (!cuda_ok(cudaGetLastError(), "sparse decode launch") ||
!cuda_ok(cudaEventRecord(stop, stream), "event stop") ||
!cuda_ok(cudaEventSynchronize(stop), "event synchronize")) { failed = true; break; }
if (repeat) {
float transfer = 0, decode = 0;
if (!cuda_ok(cudaEventElapsedTime(&transfer, start, middle), "transfer elapsed") ||
!cuda_ok(cudaEventElapsedTime(&decode, middle, stop), "decode elapsed")) {
failed = true; break;
}
transfers.push_back(transfer);
decodes.push_back(decode);
}
}
if (failed) break;
std::vector<float> host(values);
if (!cuda_ok(cudaMemcpy(host.data(), device_output, values * sizeof(float),
cudaMemcpyDeviceToHost), "copy output")) break;
const auto full_prefix = kar_decode_rows_cost(archive.get(), static_cast<uint32_t>(index),
level, row_ids.size()).resident_bytes;
std::printf("tensor=%s level=%u rows=%zu row_len=%u output_values=%zu\n",
argv[2], level, row_ids.size(), tensor->row_len, values);
std::printf("sparse_packet_bytes=%zu full_prefix_bytes=%llu iterations=%u\n",
packet_bytes, static_cast<unsigned long long>(full_prefix), iterations);
std::printf("transfer_median_ms=%.9g decode_median_ms=%.9g\n",
median(transfers), median(decodes));
std::printf("output_fnv1a64=%llx first=%.9g last=%.9g\n",
static_cast<unsigned long long>(fnv1a64(host.data(), host.size())),
host.front(), host.back());
for (size_t row = 0; row < row_ids.size(); ++row)
std::printf("row_id=%u row_fnv1a64=%llx\n", row_ids[row],
static_cast<unsigned long long>(fnv1a64(
host.data() + row * tensor->row_len, tensor->row_len)));
result = 0;
} while (false);
if (stop) cudaEventDestroy(stop);
if (middle) cudaEventDestroy(middle);
if (start) cudaEventDestroy(start);
if (stream) cudaStreamDestroy(stream);
if (device_output) cudaFree(device_output);
if (device_packet) cudaFree(device_packet);
if (pinned) cudaFreeHost(pinned);
return result;
}