Files
leleka/gpu/kar/vendor/libkar.h
T
Pavlo Ratushnyi 4013e0c9bd
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
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
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

187 lines
9.7 KiB
C

/* libkar - the KAR-2 archive reader and GPU decompressor, as a library.
*
* WHAT THIS IS FOR. r08/code/kar_decode.cu proved one kernel on one tensor of one shape read
* out of a KAR-1 file. A runtime needs three things that program does not have: a reader for
* the committed container (r08/docs/format-kar-v2.md), a decode entry point that covers every
* tensor class a real model contains, and a way for a scheduler to price a decode BEFORE it
* issues one. Those are the three halves of this surface.
*
* THE CONTRACT IN ONE PARAGRAPH. kar_open maps an archive and parses its directory, rejecting
* per section 9 of the format. kar_reserve copies one tensor's level-k prefix into VRAM - that
* is the only moment anything crosses PCIe. kar_decode then reconstructs a resident tensor into
* a caller-owned fp32 buffer on a caller-chosen stream, touching no host memory and no tensor
* core. kar_decode_cost answers what that would cost without doing it.
*
* WHAT IT GUARANTEES, AND WHAT IT DOES NOT: r08/docs/libkar-notes.md, which is the prose half of
* this header and states the assumptions behind the cost model as assumptions.
*/
#ifndef LIBKAR_H
#define LIBKAR_H
#include <cuda_runtime.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ------------------------------------------------------------------ status */
typedef enum {
KAR_OK = 0,
KAR_E_IO, /* the file could not be opened, sized or mapped */
KAR_E_FORMAT, /* a section 9 reject rule fired; kar_last_error names it */
KAR_E_RANGE, /* an index, a level or a row id was outside its declared range */
KAR_E_STATE, /* the tensor is not resident at the level asked for */
KAR_E_CUDA, /* a CUDA call failed; kar_last_error carries its text */
KAR_E_UNSUPPORTED /* legal in the format, not implemented here */
} kar_status;
/* Mirrors of the format's enumerations, so a caller never hardcodes a magic number. */
typedef enum { KAR_NESTED = 0, KAR_RAW = 1 } kar_storage_class;
typedef enum { KAR_F32 = 0, KAR_F16 = 1, KAR_BF16 = 2 } kar_source_dtype;
typedef enum { KAR_TOPDOWN = 0, KAR_BOTTOMUP = 1 } kar_nesting;
/* kar_open flags. */
#define KAR_OPEN_DEFAULT 0u
#define KAR_OPEN_SKIP_DIGEST 1u /* skip H12; the directory SHA-256 is a few microseconds */
#define KAR_OPEN_VERIFY_PAYLOAD 2u /* check every D8 payload CRC-32: a full pass over the file */
/* --------------------------------------------------------------- structures */
/* One directory record, in the format's field names. dims are in ggml order, dims[0] fastest. */
typedef struct {
const char *name;
uint64_t dims[4];
uint64_t n_elements, n_padded, n_groups, words;
uint64_t section_offset, section_bytes;
uint64_t scales_offset, books_offset, planes_offset, scales_bytes, books_bytes;
uint32_t plane_stride_bytes, payload_crc32;
uint32_t n_dims, group, planes_stored, planes_min, planes_max;
uint32_t storage_class, source_dtype, nesting, element_order;
uint32_t row_len; /* dims[0]: the addressable granule of a gather table */
uint32_t row_words; /* row_len/32, valid only when row_len is a multiple of 32 */
uint64_t row_count; /* n_elements/row_len */
} kar_tensor_info;
/* Whole-archive facts a scheduler wants without walking the directory. */
typedef struct {
uint64_t archive_bytes, total_elements, source_total_elements, payload_bits;
double accounted_bpw;
uint32_t tensor_count, global_planes_min, global_planes_max;
} kar_archive_info;
/* The machine the cost model prices against. Every field is a MEASUREMENT, not a spec figure;
* kar_measure_machine fills one in, and libkar_bench prints the one it measured. */
typedef struct {
double dram_bytes_per_s; /* streaming read+write far outside L2 */
double l2_bytes_per_s; /* the same stream when the whole working set fits in L2 */
double launch_seconds; /* fixed cost of one kernel launch on a busy stream */
uint64_t l2_bytes; /* cudaDeviceProp::l2CacheSize */
uint32_t dram_sector_bytes;/* granularity a scattered read is actually charged at */
double decode_efficiency; /* measured: what fraction of the streaming ceiling a decode
* reaches. A decode is not a memcpy - it reads two streams of
* different widths and writes a third - and this factor is the
* honest name for that gap rather than a fudge inside the
* bandwidth. libkar-notes.md records how it was obtained. */
} kar_machine;
/* What one decode would cost. est_seconds is a PREDICTION from kar_machine, never a timing. */
typedef struct {
uint64_t plane_bytes; /* coded bytes the kernel reads from VRAM */
uint64_t output_bytes; /* fp32 bytes it writes */
uint64_t resident_bytes; /* VRAM the level-k prefix occupies */
uint64_t stage_bytes; /* host->device bytes still owed; 0 once reserved */
double est_seconds;
double est_gweights_per_s;
uint64_t weights; /* elements the call produces */
} kar_cost;
typedef struct kar_archive kar_archive;
/* -------------------------------------------------------------------- opening */
kar_status kar_open(const char *path, uint32_t flags, kar_archive **out);
void kar_close(kar_archive *a);
const kar_archive_info *kar_info(const kar_archive *a);
uint32_t kar_tensor_count(const kar_archive *a);
const kar_tensor_info *kar_tensor(const kar_archive *a, uint32_t index);
int kar_find(const kar_archive *a, const char *name); /* index, or -1 */
/* ----------------------------------------------------------------- residency */
/* Copy tensor `index`'s level-k prefix into VRAM. This is the ONLY call that touches the bus.
* Asking for more planes than are already resident re-stages; asking for fewer is a no-op. */
kar_status kar_reserve(kar_archive *a, uint32_t index, uint32_t planes, cudaStream_t s);
kar_status kar_release(kar_archive *a, uint32_t index);
/* Measurement hook, not a runtime path. Stages the prefix `pad` bytes into its allocation so the
* cost of the format's 16-byte alignment floor can be measured with the PRODUCTION kernel rather
* than a copy of it. pad must be a multiple of 16. */
kar_status kar_reserve_shifted(kar_archive *a, uint32_t index, uint32_t planes, uint32_t pad,
cudaStream_t s);
uint32_t kar_resident_planes(const kar_archive *a, uint32_t index);
uint64_t kar_resident_bytes(const kar_archive *a);
/* -------------------------------------------------------------------- decode */
/* Reconstruct the whole tensor at `planes` into `dst`, which must hold n_elements floats and be
* at least 16-byte aligned. RAW tensors ignore `planes` and are widened to fp32. */
kar_status kar_decode(kar_archive *a, uint32_t index, uint32_t planes, float *dst,
cudaStream_t s);
/* Reconstruct only the rows named by d_row_ids (a DEVICE array of n_rows row indices) into dst,
* which must hold n_rows*row_len floats. Requires row_len % 32 == 0. */
typedef struct {
uint32_t index, planes, n_rows;
const uint32_t *d_row_ids;
float *dst;
} kar_row_request;
kar_status kar_decode_rows(kar_archive *a, const kar_row_request *r, cudaStream_t s);
/* The fp16 output variant. It exists so that the cost of the fp32 output the runtime actually
* needs can be ATTRIBUTED rather than argued about; see libkar-notes.md. */
kar_status kar_decode_f16(kar_archive *a, uint32_t index, uint32_t planes, void *dst,
cudaStream_t s);
/* ------------------------------------------------------------------ kernel */
/* Two mappings of weights onto threads, both of which obey the three measured facts and differ
* only in how wide a slice one thread owns. WORD32 gives each thread one plane word - 32 weights
* - which makes the plane loads perfectly coalesced and the stores 128-byte strided. QUAD gives
* each thread exactly one 16-byte store, which makes the stores perfectly coalesced and the
* plane loads redundant across eight threads. Which one wins is a measurement, and libkar_bench
* prints both; see libkar-notes.md for the number on this card. */
typedef enum { KAR_KERNEL_WORD32 = 0, KAR_KERNEL_QUAD = 1 } kar_kernel_variant;
void kar_set_kernel(kar_kernel_variant v);
kar_kernel_variant kar_get_kernel(void);
/* --------------------------------------------------------------------- cost */
kar_cost kar_decode_cost(const kar_archive *a, uint32_t index, uint32_t planes);
kar_cost kar_decode_rows_cost(const kar_archive *a, uint32_t index, uint32_t planes,
uint64_t n_rows);
const kar_machine *kar_get_machine(void);
void kar_set_machine(const kar_machine *m);
/* Runs two trivial streaming kernels over a buffer far larger than L2 and one that fits in it,
* and installs the result as the cost model's machine. This is the only measuring call. */
kar_status kar_measure_machine(kar_machine *out);
/* ------------------------------------------------------------------- errors */
const char *kar_strerror(kar_status st);
const char *kar_last_error(void);
/* Supported reconstruction levels. The kernel is specialised per level at compile time, which is
* the first of the three things that bought the decoder its throughput, so this range is a
* compile-time fact of the library and not a runtime parameter. */
#define KAR_MIN_PLANES 1u
#define KAR_MAX_PLANES 8u
#ifdef __cplusplus
}
#endif
#endif /* LIBKAR_H */