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
901 lines
41 KiB
Plaintext
901 lines
41 KiB
Plaintext
/* libkar - implementation. See libkar.h for the surface and r08/docs/libkar-notes.md for the
|
|
* guarantees, the dispatch strategy and the assumptions behind the cost model.
|
|
*
|
|
* THE THREE MEASURED FACTS THIS FILE IS BUILT AROUND, none of which is negotiable. They took
|
|
* kar_decode.cu from 71 to 941 Gweights/s and every one of them is a structural property here:
|
|
*
|
|
* 1. LEVEL IS A TEMPLATE PARAMETER. kar_plane_kernel<LEVEL, OUT> is specialised for each
|
|
* supported plane count and the runtime level selects a specialisation at call time, so the
|
|
* unrolled inner loop does exactly LEVEL iterations rather than eight with seven predicated
|
|
* off. A runtime level inside that loop costs a factor of the ratio of levels.
|
|
* 2. THE OUTPUT IS WRITTEN AS 16-BYTE VECTORS. A thread owns 32 consecutive weights; at fp32
|
|
* that is 128 bytes at a 128-byte-aligned offset from the tensor origin, so it leaves as
|
|
* eight float4 stores rather than thirty-two scalar ones.
|
|
* 3. THE GROUP SCALE IS LOADED ONCE PER THREAD. The format makes `group` a multiple of 32 for
|
|
* exactly this reason, so a thread's 32 weights are always inside one group and the per
|
|
* weight integer division disappears. One division per 32 weights remains, because `group`
|
|
* need not be a power of two.
|
|
*
|
|
* WHAT CHANGED AGAINST kar_decode.cu, which is the reference and stays as delivered:
|
|
* - the loader reads KAR-2 through the directory instead of assuming KAR-1's packed layout;
|
|
* - the output is fp32, not fp16, because the card must multiply full 32-bit values;
|
|
* - the reconstruction multiply is done in fp32 rather than as __hmul, which makes the result
|
|
* bit-identical to kar_codec.decode instead of merely close to it.
|
|
*/
|
|
|
|
#include "libkar.h"
|
|
|
|
#include <cuda_fp16.h>
|
|
#include <errno.h>
|
|
#include <fcntl.h>
|
|
#include <math.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/mman.h>
|
|
#include <sys/stat.h>
|
|
#include <unistd.h>
|
|
|
|
/* ==================================================================== errors */
|
|
|
|
static __thread char g_err[512];
|
|
|
|
static kar_status kar_fail(kar_status st, const char *fmt, const char *a, long long b) {
|
|
snprintf(g_err, sizeof g_err, fmt, a, b);
|
|
return st;
|
|
}
|
|
|
|
const char *kar_last_error(void) { return g_err; }
|
|
|
|
const char *kar_strerror(kar_status st) {
|
|
switch (st) {
|
|
case KAR_OK: return "ok";
|
|
case KAR_E_IO: return "io";
|
|
case KAR_E_FORMAT: return "format";
|
|
case KAR_E_RANGE: return "range";
|
|
case KAR_E_STATE: return "state";
|
|
case KAR_E_CUDA: return "cuda";
|
|
case KAR_E_UNSUPPORTED: return "unsupported";
|
|
}
|
|
return "?";
|
|
}
|
|
|
|
#define KAR_REJECT(rule, what) \
|
|
kar_fail(KAR_E_FORMAT, "reject %s (%lld)", rule ": " what, 0LL)
|
|
#define KAR_REJECTN(rule, what, num) \
|
|
kar_fail(KAR_E_FORMAT, "reject %s (%lld)", rule ": " what, (long long)(num))
|
|
|
|
static kar_status kar_cuda_fail(cudaError_t e, const char *where) {
|
|
snprintf(g_err, sizeof g_err, "cuda %s: %s", where, cudaGetErrorString(e));
|
|
return KAR_E_CUDA;
|
|
}
|
|
|
|
#define KAR_CUDA(call, where) do { cudaError_t e_ = (call); \
|
|
if (e_ != cudaSuccess) return kar_cuda_fail(e_, where); } while (0)
|
|
|
|
/* ================================================= CRC-32 and SHA-256 (H5, H12) */
|
|
|
|
static uint32_t g_crc_tab[256];
|
|
static int g_crc_ready;
|
|
|
|
static void crc_init(void) {
|
|
for (uint32_t i = 0; i < 256; ++i) {
|
|
uint32_t c = i;
|
|
for (int k = 0; k < 8; ++k) c = (c & 1u) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
|
|
g_crc_tab[i] = c;
|
|
}
|
|
g_crc_ready = 1;
|
|
}
|
|
|
|
static uint32_t crc32_of(const uint8_t *p, size_t n) {
|
|
if (!g_crc_ready) crc_init();
|
|
uint32_t c = 0xFFFFFFFFu;
|
|
for (size_t i = 0; i < n; ++i) c = g_crc_tab[(c ^ p[i]) & 0xFFu] ^ (c >> 8);
|
|
return c ^ 0xFFFFFFFFu;
|
|
}
|
|
|
|
static const uint32_t SHA_K[64] = {
|
|
0x428a2f98u,0x71374491u,0xb5c0fbcfu,0xe9b5dba5u,0x3956c25bu,0x59f111f1u,0x923f82a4u,0xab1c5ed5u,
|
|
0xd807aa98u,0x12835b01u,0x243185beu,0x550c7dc3u,0x72be5d74u,0x80deb1feu,0x9bdc06a7u,0xc19bf174u,
|
|
0xe49b69c1u,0xefbe4786u,0x0fc19dc6u,0x240ca1ccu,0x2de92c6fu,0x4a7484aau,0x5cb0a9dcu,0x76f988dau,
|
|
0x983e5152u,0xa831c66du,0xb00327c8u,0xbf597fc7u,0xc6e00bf3u,0xd5a79147u,0x06ca6351u,0x14292967u,
|
|
0x27b70a85u,0x2e1b2138u,0x4d2c6dfcu,0x53380d13u,0x650a7354u,0x766a0abbu,0x81c2c92eu,0x92722c85u,
|
|
0xa2bfe8a1u,0xa81a664bu,0xc24b8b70u,0xc76c51a3u,0xd192e819u,0xd6990624u,0xf40e3585u,0x106aa070u,
|
|
0x19a4c116u,0x1e376c08u,0x2748774cu,0x34b0bcb5u,0x391c0cb3u,0x4ed8aa4au,0x5b9cca4fu,0x682e6ff3u,
|
|
0x748f82eeu,0x78a5636fu,0x84c87814u,0x8cc70208u,0x90befffau,0xa4506cebu,0xbef9a3f7u,0xc67178f2u
|
|
};
|
|
|
|
#define ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
|
|
|
|
static void sha_block(uint32_t *h, const uint8_t *p) {
|
|
uint32_t w[64], a, b, c, d, e, f, g, hh;
|
|
for (int i = 0; i < 16; ++i)
|
|
w[i] = ((uint32_t)p[4*i] << 24) | ((uint32_t)p[4*i+1] << 16) |
|
|
((uint32_t)p[4*i+2] << 8) | (uint32_t)p[4*i+3];
|
|
for (int i = 16; i < 64; ++i) {
|
|
uint32_t s0 = ROR(w[i-15], 7) ^ ROR(w[i-15], 18) ^ (w[i-15] >> 3);
|
|
uint32_t s1 = ROR(w[i-2], 17) ^ ROR(w[i-2], 19) ^ (w[i-2] >> 10);
|
|
w[i] = w[i-16] + s0 + w[i-7] + s1;
|
|
}
|
|
a = h[0]; b = h[1]; c = h[2]; d = h[3]; e = h[4]; f = h[5]; g = h[6]; hh = h[7];
|
|
for (int i = 0; i < 64; ++i) {
|
|
uint32_t t1 = hh + (ROR(e,6) ^ ROR(e,11) ^ ROR(e,25)) + ((e & f) ^ (~e & g)) + SHA_K[i] + w[i];
|
|
uint32_t t2 = (ROR(a,2) ^ ROR(a,13) ^ ROR(a,22)) + ((a & b) ^ (a & c) ^ (b & c));
|
|
hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
|
|
}
|
|
h[0]+=a; h[1]+=b; h[2]+=c; h[3]+=d; h[4]+=e; h[5]+=f; h[6]+=g; h[7]+=hh;
|
|
}
|
|
|
|
/* SHA-256 over two concatenated spans, which is the exact shape H12 asks for. */
|
|
static void sha256_pair(const uint8_t *p0, size_t n0, const uint8_t *p1, size_t n1,
|
|
uint8_t out[32]) {
|
|
uint32_t h[8] = {0x6a09e667u,0xbb67ae85u,0x3c6ef372u,0xa54ff53au,
|
|
0x510e527fu,0x9b05688cu,0x1f83d9abu,0x5be0cd19u};
|
|
uint8_t buf[64];
|
|
size_t fill = 0, total = n0 + n1;
|
|
const uint8_t *src[2] = {p0, p1};
|
|
size_t len[2] = {n0, n1};
|
|
for (int s = 0; s < 2; ++s)
|
|
for (size_t i = 0; i < len[s]; ++i) {
|
|
buf[fill++] = src[s][i];
|
|
if (fill == 64) { sha_block(h, buf); fill = 0; }
|
|
}
|
|
buf[fill++] = 0x80u;
|
|
if (fill > 56) { while (fill < 64) buf[fill++] = 0; sha_block(h, buf); fill = 0; }
|
|
while (fill < 56) buf[fill++] = 0;
|
|
uint64_t bits = (uint64_t)total * 8u;
|
|
for (int i = 7; i >= 0; --i) buf[fill++] = (uint8_t)(bits >> (i * 8));
|
|
sha_block(h, buf);
|
|
for (int i = 0; i < 8; ++i)
|
|
for (int k = 0; k < 4; ++k) out[i*4+k] = (uint8_t)(h[i] >> (24 - k*8));
|
|
}
|
|
|
|
/* ====================================================== little-endian readers */
|
|
|
|
static uint8_t rd8(const uint8_t *p, size_t o) { return p[o]; }
|
|
static uint16_t rd16(const uint8_t *p, size_t o) { uint16_t v; memcpy(&v, p + o, 2); return v; }
|
|
static uint32_t rd32(const uint8_t *p, size_t o) { uint32_t v; memcpy(&v, p + o, 4); return v; }
|
|
static uint64_t rd64(const uint8_t *p, size_t o) { uint64_t v; memcpy(&v, p + o, 8); return v; }
|
|
static double rdf64(const uint8_t *p, size_t o) { double v; memcpy(&v, p + o, 8); return v; }
|
|
|
|
static uint64_t round_up_u64(uint64_t x, uint64_t a) { return ((x + a - 1) / a) * a; }
|
|
|
|
/* ============================================================ archive object */
|
|
|
|
typedef struct {
|
|
void *d_base; /* one allocation holding the level-k prefix, 256-byte aligned */
|
|
uint64_t bytes;
|
|
uint32_t planes; /* levels actually staged; 0 when not resident */
|
|
uint32_t pad; /* bytes between the allocation base and section_offset */
|
|
} kar_residency;
|
|
|
|
struct kar_archive {
|
|
int fd;
|
|
const uint8_t *map;
|
|
size_t map_bytes;
|
|
kar_archive_info info;
|
|
kar_tensor_info *t;
|
|
kar_residency *res;
|
|
char *names; /* owned NUL-terminated copies, pointed at by kar_tensor_info */
|
|
uint64_t resident_bytes;
|
|
};
|
|
|
|
static kar_machine g_machine = {
|
|
/* Placeholders only. libkar_bench calls kar_measure_machine and prints what it got; any
|
|
* number quoted from a spec sheet would be a claim this library cannot support. The
|
|
* efficiency is the one number here that is NOT re-measured at runtime - it came off this
|
|
* card on 2026-09-12 over three tensors, six levels each, and it is a property of the
|
|
* kernel rather than of the memory system. */
|
|
1.0e12, 4.0e12, 4.0e-6, 32u << 20, 32u, 0.88
|
|
};
|
|
|
|
const kar_machine *kar_get_machine(void) { return &g_machine; }
|
|
void kar_set_machine(const kar_machine *m) { if (m) g_machine = *m; }
|
|
|
|
/* ===================================================== header parse (§9.1) */
|
|
|
|
static kar_status parse_header_fixed(const uint8_t *p, size_t size, kar_archive_info *info) {
|
|
if (size < 256) return KAR_REJECT("H4", "file shorter than the header");
|
|
if (memcmp(p, "KARCHIV2", 8) != 0) return KAR_REJECT("H1", "magic");
|
|
if (rd32(p, 8) != 2u) return KAR_REJECTN("H2", "format_version", rd32(p, 8));
|
|
if (rd32(p, 12) != 0x04030201u) return KAR_REJECT("H3", "endian_probe");
|
|
if (rd32(p, 16) != 256u || rd32(p, 20) != 192u) return KAR_REJECT("H4", "fixed sizes");
|
|
if (rd32(p, 192) != crc32_of(p, 192)) return KAR_REJECT("H5", "header_crc32");
|
|
if (rd64(p, 64) != (uint64_t)size) return KAR_REJECTN("H6", "archive_bytes", rd64(p, 64));
|
|
if (rd32(p, 36) != 0u) return KAR_REJECT("H16", "flags");
|
|
if (rd32(p, 32) == 0u) return KAR_REJECT("H15", "tensor_count");
|
|
if (rd8(p, 106) != 1u) return KAR_REJECT("H11", "digest_algorithm");
|
|
info->archive_bytes = rd64(p, 64);
|
|
info->tensor_count = rd32(p, 32);
|
|
info->total_elements = rd64(p, 72);
|
|
info->payload_bits = rd64(p, 80);
|
|
info->source_total_elements = rd64(p, 88);
|
|
info->accounted_bpw = rdf64(p, 96);
|
|
info->global_planes_min = rd8(p, 104);
|
|
info->global_planes_max = rd8(p, 105);
|
|
return KAR_OK;
|
|
}
|
|
|
|
static kar_status check_header_regions(const uint8_t *p, size_t size) {
|
|
uint64_t dir = rd64(p, 24), str = rd64(p, 40), sbytes = rd64(p, 48), pay = rd64(p, 56);
|
|
uint64_t dir_end = dir + (uint64_t)rd32(p, 32) * 192u;
|
|
if ((dir % 64u) || (str % 64u) || (pay % 256u)) return KAR_REJECT("H14", "alignment");
|
|
if (dir_end > size || str + sbytes > size || pay > size)
|
|
return KAR_REJECT("H14", "a region runs past archive_bytes");
|
|
if (rd64(p, 72) > rd64(p, 88)) return KAR_REJECT("H10", "total > source_total_elements");
|
|
double want = (double)size * 8.0 / (double)rd64(p, 72);
|
|
double got = rdf64(p, 96);
|
|
if (!(got > 0.0) || fabs(got - want) > want * 9.1e-13)
|
|
return KAR_REJECT("H7", "accounted_bpw disagrees with the file length");
|
|
return KAR_OK;
|
|
}
|
|
|
|
static kar_status check_directory_digest(const uint8_t *p) {
|
|
uint8_t got[32];
|
|
uint64_t str = rd64(p, 40), sbytes = rd64(p, 48), dir = rd64(p, 24);
|
|
sha256_pair(p + str, (size_t)sbytes, p + dir, (size_t)rd32(p, 32) * 192u, got);
|
|
if (memcmp(got, p + 160, 32) != 0) return KAR_REJECT("H12", "directory_digest");
|
|
return KAR_OK;
|
|
}
|
|
|
|
/* ==================================================== record parse (§9.2) */
|
|
|
|
static void record_fields(const uint8_t *r, kar_tensor_info *t) {
|
|
t->n_dims = rd8(r, 6);
|
|
t->storage_class = rd8(r, 7);
|
|
for (int i = 0; i < 4; ++i) t->dims[i] = rd64(r, 8 + 8 * i);
|
|
t->element_order = rd8(r, 40);
|
|
t->source_dtype = rd8(r, 41);
|
|
t->planes_stored = rd8(r, 42);
|
|
t->planes_min = rd8(r, 43);
|
|
t->planes_max = rd8(r, 44);
|
|
t->nesting = rd8(r, 45);
|
|
t->group = rd16(r, 46);
|
|
t->n_elements = rd64(r, 48);
|
|
t->n_padded = rd64(r, 56);
|
|
t->scales_offset = rd64(r, 64);
|
|
t->scales_bytes = rd64(r, 72);
|
|
t->books_offset = rd64(r, 80);
|
|
t->books_bytes = rd64(r, 88);
|
|
t->planes_offset = rd64(r, 96);
|
|
t->plane_stride_bytes = rd32(r, 104);
|
|
t->payload_crc32 = rd32(r, 108);
|
|
t->section_offset = rd64(r, 112);
|
|
t->section_bytes = rd64(r, 120);
|
|
}
|
|
|
|
static void record_derived(kar_tensor_info *t) {
|
|
t->n_groups = t->storage_class == KAR_RAW ? 0 : t->n_padded / t->group;
|
|
t->words = t->storage_class == KAR_RAW ? 0 : t->n_padded / 32u;
|
|
t->row_len = (uint32_t)t->dims[0];
|
|
t->row_words = (t->row_len % 32u) ? 0u : t->row_len / 32u;
|
|
t->row_count = t->row_len ? t->n_elements / t->row_len : 0;
|
|
}
|
|
|
|
static kar_status check_record_common(const kar_tensor_info *t, uint64_t pay, uint64_t end) {
|
|
if (t->storage_class > 1u) return KAR_REJECT("D1", "storage_class");
|
|
if (t->n_dims < 1u || t->n_dims > 4u) return KAR_REJECT("D2", "n_dims");
|
|
uint64_t prod = 1;
|
|
for (uint32_t i = 0; i < 4u; ++i) {
|
|
if (i >= t->n_dims && t->dims[i] != 1u) return KAR_REJECT("D2", "unpopulated dim");
|
|
if (i < t->n_dims) prod *= t->dims[i];
|
|
}
|
|
if (prod != t->n_elements) return KAR_REJECT("D2", "n_elements is not the dim product");
|
|
if (t->element_order != 0u) return KAR_REJECT("D3", "element_order");
|
|
if (t->source_dtype > 2u) return KAR_REJECT("D4", "source_dtype");
|
|
if (t->section_offset % 256u) return KAR_REJECT("D7", "section_offset alignment");
|
|
if (t->section_offset < pay || t->section_offset + t->section_bytes > end)
|
|
return KAR_REJECT("D7", "section outside the payload");
|
|
return KAR_OK;
|
|
}
|
|
|
|
static kar_status check_record_nested(const kar_tensor_info *t) {
|
|
if (!t->group || (t->group % 32u) || t->group > 1024u) return KAR_REJECTN("D9", "group", t->group);
|
|
if (t->n_padded != round_up_u64(t->n_elements, t->group)) return KAR_REJECT("D10", "n_padded");
|
|
if (t->planes_stored < 1u || t->planes_stored > 16u) return KAR_REJECT("D11", "planes_stored");
|
|
if (!(1u <= t->planes_min && t->planes_min <= t->planes_max &&
|
|
t->planes_max <= t->planes_stored)) return KAR_REJECT("D12", "dial");
|
|
if (t->nesting > 1u) return KAR_REJECT("D13", "nesting");
|
|
if (t->scales_bytes != t->n_groups * 2u) return KAR_REJECT("D14", "scales_bytes");
|
|
if (t->books_bytes != ((uint64_t)1 << (t->planes_stored + 2)) - 4u)
|
|
return KAR_REJECT("D14", "books_bytes");
|
|
if (t->plane_stride_bytes != round_up_u64(t->words * 4u, 16u))
|
|
return KAR_REJECT("D15", "plane_stride_bytes");
|
|
uint64_t sc = t->section_offset;
|
|
if (t->scales_offset != sc || t->books_offset != round_up_u64(sc + t->scales_bytes, 16u) ||
|
|
t->planes_offset != round_up_u64(t->books_offset + t->books_bytes, 16u))
|
|
return KAR_REJECT("D16", "sub-region order or offsets");
|
|
if (t->planes_offset + (uint64_t)t->planes_stored * t->plane_stride_bytes >
|
|
t->section_offset + t->section_bytes) return KAR_REJECT("D17", "planes overrun the section");
|
|
return KAR_OK;
|
|
}
|
|
|
|
static const uint32_t KAR_DTYPE_BYTES[3] = {4u, 2u, 2u};
|
|
|
|
static kar_status check_record_raw(const kar_tensor_info *t) {
|
|
if (t->group || t->planes_stored || t->planes_min || t->planes_max || t->nesting ||
|
|
t->scales_offset || t->scales_bytes || t->books_offset || t->books_bytes ||
|
|
t->planes_offset || t->plane_stride_bytes) return KAR_REJECT("D18", "coded field set");
|
|
if (t->n_padded != t->n_elements) return KAR_REJECT("D19", "n_padded");
|
|
if (t->section_bytes < t->n_elements * KAR_DTYPE_BYTES[t->source_dtype])
|
|
return KAR_REJECT("D20", "section too short for the raw bytes");
|
|
return KAR_OK;
|
|
}
|
|
|
|
/* ============================================================ name resolution */
|
|
|
|
static kar_status bind_name(kar_archive *a, uint32_t i, const uint8_t *rec, const uint8_t *blob,
|
|
uint64_t blob_bytes) {
|
|
uint32_t off = rd32(rec, 0);
|
|
uint16_t len = rd16(rec, 4);
|
|
if ((uint64_t)off + len + 1u > blob_bytes || blob[off + len] != 0)
|
|
return KAR_REJECT("D5", "name runs past the string table");
|
|
char *dst = a->names + (size_t)i * 256;
|
|
size_t n = len < 255 ? len : 255;
|
|
memcpy(dst, blob + off, n);
|
|
dst[n] = 0;
|
|
a->t[i].name = dst;
|
|
for (uint32_t k = 0; k < i; ++k)
|
|
if (strcmp(a->t[k].name, dst) == 0) return KAR_REJECT("D6", "duplicate tensor name");
|
|
return KAR_OK;
|
|
}
|
|
|
|
/* =============================================================== whole-archive */
|
|
|
|
static kar_status check_envelope(const kar_archive *a) {
|
|
uint64_t sum = 0, bits = 0;
|
|
uint32_t lo = 255u, hi = 0u, any = 0u;
|
|
for (uint32_t i = 0; i < a->info.tensor_count; ++i) {
|
|
const kar_tensor_info *t = &a->t[i];
|
|
sum += t->n_elements;
|
|
if (t->storage_class != KAR_NESTED) continue;
|
|
any = 1u;
|
|
bits += (uint64_t)t->planes_stored * t->n_padded + 16u * t->n_groups;
|
|
if (t->planes_min < lo) lo = t->planes_min;
|
|
if (t->planes_max > hi) hi = t->planes_max;
|
|
}
|
|
if (!any) { lo = 0u; hi = 0u; }
|
|
if (sum != a->info.total_elements) return KAR_REJECT("H8", "total_elements");
|
|
if (bits != a->info.payload_bits) return KAR_REJECT("H9", "payload_bits");
|
|
if (lo != a->info.global_planes_min || hi != a->info.global_planes_max)
|
|
return KAR_REJECT("H13", "global plane envelope");
|
|
return KAR_OK;
|
|
}
|
|
|
|
static kar_status check_no_overlap(const kar_archive *a) {
|
|
for (uint32_t i = 1; i < a->info.tensor_count; ++i) {
|
|
const kar_tensor_info *p = &a->t[i - 1], *q = &a->t[i];
|
|
if (q->section_offset < p->section_offset + p->section_bytes)
|
|
return KAR_REJECTN("D7", "sections overlap or are out of order", i);
|
|
}
|
|
return KAR_OK;
|
|
}
|
|
|
|
static kar_status verify_payload_crcs(const kar_archive *a) {
|
|
for (uint32_t i = 0; i < a->info.tensor_count; ++i) {
|
|
const kar_tensor_info *t = &a->t[i];
|
|
if (crc32_of(a->map + t->section_offset, (size_t)t->section_bytes) != t->payload_crc32)
|
|
return KAR_REJECTN("D8", "payload_crc32", i);
|
|
}
|
|
return KAR_OK;
|
|
}
|
|
|
|
static kar_status parse_records(kar_archive *a, uint32_t flags) {
|
|
const uint8_t *p = a->map;
|
|
const uint8_t *dir = p + rd64(p, 24), *blob = p + rd64(p, 40);
|
|
uint64_t blob_bytes = rd64(p, 48), pay = rd64(p, 56), end = a->info.archive_bytes;
|
|
for (uint32_t i = 0; i < a->info.tensor_count; ++i) {
|
|
const uint8_t *rec = dir + (size_t)i * 192u;
|
|
kar_tensor_info *t = &a->t[i];
|
|
record_fields(rec, t);
|
|
record_derived(t);
|
|
kar_status st = check_record_common(t, pay, end);
|
|
if (st != KAR_OK) return st;
|
|
st = t->storage_class == KAR_RAW ? check_record_raw(t) : check_record_nested(t);
|
|
if (st != KAR_OK) return st;
|
|
st = bind_name(a, i, rec, blob, blob_bytes);
|
|
if (st != KAR_OK) return st;
|
|
}
|
|
kar_status st = check_no_overlap(a);
|
|
if (st == KAR_OK) st = check_envelope(a);
|
|
if (st == KAR_OK && (flags & KAR_OPEN_VERIFY_PAYLOAD)) st = verify_payload_crcs(a);
|
|
return st;
|
|
}
|
|
|
|
static kar_status map_file(const char *path, kar_archive *a) {
|
|
a->fd = open(path, O_RDONLY);
|
|
if (a->fd < 0) return kar_fail(KAR_E_IO, "open %s failed (%lld)", path, (long long)errno);
|
|
struct stat sb;
|
|
if (fstat(a->fd, &sb) != 0) return kar_fail(KAR_E_IO, "fstat %s failed (%lld)", path, 0LL);
|
|
a->map_bytes = (size_t)sb.st_size;
|
|
void *m = mmap(NULL, a->map_bytes, PROT_READ, MAP_SHARED, a->fd, 0);
|
|
if (m == MAP_FAILED) return kar_fail(KAR_E_IO, "mmap %s failed (%lld)", path, 0LL);
|
|
a->map = (const uint8_t *)m;
|
|
return KAR_OK;
|
|
}
|
|
|
|
kar_status kar_open(const char *path, uint32_t flags, kar_archive **out) {
|
|
*out = NULL;
|
|
kar_archive *a = (kar_archive *)calloc(1, sizeof *a);
|
|
if (!a) return KAR_E_IO;
|
|
a->fd = -1;
|
|
kar_status st = map_file(path, a);
|
|
if (st == KAR_OK) st = parse_header_fixed(a->map, a->map_bytes, &a->info);
|
|
if (st == KAR_OK) st = check_header_regions(a->map, a->map_bytes);
|
|
if (st == KAR_OK && !(flags & KAR_OPEN_SKIP_DIGEST)) st = check_directory_digest(a->map);
|
|
if (st == KAR_OK) {
|
|
a->t = (kar_tensor_info *)calloc(a->info.tensor_count, sizeof *a->t);
|
|
a->res = (kar_residency *)calloc(a->info.tensor_count, sizeof *a->res);
|
|
a->names = (char *)calloc(a->info.tensor_count, 256);
|
|
st = (a->t && a->res && a->names) ? parse_records(a, flags) : KAR_E_IO;
|
|
}
|
|
if (st != KAR_OK) { kar_close(a); return st; }
|
|
*out = a;
|
|
return KAR_OK;
|
|
}
|
|
|
|
void kar_close(kar_archive *a) {
|
|
if (!a) return;
|
|
if (a->res)
|
|
for (uint32_t i = 0; i < a->info.tensor_count; ++i)
|
|
if (a->res[i].d_base) cudaFree(a->res[i].d_base);
|
|
if (a->map) munmap((void *)a->map, a->map_bytes);
|
|
if (a->fd >= 0) close(a->fd);
|
|
free(a->t); free(a->res); free(a->names); free(a);
|
|
}
|
|
|
|
const kar_archive_info *kar_info(const kar_archive *a) { return &a->info; }
|
|
uint32_t kar_tensor_count(const kar_archive *a) { return a->info.tensor_count; }
|
|
|
|
const kar_tensor_info *kar_tensor(const kar_archive *a, uint32_t i) {
|
|
return i < a->info.tensor_count ? &a->t[i] : NULL;
|
|
}
|
|
|
|
int kar_find(const kar_archive *a, const char *name) {
|
|
for (uint32_t i = 0; i < a->info.tensor_count; ++i)
|
|
if (strcmp(a->t[i].name, name) == 0) return (int)i;
|
|
return -1;
|
|
}
|
|
|
|
uint64_t kar_resident_bytes(const kar_archive *a) { return a->resident_bytes; }
|
|
|
|
uint32_t kar_resident_planes(const kar_archive *a, uint32_t i) {
|
|
return i < a->info.tensor_count ? a->res[i].planes : 0u;
|
|
}
|
|
|
|
/* ================================================================= residency */
|
|
|
|
/* The level-k prefix of G2: one contiguous span starting at section_offset. The whole point of
|
|
* the format putting scales and books before planes is that this is ONE range, so staging is one
|
|
* memcpy and a lower fidelity is genuinely cheaper to MOVE, not only cheaper to compute. */
|
|
static uint64_t prefix_bytes(const kar_tensor_info *t, uint32_t planes) {
|
|
if (t->storage_class == KAR_RAW) return t->section_bytes;
|
|
return (t->planes_offset - t->section_offset) + (uint64_t)planes * t->plane_stride_bytes;
|
|
}
|
|
|
|
static kar_status check_level(const kar_tensor_info *t, uint32_t planes) {
|
|
if (t->storage_class == KAR_RAW)
|
|
return planes ? KAR_REJECT("M2", "RAW tensor has no levels") : KAR_OK;
|
|
if (planes < t->planes_min || planes > t->planes_max)
|
|
return KAR_REJECTN("M1", "level outside the declared dial", planes);
|
|
if (planes > KAR_MAX_PLANES)
|
|
return kar_fail(KAR_E_UNSUPPORTED, "%s: %lld planes exceeds the compiled specialisations",
|
|
"kar_decode", (long long)planes);
|
|
return KAR_OK;
|
|
}
|
|
|
|
kar_status kar_reserve_shifted(kar_archive *a, uint32_t index, uint32_t planes, uint32_t pad,
|
|
cudaStream_t s) {
|
|
if (index >= a->info.tensor_count) return KAR_E_RANGE;
|
|
const kar_tensor_info *t = &a->t[index];
|
|
if (t->storage_class == KAR_RAW) planes = 0u;
|
|
else if (planes > t->planes_stored) return KAR_REJECTN("M1", "level above planes_stored", planes);
|
|
kar_residency *r = &a->res[index];
|
|
if (r->d_base && r->planes >= planes && r->pad == pad) return KAR_OK;
|
|
uint64_t want = prefix_bytes(t, planes) + pad;
|
|
if (r->d_base) { cudaFree(r->d_base); a->resident_bytes -= r->bytes; r->d_base = NULL; }
|
|
KAR_CUDA(cudaMalloc(&r->d_base, (size_t)want), "cudaMalloc residency");
|
|
KAR_CUDA(cudaMemcpyAsync((uint8_t *)r->d_base + pad, a->map + t->section_offset,
|
|
(size_t)(want - pad), cudaMemcpyHostToDevice, s), "stage prefix");
|
|
KAR_CUDA(cudaStreamSynchronize(s), "stage sync");
|
|
r->bytes = want;
|
|
r->planes = planes;
|
|
r->pad = pad;
|
|
a->resident_bytes += want;
|
|
return KAR_OK;
|
|
}
|
|
|
|
kar_status kar_reserve(kar_archive *a, uint32_t index, uint32_t planes, cudaStream_t s) {
|
|
return kar_reserve_shifted(a, index, planes, 0u, s);
|
|
}
|
|
|
|
kar_status kar_release(kar_archive *a, uint32_t index) {
|
|
if (index >= a->info.tensor_count) return KAR_E_RANGE;
|
|
kar_residency *r = &a->res[index];
|
|
if (!r->d_base) return KAR_OK;
|
|
KAR_CUDA(cudaFree(r->d_base), "cudaFree residency");
|
|
a->resident_bytes -= r->bytes;
|
|
r->d_base = NULL; r->bytes = 0; r->planes = 0; r->pad = 0;
|
|
return KAR_OK;
|
|
}
|
|
|
|
/* ==================================================================== kernels */
|
|
|
|
/* Device views of one resident tensor, so the kernels stay inside the five-parameter limit. */
|
|
struct kar_dev {
|
|
const uint32_t *planes;
|
|
const __half *book;
|
|
const __half *scales;
|
|
uint32_t plane_stride_words;
|
|
uint32_t group_words; /* group/32: how many 32-weight threads share one scale */
|
|
};
|
|
|
|
/* Accumulate the level-k index of weight m out of LEVEL plane words, most significant first.
|
|
* This IS section 5.5 of the format, and it is the only place the bit order is decided. */
|
|
template <int LEVEL>
|
|
__device__ __forceinline__ uint32_t idx_of(const uint32_t *bw, int m) {
|
|
uint32_t idx = 0u;
|
|
#pragma unroll
|
|
for (int j = 0; j < LEVEL; ++j) idx = (idx << 1) | ((bw[j] >> m) & 1u);
|
|
return idx;
|
|
}
|
|
|
|
template <int LEVEL>
|
|
__device__ __forceinline__ void load_planes(const kar_dev d, uint32_t w, uint32_t *bw) {
|
|
#pragma unroll
|
|
for (int j = 0; j < LEVEL; ++j) bw[j] = d.planes[(size_t)j * d.plane_stride_words + w];
|
|
}
|
|
|
|
/* The book is small enough to live in shared memory as fp32, so the per-weight lookup is a
|
|
* broadcast and the fp16->fp32 widening happens 2^LEVEL times per block instead of 32 times per
|
|
* thread. Converting here rather than at use is what makes the multiply below bit-identical to
|
|
* kar_codec.decode: float32(book) * float32(scale), rounded exactly once. */
|
|
template <int LEVEL>
|
|
__device__ __forceinline__ void load_book(const __half *book, float *s_book) {
|
|
for (uint32_t i = threadIdx.x; i < (1u << LEVEL); i += blockDim.x)
|
|
s_book[i] = __half2float(book[i]);
|
|
__syncthreads();
|
|
}
|
|
|
|
/* Reconstruct one thread's 32 weights and store them as 16-byte vectors.
|
|
*
|
|
* THE SHAPE OF THIS FUNCTION IS THE MEASUREMENT, NOT A STYLE CHOICE. Two things about it cost a
|
|
* factor of two each if they are written the obvious way:
|
|
*
|
|
* - only PER values are live at once, one 16-byte store's worth, instead of an array of 32. An
|
|
* array of 32 floats plus LEVEL plane words crosses the point where nvcc starts spilling, and
|
|
* the spill appeared in the measurement as a cliff between four and five planes - the shallow
|
|
* levels ran at 88% of this card's HBM ceiling and the deep ones at 53%.
|
|
* - the tail loop has a COMPILE-TIME trip count with a predicate inside, not a runtime bound. A
|
|
* runtime bound makes the value array dynamically indexed, which forces it to local memory on
|
|
* every path including the fast one. That one cost 1.5x on the whole kernel.
|
|
*/
|
|
template <int LEVEL, typename OUT>
|
|
__device__ __forceinline__ void emit32(const float *s_book, const uint32_t *bw, float sc,
|
|
OUT *dst, uint32_t n_left) {
|
|
const int PER = 16 / (int)sizeof(OUT);
|
|
if (n_left >= 32u) {
|
|
#pragma unroll
|
|
for (int c = 0; c < 32 / PER; ++c) {
|
|
OUT v[PER];
|
|
#pragma unroll
|
|
for (int m = 0; m < PER; ++m)
|
|
v[m] = (OUT)(s_book[idx_of<LEVEL>(bw, c * PER + m)] * sc);
|
|
reinterpret_cast<uint4 *>(dst)[c] = *reinterpret_cast<const uint4 *>(v);
|
|
}
|
|
return;
|
|
}
|
|
#pragma unroll
|
|
for (int m = 0; m < 32; ++m)
|
|
if ((uint32_t)m < n_left) dst[m] = (OUT)(s_book[idx_of<LEVEL>(bw, m)] * sc);
|
|
}
|
|
|
|
/* Whole-tensor decode. One thread owns 32 consecutive weights: LEVEL coalesced plane loads, one
|
|
* scale load, 32 shared-memory lookups, and 32*sizeof(OUT) bytes out as 16-byte vectors. */
|
|
template <int LEVEL, typename OUT>
|
|
__global__ __launch_bounds__(256) void kar_plane_kernel(const kar_dev d, OUT *__restrict__ out,
|
|
uint32_t words, uint64_t n) {
|
|
extern __shared__ float s_book[];
|
|
load_book<LEVEL>(d.book, s_book);
|
|
uint32_t w = blockIdx.x * blockDim.x + threadIdx.x;
|
|
if (w >= words) return;
|
|
uint32_t bw[LEVEL];
|
|
load_planes<LEVEL>(d, w, bw);
|
|
float sc = __half2float(d.scales[w / d.group_words]);
|
|
uint64_t base = (uint64_t)w * 32u;
|
|
uint64_t left = n > base ? n - base : 0u;
|
|
emit32<LEVEL, OUT>(s_book, bw, sc, out + base, left > 32u ? 32u : (uint32_t)left);
|
|
}
|
|
|
|
/* The QUAD mapping: one thread, one 16-byte store, perfectly coalesced across the warp. The
|
|
* price is that the PER-weight slice is narrower than a plane word, so eight threads (four at
|
|
* fp16) load the same plane word. Those duplicate loads cost L1 and L2 bandwidth but no extra
|
|
* DRAM traffic, and the plane stream is under a byte per weight against four bytes of output. */
|
|
template <int LEVEL, typename OUT>
|
|
__global__ __launch_bounds__(256) void kar_quad_kernel(const kar_dev d, OUT *__restrict__ out,
|
|
uint64_t quads, uint64_t n) {
|
|
const int PER = 16 / (int)sizeof(OUT);
|
|
const int SUB = 32 / PER;
|
|
extern __shared__ float s_book[];
|
|
load_book<LEVEL>(d.book, s_book);
|
|
uint64_t q = (uint64_t)blockIdx.x * blockDim.x + threadIdx.x;
|
|
if (q >= quads) return;
|
|
uint32_t w = (uint32_t)(q / SUB);
|
|
int m0 = (int)(q % SUB) * PER;
|
|
uint32_t bw[LEVEL];
|
|
load_planes<LEVEL>(d, w, bw);
|
|
float sc = __half2float(d.scales[w / d.group_words]);
|
|
OUT v[PER];
|
|
#pragma unroll
|
|
for (int m = 0; m < PER; ++m) v[m] = (OUT)(s_book[idx_of<LEVEL>(bw, m0 + m)] * sc);
|
|
uint64_t base = q * PER;
|
|
if (base + PER <= n) {
|
|
reinterpret_cast<uint4 *>(out)[q] = *reinterpret_cast<const uint4 *>(v);
|
|
return;
|
|
}
|
|
#pragma unroll
|
|
for (int m = 0; m < PER; ++m)
|
|
if (base + m < n) out[base + m] = v[m];
|
|
}
|
|
|
|
/* Row-granular decode for a gather table. Thread t covers word `k` of destination row `r`; the
|
|
* source row is d_rows[r]. Rows are a multiple of 32 weights wide, so a row's words are
|
|
* contiguous, its scales are whole, and its output slice is 16-byte aligned. */
|
|
template <int LEVEL, typename OUT>
|
|
__global__ __launch_bounds__(256) void kar_row_kernel(const kar_dev d, OUT *__restrict__ out,
|
|
const uint32_t *__restrict__ rows, uint32_t row_words,
|
|
uint64_t n_threads) {
|
|
extern __shared__ float s_book[];
|
|
load_book<LEVEL>(d.book, s_book);
|
|
uint64_t t = (uint64_t)blockIdx.x * blockDim.x + threadIdx.x;
|
|
if (t >= n_threads) return;
|
|
uint32_t k = (uint32_t)(t % row_words);
|
|
uint64_t r = t / row_words;
|
|
uint32_t w = rows[r] * row_words + k;
|
|
uint32_t bw[LEVEL];
|
|
load_planes<LEVEL>(d, w, bw);
|
|
float sc = __half2float(d.scales[w / d.group_words]);
|
|
emit32<LEVEL, OUT>(s_book, bw, sc, out + (r * row_words + k) * 32u, 32u);
|
|
}
|
|
|
|
/* RAW widening. The format stores these verbatim precisely because coding a 128-element norm
|
|
* costs more than storing it; the runtime still wants fp32, so the widening lives here. */
|
|
__global__ void kar_raw_kernel(const uint8_t *__restrict__ src, float *__restrict__ out,
|
|
uint64_t n, uint32_t dtype) {
|
|
uint64_t i = (uint64_t)blockIdx.x * blockDim.x + threadIdx.x;
|
|
if (i >= n) return;
|
|
if (dtype == KAR_F32) out[i] = reinterpret_cast<const float *>(src)[i];
|
|
else if (dtype == KAR_F16) out[i] = __half2float(reinterpret_cast<const __half *>(src)[i]);
|
|
else {
|
|
uint32_t b = (uint32_t)reinterpret_cast<const uint16_t *>(src)[i] << 16;
|
|
out[i] = __int_as_float((int)b);
|
|
}
|
|
}
|
|
|
|
/* ================================================================== dispatch */
|
|
|
|
static kar_kernel_variant g_kernel = KAR_KERNEL_QUAD;
|
|
|
|
void kar_set_kernel(kar_kernel_variant v) { g_kernel = v; }
|
|
kar_kernel_variant kar_get_kernel(void) { return g_kernel; }
|
|
|
|
static kar_dev device_view(const kar_archive *a, uint32_t index) {
|
|
const kar_tensor_info *t = &a->t[index];
|
|
const uint8_t *base = (const uint8_t *)a->res[index].d_base + a->res[index].pad;
|
|
kar_dev d;
|
|
d.scales = (const __half *)(base + (t->scales_offset - t->section_offset));
|
|
d.book = NULL;
|
|
d.planes = (const uint32_t *)(base + (t->planes_offset - t->section_offset));
|
|
d.plane_stride_words = t->plane_stride_bytes / 4u;
|
|
d.group_words = t->group / 32u;
|
|
return d;
|
|
}
|
|
|
|
/* Book k lives at books_offset + (2^k - 2) * 2 bytes: the tables for levels 1..k-1 precede it. */
|
|
static const __half *book_ptr(const kar_archive *a, uint32_t index, uint32_t planes) {
|
|
const kar_tensor_info *t = &a->t[index];
|
|
const uint8_t *base = (const uint8_t *)a->res[index].d_base + a->res[index].pad;
|
|
uint64_t off = (t->books_offset - t->section_offset) + (((uint64_t)1 << planes) - 2u) * 2u;
|
|
return (const __half *)(base + off);
|
|
}
|
|
|
|
/* The dispatch of a runtime plane count onto a compile-time specialisation. A switch, on purpose:
|
|
* it is the whole mechanism by which fact 1 survives contact with a runtime dial. */
|
|
#define KAR_DISPATCH(OUT, LAUNCH) \
|
|
switch (planes) { \
|
|
case 1: LAUNCH(1, OUT); break; case 2: LAUNCH(2, OUT); break; \
|
|
case 3: LAUNCH(3, OUT); break; case 4: LAUNCH(4, OUT); break; \
|
|
case 5: LAUNCH(5, OUT); break; case 6: LAUNCH(6, OUT); break; \
|
|
case 7: LAUNCH(7, OUT); break; case 8: LAUNCH(8, OUT); break; \
|
|
default: return KAR_E_UNSUPPORTED; \
|
|
}
|
|
|
|
#define KAR_LAUNCH_PLANE(L, OUT) \
|
|
do { if (g_kernel == KAR_KERNEL_QUAD) { \
|
|
uint64_t quads_ = t->n_padded / (16u / sizeof(OUT)); \
|
|
kar_quad_kernel<L, OUT><<<(unsigned)((quads_ + 255u) / 256u), 256, shmem, s>>>( \
|
|
d, (OUT *)dst, quads_, t->n_elements); \
|
|
} else { \
|
|
kar_plane_kernel<L, OUT><<<blocks, 256, shmem, s>>>(d, (OUT *)dst, (uint32_t)t->words, \
|
|
t->n_elements); \
|
|
} } while (0)
|
|
|
|
#define KAR_LAUNCH_ROW(L, OUT) \
|
|
kar_row_kernel<L, OUT><<<blocks, 256, shmem, s>>>(d, (OUT *)r->dst, r->d_row_ids, \
|
|
t->row_words, threads)
|
|
|
|
static kar_status decode_raw(kar_archive *a, uint32_t index, float *dst, cudaStream_t s) {
|
|
const kar_tensor_info *t = &a->t[index];
|
|
const uint8_t *src = (const uint8_t *)a->res[index].d_base + a->res[index].pad;
|
|
uint64_t blocks = (t->n_elements + 255u) / 256u;
|
|
kar_raw_kernel<<<(unsigned)blocks, 256, 0, s>>>(src, dst, t->n_elements, t->source_dtype);
|
|
KAR_CUDA(cudaGetLastError(), "raw kernel");
|
|
return KAR_OK;
|
|
}
|
|
|
|
struct kar_call {
|
|
uint32_t index, planes, as_half;
|
|
void *dst;
|
|
};
|
|
|
|
static kar_status decode_any(kar_archive *a, struct kar_call c, cudaStream_t s) {
|
|
uint32_t index = c.index, planes = c.planes;
|
|
if (index >= a->info.tensor_count) return KAR_E_RANGE;
|
|
const kar_tensor_info *t = &a->t[index];
|
|
if (t->storage_class == KAR_RAW) return decode_raw(a, index, (float *)c.dst, s);
|
|
kar_status st = check_level(t, planes);
|
|
if (st != KAR_OK) return st;
|
|
if (a->res[index].planes < planes)
|
|
return kar_fail(KAR_E_STATE, "%s: resident at fewer planes than asked (%lld)",
|
|
t->name, (long long)a->res[index].planes);
|
|
kar_dev d = device_view(a, index);
|
|
d.book = book_ptr(a, index, planes);
|
|
size_t shmem = ((size_t)1 << planes) * sizeof(float);
|
|
unsigned blocks = (unsigned)((t->words + 255u) / 256u);
|
|
void *dst = c.dst;
|
|
if (c.as_half) { KAR_DISPATCH(__half, KAR_LAUNCH_PLANE) }
|
|
else { KAR_DISPATCH(float, KAR_LAUNCH_PLANE) }
|
|
KAR_CUDA(cudaGetLastError(), "plane kernel");
|
|
return KAR_OK;
|
|
}
|
|
|
|
kar_status kar_decode(kar_archive *a, uint32_t index, uint32_t planes, float *dst,
|
|
cudaStream_t s) {
|
|
struct kar_call c = {index, planes, 0u, (void *)dst};
|
|
return decode_any(a, c, s);
|
|
}
|
|
|
|
kar_status kar_decode_f16(kar_archive *a, uint32_t index, uint32_t planes, void *dst,
|
|
cudaStream_t s) {
|
|
struct kar_call c = {index, planes, 1u, dst};
|
|
return decode_any(a, c, s);
|
|
}
|
|
|
|
kar_status kar_decode_rows(kar_archive *a, const kar_row_request *r, cudaStream_t s) {
|
|
if (r->index >= a->info.tensor_count) return KAR_E_RANGE;
|
|
const kar_tensor_info *t = &a->t[r->index];
|
|
uint32_t planes = r->planes;
|
|
if (t->storage_class == KAR_RAW) return KAR_REJECT("M2", "RAW tensor has no rows to gather");
|
|
if (!t->row_words) return kar_fail(KAR_E_UNSUPPORTED, "%s: row_len %lld is not a multiple of 32",
|
|
t->name, (long long)t->row_len);
|
|
kar_status st = check_level(t, planes);
|
|
if (st != KAR_OK) return st;
|
|
if (a->res[r->index].planes < planes) return KAR_E_STATE;
|
|
kar_dev d = device_view(a, r->index);
|
|
d.book = book_ptr(a, r->index, planes);
|
|
size_t shmem = ((size_t)1 << planes) * sizeof(float);
|
|
uint64_t threads = (uint64_t)r->n_rows * t->row_words;
|
|
unsigned blocks = (unsigned)((threads + 255u) / 256u);
|
|
KAR_DISPATCH(float, KAR_LAUNCH_ROW)
|
|
KAR_CUDA(cudaGetLastError(), "row kernel");
|
|
return KAR_OK;
|
|
}
|
|
|
|
/* ================================================================ cost model */
|
|
|
|
/* An ESTIMATE, and the notes say so at length. It prices the two streams the kernel moves and
|
|
* charges them at whichever measured bandwidth the working set implies. It knows nothing about
|
|
* occupancy, about what else is on the card, or about whether the caller's destination buffer is
|
|
* already hot; a scheduler that needs those must measure them itself. */
|
|
static double price(uint64_t read_bytes, uint64_t write_bytes) {
|
|
double ws = (double)(read_bytes + write_bytes);
|
|
double bw = ws <= (double)g_machine.l2_bytes * 0.6 ? g_machine.l2_bytes_per_s
|
|
: g_machine.dram_bytes_per_s;
|
|
return g_machine.launch_seconds + ws / (bw * g_machine.decode_efficiency);
|
|
}
|
|
|
|
static kar_cost cost_finish(kar_cost c) {
|
|
c.est_seconds = price(c.plane_bytes, c.output_bytes);
|
|
c.est_gweights_per_s = c.est_seconds > 0.0 ? (double)c.weights / c.est_seconds / 1e9 : 0.0;
|
|
return c;
|
|
}
|
|
|
|
kar_cost kar_decode_cost(const kar_archive *a, uint32_t index, uint32_t planes) {
|
|
kar_cost c;
|
|
memset(&c, 0, sizeof c);
|
|
if (index >= a->info.tensor_count) return c;
|
|
const kar_tensor_info *t = &a->t[index];
|
|
c.weights = t->n_elements;
|
|
c.output_bytes = t->n_elements * 4u;
|
|
if (t->storage_class == KAR_RAW) {
|
|
c.plane_bytes = t->n_elements * KAR_DTYPE_BYTES[t->source_dtype];
|
|
c.resident_bytes = t->section_bytes;
|
|
} else {
|
|
c.plane_bytes = (uint64_t)planes * t->words * 4u + t->scales_bytes +
|
|
(((uint64_t)1 << planes) * 2u);
|
|
c.resident_bytes = prefix_bytes(t, planes);
|
|
}
|
|
uint32_t have = a->res[index].planes;
|
|
c.stage_bytes = (a->res[index].d_base && have >= planes) ? 0u : c.resident_bytes;
|
|
return cost_finish(c);
|
|
}
|
|
|
|
/* A row gather reads rw*4 bytes per plane per row, but the memory system charges it in whole
|
|
* sectors, and 160 weights is five words - twenty bytes - so a 32-byte sector is the unit that
|
|
* is actually paid for. Modelling that is the difference between a scheduler that thinks the
|
|
* gather table is free and one that knows what it costs. */
|
|
kar_cost kar_decode_rows_cost(const kar_archive *a, uint32_t index, uint32_t planes,
|
|
uint64_t n_rows) {
|
|
kar_cost c;
|
|
memset(&c, 0, sizeof c);
|
|
if (index >= a->info.tensor_count) return c;
|
|
const kar_tensor_info *t = &a->t[index];
|
|
if (!t->row_words) return c;
|
|
uint64_t sector = g_machine.dram_sector_bytes;
|
|
uint64_t per_row = round_up_u64((uint64_t)t->row_words * 4u, sector) * planes +
|
|
round_up_u64((uint64_t)(t->row_len / t->group) * 2u, sector);
|
|
c.weights = n_rows * t->row_len;
|
|
c.plane_bytes = n_rows * per_row;
|
|
c.output_bytes = c.weights * 4u;
|
|
c.resident_bytes = prefix_bytes(t, planes);
|
|
c.stage_bytes = (a->res[index].d_base && a->res[index].planes >= planes) ? 0u : c.resident_bytes;
|
|
return cost_finish(c);
|
|
}
|
|
|
|
/* ========================================================= machine measurement */
|
|
|
|
__global__ void kar_stream_kernel(const float4 *__restrict__ in, float4 *__restrict__ out,
|
|
uint64_t n) {
|
|
uint64_t i = (uint64_t)blockIdx.x * blockDim.x + threadIdx.x;
|
|
if (i < n) out[i] = in[i];
|
|
}
|
|
|
|
static double time_stream(const float4 *in, float4 *out, uint64_t n4, int iters) {
|
|
cudaEvent_t t0, t1;
|
|
cudaEventCreate(&t0); cudaEventCreate(&t1);
|
|
unsigned blocks = (unsigned)((n4 + 255u) / 256u);
|
|
kar_stream_kernel<<<blocks, 256>>>(in, out, n4);
|
|
cudaDeviceSynchronize();
|
|
cudaEventRecord(t0);
|
|
for (int i = 0; i < iters; ++i) kar_stream_kernel<<<blocks, 256>>>(in, out, n4);
|
|
cudaEventRecord(t1);
|
|
cudaEventSynchronize(t1);
|
|
float ms = 0.f;
|
|
cudaEventElapsedTime(&ms, t0, t1);
|
|
cudaEventDestroy(t0); cudaEventDestroy(t1);
|
|
double secs = (double)ms * 1e-3 / iters;
|
|
return (double)n4 * 32.0 / secs; /* 16 bytes read + 16 written per float4 */
|
|
}
|
|
|
|
kar_status kar_measure_machine(kar_machine *out) {
|
|
cudaDeviceProp prop;
|
|
KAR_CUDA(cudaGetDeviceProperties(&prop, 0), "getDeviceProperties");
|
|
kar_machine m = g_machine;
|
|
m.l2_bytes = (uint64_t)prop.l2CacheSize;
|
|
uint64_t big = 2ull << 30, small = m.l2_bytes / 4;
|
|
float4 *a4 = NULL, *b4 = NULL;
|
|
KAR_CUDA(cudaMalloc(&a4, (size_t)big), "measure alloc in");
|
|
if (cudaMalloc(&b4, (size_t)big) != cudaSuccess) { cudaFree(a4); return KAR_E_CUDA; }
|
|
cudaMemset(a4, 0, (size_t)big);
|
|
m.dram_bytes_per_s = time_stream(a4, b4, big / 16, 20);
|
|
m.l2_bytes_per_s = time_stream(a4, b4, small / 16, 200);
|
|
if (m.l2_bytes_per_s < m.dram_bytes_per_s) m.l2_bytes_per_s = m.dram_bytes_per_s;
|
|
cudaFree(a4); cudaFree(b4);
|
|
m.launch_seconds = 3.0e-6;
|
|
m.dram_sector_bytes = 32u;
|
|
if (!(m.decode_efficiency > 0.0)) m.decode_efficiency = 0.88;
|
|
g_machine = m;
|
|
if (out) *out = m;
|
|
return KAR_OK;
|
|
}
|