Files
leleka/gpu/kar/src/kar_ple_cache.cu
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

301 lines
13 KiB
Plaintext

#include "kar_ple_cache.hpp"
#include <cuda_fp16.h>
#include <algorithm>
#include <cstring>
#include <iterator>
#include <list>
#include <mutex>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace strata::kar {
namespace {
constexpr uint32_t kRowValues = 160;
constexpr uint32_t kWords = 5;
constexpr uint32_t kLevel = 2;
constexpr uint32_t kScaleBytes = kWords * 2;
constexpr uint32_t kPlaneBytes = kWords * 4;
constexpr uint32_t kRowBytes = kScaleBytes + kLevel * kPlaneBytes;
constexpr uint32_t kSlotBytes = 64;
struct Update {
uint32_t slot;
uint8_t bytes[kRowBytes];
uint16_t part;
};
static_assert(sizeof(Update) == 56);
bool inside(uint64_t offset, uint64_t size, uint64_t total) {
return offset <= total && size <= total - offset;
}
bool cuda_ok(cudaError_t status, const char* where, std::string& err) {
if (status == cudaSuccess) return true;
err = std::string(where) + ": " + cudaGetErrorString(status);
return false;
}
__global__ void scatter_updates(uint8_t* cache, const Update* updates, uint32_t count) {
const uint32_t i = blockIdx.x;
const uint32_t byte = threadIdx.x;
if (i >= count) return;
if (byte < kRowBytes)
cache[uint64_t(updates[i].slot) * kSlotBytes + byte] = updates[i].bytes[byte];
if (byte < 2)
cache[uint64_t(updates[i].slot) * kSlotBytes + kRowBytes + byte] =
uint8_t(updates[i].part >> (byte * 8));
}
__global__ void decode_rows(const uint8_t* cache, const uint32_t* slots,
const uint16_t* books, float* output, uint32_t count) {
const uint32_t row = blockIdx.x;
const uint32_t value = threadIdx.x;
if (row >= count || value >= kRowValues) return;
const uint8_t* source = cache + uint64_t(slots[row]) * kSlotBytes;
const uint32_t word = value / 32;
const uint32_t bit = value % 32;
const uint16_t scale_bits = uint16_t(source[word * 2]) |
(uint16_t(source[word * 2 + 1]) << 8);
const uint16_t part = uint16_t(source[kRowBytes]) |
(uint16_t(source[kRowBytes + 1]) << 8);
uint32_t p0 = 0, p1 = 0;
memcpy(&p0, source + kScaleBytes + word * 4, 4);
memcpy(&p1, source + kScaleBytes + kPlaneBytes + word * 4, 4);
const uint32_t code = (((p0 >> bit) & 1u) << 1) | ((p1 >> bit) & 1u);
output[uint64_t(row) * kRowValues + value] =
__half2float(__ushort_as_half(books[uint32_t(part) * 4 + code])) *
__half2float(__ushort_as_half(scale_bits));
}
struct Entry {
uint32_t slot;
std::list<uint32_t>::iterator age;
};
} // namespace
struct PleRowCache::Impl {
const uint8_t* archive = nullptr;
size_t archive_bytes = 0;
std::vector<PlePart> parts;
uint32_t slot_count = 0;
uint32_t max_rows = 0;
uint32_t next_slot = 0;
std::list<uint32_t> recent;
std::unordered_map<uint32_t, Entry> entries;
PleCacheStats counters;
mutable std::mutex mutex;
bool pending = false;
bool failed = false;
cudaEvent_t finished = nullptr;
uint8_t* device_cache = nullptr;
Update* device_updates = nullptr;
uint32_t* device_slots = nullptr;
uint16_t* device_books = nullptr;
Update* host_updates = nullptr;
uint32_t* host_slots = nullptr;
~Impl() {
if (pending) cudaEventSynchronize(finished);
if (finished) cudaEventDestroy(finished);
if (device_books) cudaFree(device_books);
if (device_slots) cudaFree(device_slots);
if (device_updates) cudaFree(device_updates);
if (device_cache) cudaFree(device_cache);
if (host_slots) cudaFreeHost(host_slots);
if (host_updates) cudaFreeHost(host_updates);
}
uint32_t admit(uint32_t row) {
uint32_t slot;
if (next_slot < slot_count) {
slot = next_slot++;
} else {
const uint32_t victim = recent.back();
slot = entries.at(victim).slot;
entries.erase(victim);
recent.pop_back();
}
recent.push_front(row);
entries.emplace(row, Entry{slot, recent.begin()});
return slot;
}
bool pack(Update& update, uint32_t row, std::string& err) const {
const auto it = std::upper_bound(parts.begin(), parts.end(), uint64_t(row),
[](uint64_t wanted, const PlePart& part) { return wanted < part.row_base; });
if (it == parts.begin()) { err = "PLE row is before the first KAR part"; return false; }
const auto part = std::prev(it);
const uint64_t local = uint64_t(row) - part->row_base;
const kar_tensor_info* t = part->tensor;
if (local >= t->row_count) { err = "PLE row is outside the KAR parts"; return false; }
const uint64_t scale = t->scales_offset + local * kScaleBytes;
if (!inside(scale, kScaleBytes, archive_bytes)) { err = "PLE scale is outside the archive"; return false; }
std::memcpy(update.bytes, archive + scale, kScaleBytes);
for (uint32_t plane = 0; plane < kLevel; ++plane) {
const uint64_t offset = t->planes_offset + uint64_t(plane) * t->plane_stride_bytes +
local * kPlaneBytes;
if (!inside(offset, kPlaneBytes, archive_bytes)) {
err = "PLE plane is outside the archive"; return false;
}
std::memcpy(update.bytes + kScaleBytes + plane * kPlaneBytes,
archive + offset, kPlaneBytes);
}
update.part = uint16_t(part - parts.begin());
return true;
}
};
PleRowCache::PleRowCache() = default;
PleRowCache::~PleRowCache() = default;
bool PleRowCache::open(const uint8_t* archive_map, size_t archive_bytes,
const std::vector<PlePart>& parts, uint32_t cache_mib,
uint32_t max_batch_rows, std::string& err) {
close();
if (!archive_map || !archive_bytes || parts.empty() || parts.size() > 65535 ||
cache_mib < 1 || cache_mib > 1024 || max_batch_rows < 1 || max_batch_rows > 65536) {
err = "invalid KAR PLE cache geometry or budget"; return false;
}
uint64_t end = 0;
std::vector<uint16_t> books(parts.size() * 4);
for (size_t i = 0; i < parts.size(); ++i) {
const auto& part = parts[i];
const kar_tensor_info* t = part.tensor;
if (!t || part.row_base != end || t->row_count == 0 ||
t->row_count > uint64_t(UINT32_MAX) + 1 - end ||
t->storage_class != KAR_NESTED || t->source_dtype != KAR_F32 ||
t->nesting != KAR_TOPDOWN || t->group != 32 ||
t->row_len != kRowValues || t->row_words != kWords ||
t->planes_min > kLevel || t->planes_max < kLevel ||
!inside(t->books_offset, 12, archive_bytes)) {
err = "KAR PLE part does not have contiguous level-2 group-32 rows";
return false;
}
std::memcpy(books.data() + i * 4, archive_map + t->books_offset + 4, 8);
end += t->row_count;
}
auto next = std::make_unique<Impl>();
next->archive = archive_map;
next->archive_bytes = archive_bytes;
next->parts = parts;
next->slot_count = uint32_t(std::min<uint64_t>((uint64_t(cache_mib) << 20) / kSlotBytes, end));
next->max_rows = max_batch_rows;
if (next->slot_count == 0) { err = "KAR PLE cache has no slots"; return false; }
const uint64_t needed = uint64_t(next->slot_count) * kSlotBytes +
uint64_t(max_batch_rows) * (sizeof(Update) + sizeof(uint32_t)) + books.size() * 2;
size_t free_bytes = 0, total_bytes = 0;
if (!cuda_ok(cudaMemGetInfo(&free_bytes, &total_bytes), "PLE cache VRAM query", err)) return false;
const uint64_t headroom = std::max<uint64_t>(512ull << 20, total_bytes / 16);
if (free_bytes <= headroom || needed > free_bytes - headroom) {
err = "insufficient VRAM for PLE cache and required headroom"; return false;
}
if (!cuda_ok(cudaMalloc(&next->device_cache, uint64_t(next->slot_count) * kSlotBytes), "PLE cache allocation", err) ||
!cuda_ok(cudaMalloc(&next->device_updates, uint64_t(max_batch_rows) * sizeof(Update)), "PLE update allocation", err) ||
!cuda_ok(cudaMalloc(&next->device_slots, uint64_t(max_batch_rows) * sizeof(uint32_t)), "PLE slot allocation", err) ||
!cuda_ok(cudaMalloc(&next->device_books, books.size() * 2), "PLE book allocation", err) ||
!cuda_ok(cudaHostAlloc(reinterpret_cast<void**>(&next->host_updates), uint64_t(max_batch_rows) * sizeof(Update), cudaHostAllocDefault), "PLE pinned update allocation", err) ||
!cuda_ok(cudaHostAlloc(reinterpret_cast<void**>(&next->host_slots), uint64_t(max_batch_rows) * sizeof(uint32_t), cudaHostAllocDefault), "PLE pinned slot allocation", err) ||
!cuda_ok(cudaEventCreateWithFlags(&next->finished, cudaEventDisableTiming), "PLE event allocation", err) ||
!cuda_ok(cudaMemcpy(next->device_books, books.data(), books.size() * 2, cudaMemcpyHostToDevice), "PLE book upload", err))
return false;
impl_ = std::move(next);
return true;
}
bool PleRowCache::enqueue(const uint32_t* rows, size_t count, float* device_output,
cudaStream_t stream, std::string& err) {
if (!impl_) { err = "KAR PLE cache is not open"; return false; }
Impl& cache = *impl_;
std::lock_guard<std::mutex> guard(cache.mutex);
if (cache.failed) { err = "KAR PLE cache previously failed; reopen it"; return false; }
if (!rows || !device_output || !count || count > cache.max_rows) {
err = "invalid KAR PLE row batch"; return false;
}
const uint64_t total_rows = cache.parts.back().row_base + cache.parts.back().tensor->row_count;
for (size_t i = 0; i < count; ++i) {
if (uint64_t(rows[i]) >= total_rows) {
err = "KAR PLE row is outside the table"; return false;
}
}
// The common path has fewer accesses than slots, so it cannot overflow
// even if every ID differs. Avoid building a second hash table per token.
if (count > cache.slot_count) {
std::unordered_set<uint32_t> distinct(rows, rows + count);
if (distinct.size() > cache.slot_count) {
err = "KAR PLE batch has more distinct rows than cache slots"; return false;
}
}
// The earlier decode must finish before its slots or pinned H2D buffers
// can be reused. This also allows callers to alternate CUDA streams.
if (cache.pending) {
if (!cuda_ok(cudaEventSynchronize(cache.finished), "PLE previous batch", err)) {
cache.failed = true; return false;
}
cache.pending = false;
}
uint32_t updates = 0;
for (size_t i = 0; i < count; ++i) {
uint32_t slot = 0;
const auto found = cache.entries.find(rows[i]);
if (found != cache.entries.end()) {
slot = found->second.slot;
cache.recent.splice(cache.recent.begin(), cache.recent, found->second.age);
++cache.counters.hits;
} else {
slot = cache.admit(rows[i]);
Update& update = cache.host_updates[updates];
update.slot = slot;
if (!cache.pack(update, rows[i], err)) {
cache.failed = true; return false;
}
++updates;
++cache.counters.misses;
}
cache.host_slots[i] = slot;
}
cache.counters.compressed_bytes += uint64_t(updates) * kRowBytes;
cache.counters.host_to_device_bytes += uint64_t(updates) * sizeof(Update) + count * sizeof(uint32_t);
auto fail_async = [&] {
cache.failed = true;
// A previous H2D copy in this call may already be queued. Preserve
// the pinned source and device buffers until that stream is done.
cudaStreamSynchronize(stream);
return false;
};
if ((updates && !cuda_ok(cudaMemcpyAsync(cache.device_updates, cache.host_updates,
uint64_t(updates) * sizeof(Update), cudaMemcpyHostToDevice, stream), "PLE update upload", err)) ||
!cuda_ok(cudaMemcpyAsync(cache.device_slots, cache.host_slots,
count * sizeof(uint32_t), cudaMemcpyHostToDevice, stream), "PLE slot upload", err)) {
return fail_async();
}
if (updates) {
scatter_updates<<<updates, 64, 0, stream>>>(cache.device_cache, cache.device_updates, updates);
if (!cuda_ok(cudaGetLastError(), "PLE scatter", err)) return fail_async();
}
decode_rows<<<uint32_t(count), 256, 0, stream>>>(cache.device_cache, cache.device_slots,
cache.device_books, device_output, uint32_t(count));
if (!cuda_ok(cudaGetLastError(), "PLE decode", err) ||
!cuda_ok(cudaEventRecord(cache.finished, stream), "PLE completion event", err)) {
return fail_async();
}
cache.pending = true;
return true;
}
void PleRowCache::close() { impl_.reset(); }
PleCacheStats PleRowCache::stats() const {
if (!impl_) return {};
std::lock_guard<std::mutex> guard(impl_->mutex);
return impl_->counters;
}
uint32_t PleRowCache::slots() const { return impl_ ? impl_->slot_count : 0; }
} // namespace strata::kar