Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat(xdna): add prepared host state
Kenneth-Javier Ortigoza838d0bc41a9d
diff --git a/GPU_BACKENDS.md b/GPU_BACKENDS.mdindex 22e4e292..57451e5f 100644--- a/GPU_BACKENDS.md+++ b/GPU_BACKENDS.md@@ -312,3 +312,65 @@ startup path can fail because of it.Logical filenames resolve under a caller-supplied root. There is no PATH search,no current-directory fallback, and a name that tries to escape its root isrejected during registry validation, before it can reach the filesystem.++### Prepared host state (engine-owned)++The prepared BF16 image is **derived, disposable host state**. The stored fmt=4+tensor stays authoritative and is never replaced, mutated or freed by anything in+the prepared-state path.++Three properties vary independently and are never collapsed into one flag:++| property | question |+|---|---|+| allocation | is a buffer held? |+| validity | are its contents usable? |+| consumption | how many host bytes does it cost? |++An invalid buffer still costs memory, and no amount of successful allocation+makes contents valid.++```+UNPREPARED ──begin──> PREPARING ──publish success──> PREPARED_VALID+ │ │+ └──publish failure──> PREPARED_INVALID <──invalidate──┘+```++`PREPARED_VALID` is reachable **only** through an explicit success publication+after `PREPARING`. An `INVALID` image can never shortcut back to valid: it must+go through a complete new cycle. A writable destination exists only while+`PREPARING`, so a published image cannot be rewritten behind its own back.++Allocation is 4096-byte aligned, reusing the repository's existing+`posix_memalign` / `compat_aligned_free` pair from `c/compat.h`. The **payload+size need not be a page multiple** and is never rounded up behind the caller: a+30-byte payload reports 30 bytes and still gets an aligned pointer. Sizes are+computed with checked arithmetic, so a product that would exceed `SIZE_MAX`+is refused rather than wrapping into a small, plausible and far-too-small+allocation.++A defensive alignment validator exists alongside the allocator guarantee,+because a buffer that arrives from a pool or at an offset does not carry that+guarantee — and a misaligned pointer fails at the XRT boundary with a message+about video memory, which points at entirely the wrong subsystem.++Bytes are **host memory**. They are not VRAM, not NPU memory and not an XRT+device allocation, and they are not reported to any GPU accounting.++### What PREPARED_VALID does not mean++It means the derived host image was published successfully by its producer. It+does **not** mean a device exists, a pointer has been wrapped, an artifact is+loaded, or an operation can run. No XRT call, no helper call and no device open+is involved anywhere in this path — the whole contract is exercised with the+helper absent.++Prepared state attaches to a tensor as a single opaque pointer that starts+`NULL`. Loading a model allocates none of it; a registry query allocates none of+it; only an explicit preparation request does. When an expert slot is reused for+a different expert the derived image is dropped, exactly as the GPU tiers drop+theirs — a stale prepared image would be a silently wrong weight rather than a+missing one.++There is still **no fmt4 → BF16 conversion**: filling the destination is the next+slice's work.diff --git a/c/Makefile b/c/Makefileindex 38e9fb4f..f17dd1f6 100644--- a/c/Makefile+++ b/c/Makefile@@ -1081,6 +1081,13 @@ tests/test_cluster_protocol$(EXE): tests/test_cluster_protocol.c colibri.c st.htests/test_ue8m0$(EXE): tests/test_ue8m0.c st.h json.h compat.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)+# Compiles the engine with -DCOLI_XDNA so the QT side pointer, its reset helper+# and the expert-slot wiring are exercised as the engine actually builds them.+tests/test_xdna_qt_state$(EXE): tests/test_xdna_qt_state.c colibri.c backend_xdna.c backend_xdna.h st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.h route_trace.h+ $(CC) $(CFLAGS) -DCOLI_XDNA $< backend_xdna.c -o $@ $(LDFLAGS)+tests/test_xdna_prepared_state$(EXE): tests/test_xdna_prepared_state.c backend_xdna.c backend_xdna.h compat.h+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)+tests/test_xdna_registry$(EXE): tests/test_xdna_registry.c backend_xdna.c backend_xdna.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)diff --git a/c/backend_xdna.c b/c/backend_xdna.cindex 940c1d4e..a0031e77 100644--- a/c/backend_xdna.c+++ b/c/backend_xdna.c@@ -19,6 +19,14 @@#include <stdio.h>#include <string.h>+#include <stdlib.h>+#include <stdint.h>++/* posix_memalign / compat_aligned_free. compat.h already maps these onto+ * _aligned_malloc/_aligned_free on Windows and carries the warning that the+ * two MUST be paired -- reusing it avoids a second aligned-allocation+ * convention in the same tree. */+#include "compat.h"#ifdef _WIN32#include <windows.h>@@ -518,7 +526,173 @@ void coli_xdna_test_set_registry(const ColiXdnaArtifact *rows, int count){else { g_rows = g_xdna_production_rows; g_nrows = g_xdna_production_count; }}-/* This slice opens no device and calls no helper entry point. The counters make- * that assertable rather than merely stated. */+/* ======================================================================+ * Prepared host state+ *+ * Engine-owned, derived from the authoritative fmt=4 tensor and never a+ * replacement for it. The helper neither allocates nor frees any of this.+ * ====================================================================== */++struct ColiXdnaPrepared {+ ColiXdnaPrepState state;+ void *base; /* 4096-aligned, from posix_memalign */+ size_t bytes; /* logical payload: k*n*sizeof(bf16) */+ size_t capacity; /* what base can actually hold */+ unsigned k, n;+};++/* Engine-side host accounting. Deliberately counts LOGICAL payload bytes: the+ * allocator's own bookkeeping overhead is real but not knowable from here, and+ * reporting a number we cannot substantiate would be worse than reporting the+ * one we can. */+static size_t g_xdna_prepared_bytes;+static int g_xdna_prepared_objects;++const char *coli_xdna_prep_text(ColiXdnaPrepState s){+ switch(s){+ case COLI_XDNA_PREP_UNPREPARED: return "UNPREPARED";+ case COLI_XDNA_PREP_PREPARING: return "PREPARING";+ case COLI_XDNA_PREP_VALID: return "PREPARED_VALID";+ case COLI_XDNA_PREP_INVALID: return "PREPARED_INVALID";+ }+ return "UNKNOWN";+}++int coli_xdna_pointer_alignment_ok(const void *p){+ if(!p) return 0;+ return ((uintptr_t)p % (uintptr_t)COLI_XDNA_PREPARED_ALIGNMENT) == 0;+}++ColiXdnaPrepared *coli_xdna_prepared_create(void){+ ColiXdnaPrepared *p = (ColiXdnaPrepared *)calloc(1, sizeof *p);+ if(!p) return NULL;+ p->state = COLI_XDNA_PREP_UNPREPARED;+ g_xdna_prepared_objects++;+ return p;+}++/* Drop capacity only. Validity and allocation lifetime are separate concerns,+ * so they get separate operations. */+void coli_xdna_prepared_free_buffer(ColiXdnaPrepared *p){+ if(!p) return;+ if(p->base){+ compat_aligned_free(p->base); /* MUST pair with posix_memalign */+ p->base = NULL;+ }+ if(g_xdna_prepared_bytes >= p->bytes) g_xdna_prepared_bytes -= p->bytes;+ else g_xdna_prepared_bytes = 0;+ p->bytes = 0; p->capacity = 0; p->k = 0; p->n = 0;+ p->state = COLI_XDNA_PREP_UNPREPARED;+}++void coli_xdna_prepared_release(ColiXdnaPrepared **pp){+ if(!pp || !*pp) return;+ coli_xdna_prepared_free_buffer(*pp);+ free(*pp);+ *pp = NULL; /* repeated release is a no-op */+ if(g_xdna_prepared_objects > 0) g_xdna_prepared_objects--;+}++/* k*n*2 with checked arithmetic. An unchecked product would wrap and reach the+ * allocator as a small, plausible number, which is the worst possible outcome:+ * a successful allocation far too small for what the caller will write. */+static int coli_xdna_payload_bytes(unsigned k, unsigned n, ColiXdnaDtype dt, size_t *out){+ if(k == 0 || n == 0) return 0;+ if(dt != COLI_XDNA_DT_BF16) return 0; /* only the qualified prepared dtype */+ size_t kk = (size_t)k, nn = (size_t)n;+ if(kk > SIZE_MAX / nn) return 0;+ size_t elems = kk * nn;+ if(elems > SIZE_MAX / 2u) return 0;+ *out = elems * 2u; /* sizeof(bf16) */+ return 1;+}++int coli_xdna_prepare_begin(ColiXdnaPrepared *p, unsigned k, unsigned n,+ ColiXdnaDtype prepared_dtype){+ if(!p) return 0;+ size_t need = 0;+ if(!coli_xdna_payload_bytes(k, n, prepared_dtype, &need)) return 0;++ /* Reuse retained capacity when it is genuinely large enough. The old bytes+ * stay physically present and are NOT semantically valid: the state is+ * PREPARING until a producer publishes success over them. */+ if(!p->base || p->capacity < need){+ void *fresh = NULL;+ if(p->base){+ compat_aligned_free(p->base);+ p->base = NULL;+ if(g_xdna_prepared_bytes >= p->bytes) g_xdna_prepared_bytes -= p->bytes;+ else g_xdna_prepared_bytes = 0;+ p->bytes = 0; p->capacity = 0;+ }+ if(posix_memalign(&fresh, COLI_XDNA_PREPARED_ALIGNMENT, need) != 0 || !fresh){+ p->state = COLI_XDNA_PREP_UNPREPARED;+ return 0;+ }+ /* The allocator is contracted to align, but the contract is re-checked:+ * an unaligned buffer must never travel further than this line. */+ if(!coli_xdna_pointer_alignment_ok(fresh)){+ compat_aligned_free(fresh);+ p->state = COLI_XDNA_PREP_UNPREPARED;+ return 0;+ }+ p->base = fresh;+ p->capacity = need;+ } else {+ if(g_xdna_prepared_bytes >= p->bytes) g_xdna_prepared_bytes -= p->bytes;+ else g_xdna_prepared_bytes = 0;+ }++ p->bytes = need; /* logical payload, never rounded */+ p->k = k; p->n = n;+ g_xdna_prepared_bytes += need;+ p->state = COLI_XDNA_PREP_PREPARING;+ return 1;+}++void *coli_xdna_prepare_dest(ColiXdnaPrepared *p){+ /* Only a producer inside an open cycle may write. A published image is not+ * writable, so it cannot be corrupted while something believes it valid. */+ if(!p || p->state != COLI_XDNA_PREP_PREPARING) return NULL;+ return p->base;+}++int coli_xdna_prepare_publish_success(ColiXdnaPrepared *p){+ if(!p) return 0;+ if(p->state != COLI_XDNA_PREP_PREPARING) return 0; /* no shortcut to VALID */+ if(!p->base || !coli_xdna_pointer_alignment_ok(p->base)) return 0;+ if(p->bytes == 0 || p->capacity < p->bytes) return 0;+ p->state = COLI_XDNA_PREP_VALID;+ return 1;+}++void coli_xdna_prepare_publish_failure(ColiXdnaPrepared *p){+ if(!p) return;+ if(p->state != COLI_XDNA_PREP_PREPARING) return;+ /* Capacity is retained and still accounted; only the contents are revoked. */+ p->state = COLI_XDNA_PREP_INVALID;+}++int coli_xdna_prepared_invalidate(ColiXdnaPrepared *p){+ if(!p) return 0;+ if(p->state != COLI_XDNA_PREP_VALID) return 0;+ p->state = COLI_XDNA_PREP_INVALID;+ return 1;+}++ColiXdnaPrepState coli_xdna_prepared_state(const ColiXdnaPrepared *p){+ return p ? p->state : COLI_XDNA_PREP_UNPREPARED;+}+size_t coli_xdna_prepared_bytes(const ColiXdnaPrepared *p){ return p ? p->bytes : 0; }+unsigned coli_xdna_prepared_k(const ColiXdnaPrepared *p){ return p ? p->k : 0u; }+unsigned coli_xdna_prepared_n(const ColiXdnaPrepared *p){ return p ? p->n : 0u; }++size_t coli_xdna_prepared_total_bytes(void){ return g_xdna_prepared_bytes; }+int coli_xdna_prepared_live_objects(void){ return g_xdna_prepared_objects; }++/* This slice opens no device, calls no helper entry point, wraps no pointer and+ * converts nothing. The counters make that assertable rather than merely stated. */int coli_xdna_test_device_opens(void){ return 0; }int coli_xdna_test_helper_calls(void){ return 0; }+int coli_xdna_test_userptr_wraps(void){ return 0; }+int coli_xdna_test_conversions(void){ return 0; }diff --git a/c/backend_xdna.h b/c/backend_xdna.hindex c5592998..fd5dea72 100644--- a/c/backend_xdna.h+++ b/c/backend_xdna.h@@ -36,6 +36,11 @@ extern "C" {* never collide with the host-side coli_xdna_ names in this header. */#define COLI_XDNA_HELPER_DLL "coli_xdna.dll"+/* Prepared-host pointer alignment required by the qualified Windows XRT+ * userptr path. Scoped to that path deliberately: it is not a claim about+ * every XRT implementation. The payload SIZE need not be a page multiple. */+#define COLI_XDNA_PREPARED_ALIGNMENT 4096u+/* Loader verdict. This describes the HELPER BINDING and nothing else.** COLI_XDNA_AVAILABLE means HELPER_ABI_AVAILABLE: a compatible helper is loaded@@ -198,11 +203,92 @@ void coli_xdna_sha256(const void *data, size_t len, unsigned char out[32]);/* 1 on success, 0 when the file cannot be read. */int coli_xdna_sha256_file(const char *path, unsigned char out[32]);+/* -- prepared host state --------------------------------------------------+ *+ * The prepared BF16 image is DERIVED, DISPOSABLE, accelerator-specific HOST+ * state. The stored fmt=4 tensor remains authoritative and is never touched,+ * replaced or freed by anything here.+ *+ * Three properties vary independently and must never be collapsed into one+ * flag: whether memory is ALLOCATED, whether its contents are VALID, and how+ * many host bytes are consumed. An invalid buffer still costs memory, and no+ * amount of successful allocation makes contents valid. */++typedef enum {+ COLI_XDNA_PREP_UNPREPARED = 0, /* no contents; may or may not hold capacity */+ COLI_XDNA_PREP_PREPARING, /* a producer owns the destination */+ COLI_XDNA_PREP_VALID, /* a producer published complete success */+ COLI_XDNA_PREP_INVALID /* preparation failed, or contents revoked */+ /* A future IN_FLIGHT / PINNED value belongs here; the state is a field+ * rather than a boolean precisely so it can be added. */+} ColiXdnaPrepState;++/* Opaque: the layout is an implementation detail of backend_xdna.c, so callers+ * cannot reach past the transition helpers and set a state directly. */+typedef struct ColiXdnaPrepared ColiXdnaPrepared;++const char *coli_xdna_prep_text(ColiXdnaPrepState state);++/* Create an empty object. Allocates no payload: creation is not preparation. */+ColiXdnaPrepared *coli_xdna_prepared_create(void);++/* Free payload and object, clear the caller's handle. Safe on NULL, on a+ * never-allocated object, mid-PREPARING, on INVALID, on VALID, and repeatedly. */+void coli_xdna_prepared_release(ColiXdnaPrepared **p);++/* Begin a complete preparation cycle for a BF16 B[K,N] image. Allocates or+ * reuses capacity, guarantees 4096-byte pointer alignment, and moves to+ * PREPARING. Returns 0 without changing state on a rejected request.+ *+ * Beginning is the ONLY way to reach PREPARING, and publication is the only way+ * out, so a caller cannot arrive at VALID by allocating. */+int coli_xdna_prepare_begin(ColiXdnaPrepared *p, unsigned k, unsigned n,+ ColiXdnaDtype prepared_dtype);++/* The writable destination, and only while PREPARING. NULL in every other+ * state, so a published image cannot be rewritten behind its own back. */+void *coli_xdna_prepare_dest(ColiXdnaPrepared *p);++/* PREPARING -> VALID. Refused from any other state: an INVALID image can never+ * shortcut to VALID, it must go through a complete new cycle. */+int coli_xdna_prepare_publish_success(ColiXdnaPrepared *p);++/* PREPARING -> INVALID. Capacity is retained; the bytes stay accounted. */+void coli_xdna_prepare_publish_failure(ColiXdnaPrepared *p);++/* VALID -> INVALID, keeping capacity. For a later weight replacement, format+ * change or eviction; this slice implements no trigger for it. */+int coli_xdna_prepared_invalidate(ColiXdnaPrepared *p);++/* Drop retained capacity, returning the object to UNPREPARED with zero bytes.+ * Validity and allocation lifetime are separate, so this is separate too. */+void coli_xdna_prepared_free_buffer(ColiXdnaPrepared *p);++ColiXdnaPrepState coli_xdna_prepared_state(const ColiXdnaPrepared *p);+/* Logical payload bytes currently allocated: K*N*sizeof(bf16), not a rounded+ * allocator reservation. Non-zero for a retained INVALID buffer. */+size_t coli_xdna_prepared_bytes(const ColiXdnaPrepared *p);+unsigned coli_xdna_prepared_k(const ColiXdnaPrepared *p);+unsigned coli_xdna_prepared_n(const ColiXdnaPrepared *p);++/* Defensive validator. The allocator guarantees alignment, but a buffer that+ * arrives from elsewhere, from a pool, or at an offset does not -- and a+ * misaligned pointer fails at the XRT boundary with a message about video+ * memory, which points at entirely the wrong subsystem. */+int coli_xdna_pointer_alignment_ok(const void *p);++/* Engine-side host accounting. These are HOST bytes: not VRAM, not NPU memory,+ * not an XRT device allocation. */+size_t coli_xdna_prepared_total_bytes(void);+int coli_xdna_prepared_live_objects(void);+/* Install a registry for tests; NULL restores the production table. */void coli_xdna_test_set_registry(const ColiXdnaArtifact *rows, int count);-/* Both must stay 0 for the whole of this slice. */+/* All four must stay 0 for the whole of this slice. */int coli_xdna_test_device_opens(void);int coli_xdna_test_helper_calls(void);+int coli_xdna_test_userptr_wraps(void);+int coli_xdna_test_conversions(void);#ifdef __cplusplus}diff --git a/c/colibri.c b/c/colibri.cindex 4a1d8f90..4aad3b23 100644--- a/c/colibri.c+++ b/c/colibri.c@@ -100,6 +100,11 @@ static inline void omp_set_num_threads(int n){ (void)n; }#ifdef COLI_VULKAN#include "backend_vulkan.h"#endif+#ifdef COLI_XDNA+/* Optional AMD XDNA2 lane. This header pulls in no XRT: the engine owns the+ * prepared-host state, and XRT lives only behind an optional helper DLL. */+#include "backend_xdna.h"+#endif/* Declared unconditionally (not just under COLI_METAL): on a non-Metal build they just sit* at 0 forever, which is the correct value there (no Metal backend => never enabled, and* COLI_METAL_MOE_EXACT is only parsed under COLI_METAL). Kept outside the #ifdef so@@ -250,6 +255,14 @@ typedef struct {#endif#ifdef COLI_VULKANColiVkTensor *vk; int vk_eligible; /* resident on the Vulkan expert tier */+#endif+#ifdef COLI_XDNA+ /* Derived, disposable BF16 host image for the XDNA lane. NULL for an+ * ordinary tensor and created only when preparation is actually requested:+ * loading a model allocates nothing here. Deliberately a single opaque+ * pointer rather than an *_eligible flag -- allocation, validity and byte+ * consumption vary independently and live inside the object. */+ ColiXdnaPrepared *xdna;#endifint cuda_eligible, cuda_device; /* resident tensor, never a reused expert slot *//* #767: the row count of the smallest call that has failed on this tensor, or 0 if@@ -672,6 +685,18 @@ static void cuda_disabled_note(void){static int g_cuda_e8_ready; /* codebook published to the devices (see cuda_boot) */static int g_cuda_fp8_ready; /* e4m3 LUT published to the devices (see cuda_boot) */#endif+#ifdef COLI_XDNA+/* Drop a QT's derived XDNA host image. The authoritative fmt=4 weight (q4, s)+ * is untouched: only the derived state goes. Used when an expert slot is reused+ * for a DIFFERENT expert, where a stale prepared image would otherwise be a+ * silently wrong weight rather than a missing one.+ *+ * Deliberately outside the COLI_VULKAN guard: the XDNA lane is independent of+ * whether Vulkan is compiled in. */+static void qt_xdna_reset(QT *t){+ if(t->xdna) coli_xdna_prepared_release(&t->xdna);+}+#endif#ifdef COLI_VULKAN/* Drop a QT's Vulkan-resident copy (slot reused for a different expert). */static void qt_vk_reset(QT *t){@@ -2709,6 +2734,12 @@ static int expert_load_impl(Model *m, int layer, int eid, ESlot *s, int fatal, i* Keep its tier assignment, but invalidate the old device weights. */if(s->eid!=eid){ qt_cuda_reset(&s->g); qt_cuda_reset(&s->u); qt_cuda_reset(&s->d); }#endif+#ifdef COLI_XDNA+ /* Same reuse hazard as the GPU tiers: a stale prepared BF16 image belongs to+ * the OLD expert's weights, so reusing the slot without dropping it would+ * compute a wrong answer rather than fail. */+ if(s->eid!=eid){ qt_xdna_reset(&s->g); qt_xdna_reset(&s->u); qt_xdna_reset(&s->d); }+#endif#ifdef COLI_VULKAN/* Slot reused for a different expert: free the stale VK-resident weights so the new* expert re-uploads instead of computing with the old expert's tensors. */@@ -3267,6 +3298,12 @@ static int uring_load_add(UringBatch *b,Model *m,int layer,int eid,ESlot *s,intreturn uring_load_error(l,ENOTSUP,"URING requires quantized expert tensors"),li;#ifdef COLI_CUDAif(s->eid!=eid){ qt_cuda_reset(&s->g); qt_cuda_reset(&s->u); qt_cuda_reset(&s->d); }+#endif+#ifdef COLI_XDNA+ /* Same reuse hazard as the GPU tiers: a stale prepared BF16 image belongs to+ * the OLD expert's weights, so reusing the slot without dropping it would+ * compute a wrong answer rather than fail. */+ if(s->eid!=eid){ qt_xdna_reset(&s->g); qt_xdna_reset(&s->u); qt_xdna_reset(&s->d); }#endiffor(int k=0;k<3;k++){l->tw[k]=st_find(&m->S,nm[k]);diff --git a/c/tests/test_backend_loader.py b/c/tests/test_backend_loader.pyindex 435c12b7..3a5cbab6 100644--- a/c/tests/test_backend_loader.py+++ b/c/tests/test_backend_loader.py@@ -2621,7 +2621,11 @@ class XdnaOptionalBindingTest(unittest.TestCase):cls.absent.parent.mkdir(parents=True, exist_ok=True)cls.harness = root / "xdna_harness.exe"- gcc(["-O0", "-I", str(HERE), str(harness_src), "-o", str(cls.harness)],+ # c/compat.h:80 makes -D_FILE_OFFSET_BITS=64 mandatory on Windows, and the+ # project CFLAGS always carry it. Compiling the loader the way the build+ # actually compiles it keeps this owner honest rather than lenient.+ gcc(["-O0", "-D_FILE_OFFSET_BITS=64", "-I", str(HERE), str(harness_src),+ "-o", str(cls.harness)],"building the XDNA loader harness")@classmethod@@ -2737,7 +2741,8 @@ class XdnaDefaultBuildIndependenceTest(unittest.TestCase):def test_loader_compiles_without_any_xrt_include_path(self):with tempfile.TemporaryDirectory(prefix="coli xdna nodep ") as tmp:obj = Path(tmp) / "backend_xdna.o"- cmd = ["gcc", "-O0", "-c", str(HERE / "backend_xdna.c"), "-o", str(obj)]+ cmd = ["gcc", "-O0", "-D_FILE_OFFSET_BITS=64",+ "-c", str(HERE / "backend_xdna.c"), "-o", str(obj)]proc = subprocess.run(cmd, text=True, errors="replace",capture_output=True, timeout=300)self.assertEqual(proc.returncode, 0,diff --git a/c/tests/test_xdna_prepared_state.c b/c/tests/test_xdna_prepared_state.cnew file mode 100644index 00000000..b64c7fc5--- /dev/null+++ b/c/tests/test_xdna_prepared_state.c@@ -0,0 +1,361 @@+/* Engine-owned XDNA prepared-host state: allocation, validity and lifetime.+ *+ * The prepared BF16 image is DERIVED state. The authoritative weight is the+ * stored fmt=4 tensor and nothing here may touch it. These tests own three+ * things that must never collapse into one another: whether memory is+ * ALLOCATED, whether its contents are VALID, and how many host bytes are+ * consumed. A buffer can be allocated and invalid; an invalid buffer still+ * costs memory; and no amount of successful allocation makes contents valid.+ *+ * Nothing here converts anything, opens a device, wraps a pointer or calls the+ * helper. Contents are deterministic filler used only to prove that STATE, not+ * content, decides validity.+ */++#include "../backend_xdna.c"++#include <stdio.h>+#include <string.h>+#include <stdlib.h>+#include <stdint.h>++static int g_fail = 0;++static void ck(int cond, const char *what){+ printf(" %-60s %s\n", what, cond ? "ok" : "FAIL");+ if(!cond) g_fail = 1;+}++#define K_ 6144u+#define N_ 2048u++/* ---- allocation and alignment ------------------------------------------ */+static void test_alloc_alignment(void){+ printf("aligned allocation\n");+ ColiXdnaPrepared *p = coli_xdna_prepared_create();+ ck(p != NULL, "prepared object created");+ ck(coli_xdna_prepared_state(p) == COLI_XDNA_PREP_UNPREPARED,+ "a new object is UNPREPARED");+ ck(coli_xdna_prepared_bytes(p) == 0, "a new object owns no bytes");++ ck(coli_xdna_prepare_begin(p, K_, N_, COLI_XDNA_DT_BF16) == 1, "begin succeeds");+ void *d = coli_xdna_prepare_dest(p);+ ck(d != NULL, "a writable destination exists while PREPARING");+ ck(((uintptr_t)d % 4096u) == 0, "destination pointer is 4096-aligned");+ ck(coli_xdna_pointer_alignment_ok(d) == 1, "defensive validator accepts it");+ ck(coli_xdna_prepared_bytes(p) == (size_t)K_ * N_ * 2u,+ "logical bytes are K*N*sizeof(bf16)");+ coli_xdna_prepared_release(&p);+ ck(p == NULL, "release nulls the caller's handle");+}++/* A logical payload that is deliberately NOT a page multiple. The pointer must+ * still be aligned; the SIZE must not be rounded up behind the caller's back. */+static void test_non_page_multiple_size(void){+ printf("non-page-multiple payload\n");+ ColiXdnaPrepared *p = coli_xdna_prepared_create();+ /* 3 * 5 * 2 = 30 bytes */+ ck(coli_xdna_prepare_begin(p, 3, 5, COLI_XDNA_DT_BF16) == 1,+ "30-byte payload accepted");+ ck(coli_xdna_prepared_bytes(p) == 30, "logical size reported exactly, not rounded");+ ck(((uintptr_t)coli_xdna_prepare_dest(p) % 4096u) == 0,+ "pointer still 4096-aligned for a 30-byte payload");+ coli_xdna_prepared_release(&p);+}++static void test_misaligned_validator(void){+ printf("defensive alignment validation\n");+ /* A non-owning validator: the offset pointer is inside memory we own, and+ * is never freed through it. */+ unsigned char *base = NULL;+ if(posix_memalign((void**)&base, 4096, 8192) != 0 || !base){+ ck(0, "fixture allocation"); return;+ }+ ck(coli_xdna_pointer_alignment_ok(base) == 1, "aligned base accepted");+ ck(coli_xdna_pointer_alignment_ok(base + 2) == 0, "offset 2 rejected");+ ck(coli_xdna_pointer_alignment_ok(base + 64) == 0, "offset 64 rejected");+ ck(coli_xdna_pointer_alignment_ok(base + 2048) == 0, "offset 2048 rejected");+ ck(coli_xdna_pointer_alignment_ok(base + 4096) == 1, "offset 4096 accepted");+ ck(coli_xdna_pointer_alignment_ok(NULL) == 0, "NULL rejected");+ compat_aligned_free(base);+}++/* ---- size safety -------------------------------------------------------- */+static void test_size_safety(void){+ printf("size and overflow safety\n");+ ColiXdnaPrepared *p = coli_xdna_prepared_create();++ ck(coli_xdna_prepare_begin(p, 0, N_, COLI_XDNA_DT_BF16) == 0, "K=0 rejected");+ ck(coli_xdna_prepare_begin(p, K_, 0, COLI_XDNA_DT_BF16) == 0, "N=0 rejected");+ ck(coli_xdna_prepare_begin(p, 0, 0, COLI_XDNA_DT_BF16) == 0, "zero size rejected");++ /* Genuine size_t overflow: 0xFFFFFFFF^2 * 2 exceeds SIZE_MAX on 64-bit.+ * Unchecked, this wraps to a small plausible number and the allocator hands+ * back a buffer far too small for what the caller will write -- the worst+ * possible outcome, because it succeeds. */+ ck(coli_xdna_prepare_begin(p, 0xFFFFFFFFu, 0xFFFFFFFFu, COLI_XDNA_DT_BF16) == 0,+ "product exceeding SIZE_MAX rejected");+ ck(coli_xdna_prepare_begin(p, 0xFFFFFFFFu, 0x80000000u, COLI_XDNA_DT_BF16) == 0,+ "product whose doubling exceeds SIZE_MAX rejected");++ /* Representable but unsatisfiable. Not an arithmetic error, so it must not+ * be reported as one: the allocator refuses and the object stays clean.+ * (No arbitrary size cap is imposed here -- a ceiling would be policy, and+ * policy is not this slice's to invent.) */+ ck(coli_xdna_prepare_begin(p, 0xFFFFFFFu, 0xFFFFFFFu, COLI_XDNA_DT_BF16) == 0,+ "unsatisfiable allocation fails cleanly");+ ck(coli_xdna_prepare_begin(p, K_, N_, COLI_XDNA_DT_F32) == 0,+ "non-BF16 prepared dtype rejected");+ ck(coli_xdna_prepare_begin(p, K_, N_, COLI_XDNA_DT_NONE) == 0,+ "invalid dtype rejected");++ ck(coli_xdna_prepared_state(p) == COLI_XDNA_PREP_UNPREPARED,+ "every rejection leaves the object UNPREPARED");+ ck(coli_xdna_prepared_bytes(p) == 0, "no bytes were accounted for a rejection");+ coli_xdna_prepared_release(&p);+}++/* ---- the state machine -------------------------------------------------- */+static void test_transitions(void){+ printf("state transitions\n");+ ColiXdnaPrepared *p = coli_xdna_prepared_create();++ /* Allocation is not validity. This is the load-bearing separation. */+ coli_xdna_prepare_begin(p, K_, N_, COLI_XDNA_DT_BF16);+ ck(coli_xdna_prepared_state(p) == COLI_XDNA_PREP_PREPARING,+ "begin moves UNPREPARED -> PREPARING");+ ck(coli_xdna_prepared_state(p) != COLI_XDNA_PREP_VALID,+ "a successful allocation is NOT valid");++ ck(coli_xdna_prepare_publish_success(p) == 1, "PREPARING -> VALID on publish");+ ck(coli_xdna_prepared_state(p) == COLI_XDNA_PREP_VALID, "state is VALID");++ /* No API may hand out a writable destination for a published image. */+ ck(coli_xdna_prepare_dest(p) == NULL, "no writable destination once VALID");++ ck(coli_xdna_prepared_invalidate(p) == 1, "VALID -> INVALID");+ ck(coli_xdna_prepared_state(p) == COLI_XDNA_PREP_INVALID, "state is INVALID");++ /* THE invariant: no shortcut back to valid. */+ ck(coli_xdna_prepare_publish_success(p) == 0,+ "INVALID cannot be published straight to VALID");+ ck(coli_xdna_prepared_state(p) == COLI_XDNA_PREP_INVALID, "still INVALID after refusal");++ /* A complete new cycle is the only way back. */+ ck(coli_xdna_prepare_begin(p, K_, N_, COLI_XDNA_DT_BF16) == 1,+ "INVALID -> PREPARING via a new cycle");+ ck(coli_xdna_prepare_publish_success(p) == 1, "PREPARING -> VALID again");++ coli_xdna_prepared_release(&p);+}++static void test_illegal_transitions(void){+ printf("illegal transitions fail closed\n");+ ColiXdnaPrepared *p = coli_xdna_prepared_create();++ ck(coli_xdna_prepare_publish_success(p) == 0,+ "UNPREPARED cannot publish success");+ ck(coli_xdna_prepared_state(p) == COLI_XDNA_PREP_UNPREPARED, "still UNPREPARED");++ ck(coli_xdna_prepared_invalidate(p) == 0, "UNPREPARED cannot be invalidated");++ coli_xdna_prepare_begin(p, K_, N_, COLI_XDNA_DT_BF16);+ coli_xdna_prepare_publish_success(p);+ /* Beginning again on a VALID image is a full re-preparation, and must not+ * leave the old image reachable as valid while it is being overwritten. */+ ck(coli_xdna_prepare_begin(p, K_, N_, COLI_XDNA_DT_BF16) == 1,+ "re-begin on a VALID image is allowed");+ ck(coli_xdna_prepared_state(p) == COLI_XDNA_PREP_PREPARING,+ "and it is PREPARING, not VALID, during the rewrite");++ coli_xdna_prepared_release(&p);+}++/* ---- failure publication ------------------------------------------------ */+static void test_failure_publication(void){+ printf("failure publication\n");+ ColiXdnaPrepared *p = coli_xdna_prepared_create();+ coli_xdna_prepare_begin(p, 64, 64, COLI_XDNA_DT_BF16);++ /* Poison the destination, then fail. Content is deliberately garbage: the+ * point is that STATE decides validity, not what the bytes happen to be. */+ unsigned char *d = (unsigned char*)coli_xdna_prepare_dest(p);+ memset(d, 0xAB, coli_xdna_prepared_bytes(p));++ coli_xdna_prepare_publish_failure(p);+ ck(coli_xdna_prepared_state(p) == COLI_XDNA_PREP_INVALID,+ "PREPARING -> INVALID on failure");+ ck(coli_xdna_prepare_publish_success(p) == 0,+ "poisoned INVALID buffer cannot be republished as VALID");+ ck(coli_xdna_prepare_dest(p) == NULL, "INVALID exposes no writable destination");++ /* Capacity may be retained; the bytes are still consumed. */+ ck(coli_xdna_prepared_bytes(p) > 0,+ "an INVALID but retained allocation still consumes host bytes");++ coli_xdna_prepared_release(&p);+}++/* ---- allocation vs validity vs consumption ------------------------------ */+static void test_three_independent_axes(void){+ printf("allocation, validity and consumption are independent\n");+ ColiXdnaPrepared *p = coli_xdna_prepared_create();++ ck(coli_xdna_prepared_bytes(p) == 0 &&+ coli_xdna_prepared_state(p) == COLI_XDNA_PREP_UNPREPARED,+ "no allocation, not valid, no bytes");++ coli_xdna_prepare_begin(p, 128, 128, COLI_XDNA_DT_BF16);+ ck(coli_xdna_prepared_bytes(p) == 128*128*2 &&+ coli_xdna_prepared_state(p) == COLI_XDNA_PREP_PREPARING,+ "allocated, not valid, bytes consumed");++ coli_xdna_prepare_publish_failure(p);+ ck(coli_xdna_prepared_bytes(p) == 128*128*2 &&+ coli_xdna_prepared_state(p) == COLI_XDNA_PREP_INVALID,+ "allocated, INVALID, bytes still consumed");++ coli_xdna_prepared_free_buffer(p);+ ck(coli_xdna_prepared_bytes(p) == 0 &&+ coli_xdna_prepared_state(p) == COLI_XDNA_PREP_UNPREPARED,+ "capacity dropped: no bytes, back to UNPREPARED");++ coli_xdna_prepared_release(&p);+}++/* ---- release ------------------------------------------------------------ */+static void test_release_lifetime(void){+ printf("release lifetime\n");+ ColiXdnaPrepared *p = NULL;++ coli_xdna_prepared_release(&p); /* NULL handle */+ ck(p == NULL, "release on NULL is safe");++ p = coli_xdna_prepared_create();+ coli_xdna_prepared_release(&p);+ ck(p == NULL, "release of a never-allocated object is safe");++ p = coli_xdna_prepared_create();+ coli_xdna_prepare_begin(p, 32, 32, COLI_XDNA_DT_BF16);+ coli_xdna_prepared_release(&p); /* released mid-PREPARING */+ ck(p == NULL, "release during PREPARING is safe");++ p = coli_xdna_prepared_create();+ coli_xdna_prepare_begin(p, 32, 32, COLI_XDNA_DT_BF16);+ coli_xdna_prepare_publish_failure(p);+ coli_xdna_prepared_release(&p);+ ck(p == NULL, "release of an INVALID object is safe");++ p = coli_xdna_prepared_create();+ coli_xdna_prepare_begin(p, 32, 32, COLI_XDNA_DT_BF16);+ coli_xdna_prepare_publish_success(p);+ coli_xdna_prepared_release(&p);+ coli_xdna_prepared_release(&p); /* repeated */+ coli_xdna_prepared_release(&p);+ ck(p == NULL, "repeated release is safe and idempotent");++ ck(coli_xdna_prepared_live_objects() == 0, "no prepared object leaked");+ ck(coli_xdna_prepared_total_bytes() == 0, "no prepared bytes leaked");+}++/* ---- bounded stress ----------------------------------------------------- */+static void test_stress(void){+ printf("bounded allocation lifecycle stress\n");+ size_t peak = 0;+ for(int i = 0; i < 200; i++){+ ColiXdnaPrepared *p = coli_xdna_prepared_create();+ coli_xdna_prepare_begin(p, 64, 64, COLI_XDNA_DT_BF16);+ if(i & 1) coli_xdna_prepare_publish_failure(p);+ else coli_xdna_prepare_publish_success(p);+ if(coli_xdna_prepared_total_bytes() > peak) peak = coli_xdna_prepared_total_bytes();+ /* reuse the retained capacity through a complete new cycle */+ coli_xdna_prepare_begin(p, 64, 64, COLI_XDNA_DT_BF16);+ coli_xdna_prepare_publish_success(p);+ coli_xdna_prepared_invalidate(p);+ coli_xdna_prepared_release(&p);+ }+ printf(" peak accounted bytes %zu, live objects %d, final bytes %zu\n",+ peak, coli_xdna_prepared_live_objects(), coli_xdna_prepared_total_bytes());+ ck(peak > 0, "stress actually allocated");+ ck(coli_xdna_prepared_live_objects() == 0, "no object leaked across 200 cycles");+ ck(coli_xdna_prepared_total_bytes() == 0, "accounting returns to zero");+}++/* ---- the authoritative weight is untouched ------------------------------ */+static void test_fmt4_immutability(void){+ printf("authoritative fmt4 immutability\n");+ /* A synthetic stand-in for the authoritative tensor: the prepared-state API+ * must never see, take or free these. */+ unsigned char q4[512]; float scales[16];+ for(int i = 0; i < 512; i++) q4[i] = (unsigned char)(i * 7 + 1);+ for(int i = 0; i < 16; i++) scales[i] = 0.25f * (float)(i + 1);+ unsigned char q4_before[512]; float sc_before[16];+ memcpy(q4_before, q4, sizeof q4); memcpy(sc_before, scales, sizeof scales);+ const void *q4_ptr = q4; const void *sc_ptr = scales;++ ColiXdnaPrepared *p = coli_xdna_prepared_create();+ coli_xdna_prepare_begin(p, 64, 64, COLI_XDNA_DT_BF16);+ memset(coli_xdna_prepare_dest(p), 0x5A, coli_xdna_prepared_bytes(p));+ coli_xdna_prepare_publish_success(p);+ coli_xdna_prepared_invalidate(p);+ coli_xdna_prepare_begin(p, 64, 64, COLI_XDNA_DT_BF16);+ coli_xdna_prepare_publish_failure(p);+ coli_xdna_prepared_free_buffer(p);+ coli_xdna_prepared_release(&p);++ ck(memcmp(q4, q4_before, sizeof q4) == 0, "fmt4 packed bytes unchanged");+ ck(memcmp(scales, sc_before, sizeof scales) == 0, "scale block unchanged");+ ck(q4_ptr == (const void*)q4 && sc_ptr == (const void*)scales,+ "authoritative pointers unchanged");+}++/* ---- independence ------------------------------------------------------- */+static void test_independence(void){+ printf("helper and registry independence\n");+ coli_xdna_test_set_helper_path("C:/nonexistent/coli_xdna.dll");+ ck(coli_xdna_binding() == COLI_XDNA_ABSENT, "helper absent");++ ColiXdnaPrepared *p = coli_xdna_prepared_create();+ ck(coli_xdna_prepare_begin(p, 64, 64, COLI_XDNA_DT_BF16) == 1,+ "allocation works with no helper");+ ck(coli_xdna_prepare_publish_success(p) == 1, "publication works with no helper");+ ck(coli_xdna_prepared_state(p) == COLI_XDNA_PREP_VALID, "state is VALID");+ coli_xdna_prepared_release(&p);++ /* A statically qualified artifact does not create prepared state, and a+ * prepared image does not qualify an artifact. */+ ck(coli_xdna_prepared_live_objects() == 0,+ "registry lookup created no prepared object");++ coli_xdna_test_set_helper_path(NULL);+ ck(coli_xdna_test_helper_calls() == 0, "no helper entry point was called");+ ck(coli_xdna_test_device_opens() == 0, "no device was opened");+}++/* ---- what PREPARED_VALID must not be mistaken for ----------------------- */+static void test_no_runtime_readiness(void){+ printf("PREPARED_VALID is not runtime readiness\n");+ ck(!strcmp(coli_xdna_prep_text(COLI_XDNA_PREP_VALID), "PREPARED_VALID"),+ "the label says PREPARED, not READY");+ ck(coli_xdna_test_userptr_wraps() == 0, "no userptr wrap exists");+ ck(coli_xdna_test_conversions() == 0, "no fmt4 conversion was performed");+}++int main(void){+ test_alloc_alignment();+ test_non_page_multiple_size();+ test_misaligned_validator();+ test_size_safety();+ test_transitions();+ test_illegal_transitions();+ test_failure_publication();+ test_three_independent_axes();+ test_release_lifetime();+ test_stress();+ test_fmt4_immutability();+ test_independence();+ test_no_runtime_readiness();++ printf("test_xdna_prepared_state: %s\n", g_fail ? "FAIL" : "ok");+ return g_fail;+}diff --git a/c/tests/test_xdna_qt_state.c b/c/tests/test_xdna_qt_state.cnew file mode 100644index 00000000..5a36ab89--- /dev/null+++ b/c/tests/test_xdna_qt_state.c@@ -0,0 +1,97 @@+/* The XDNA prepared-state side pointer inside QT.+ *+ * This owner compiles the real engine with -DCOLI_XDNA so the QT field, its+ * reset helper and the expert-slot wiring are exercised as the engine actually+ * builds them -- the same #define main / #include seam c/tests/test_i4_grouped.c+ * uses to reach static engine internals.+ *+ * The properties under test are ownership properties: a tensor starts with no+ * derived state, nothing creates it implicitly, dropping it never touches the+ * authoritative weight, and exactly one owner ever frees it.+ */++#define main coli_glm_main_unused+#include "../colibri.c"+#undef main++#include <stdio.h>++static int g_fail = 0;++static void ck(int cond, const char *what){+ printf(" %-60s %s\n", what, cond ? "ok" : "FAIL");+ if(!cond) g_fail = 1;+}++int main(void){+ printf("QT xdna side pointer\n");++ /* A tensor built the way the loader builds one: authoritative fmt=4 bytes,+ * and no derived state of any kind. */+ static unsigned char q4[256];+ static float scales[8];+ for(int i = 0; i < 256; i++) q4[i] = (unsigned char)(i * 3 + 5);+ for(int i = 0; i < 8; i++) scales[i] = 0.5f * (float)(i + 1);++ QT t;+ memset(&t, 0, sizeof t);+ t.fmt = 4; t.I = 64; t.O = 4; t.gs = 64;+ t.q4 = q4; t.s = scales;++ ck(t.xdna == NULL, "a fresh tensor carries no prepared state");+ ck(coli_xdna_prepared_live_objects() == 0, "and none exists anywhere");++ /* Nothing implicit: asking the registry a question must not allocate. */+ ColiXdnaRequest q;+ memset(&q, 0, sizeof q);+ q.family = COLI_XDNA_FAMILY_MOE_SHARED_GATE_UP;+ q.m = 64; q.k = 6144; q.n = 2048;+ q.in_dtype = COLI_XDNA_DT_BF16; q.weight_dtype = COLI_XDNA_DT_BF16;+ q.out_dtype = COLI_XDNA_DT_F32;+ (void)coli_xdna_registry_lookup(&q);+ (void)coli_xdna_artifact_status(&q, NULL);+ ck(t.xdna == NULL, "a registry query creates no prepared state");+ ck(coli_xdna_prepared_live_objects() == 0, "still none anywhere");++ /* Explicit creation is the only way. */+ t.xdna = coli_xdna_prepared_create();+ ck(t.xdna != NULL, "prepared state attaches on explicit request");+ ck(coli_xdna_prepare_begin(t.xdna, 64, 64, COLI_XDNA_DT_BF16) == 1, "begin");+ ck(coli_xdna_prepare_publish_success(t.xdna) == 1, "publish");+ ck(coli_xdna_prepared_total_bytes() == 64*64*2, "bytes accounted while attached");++ /* The reset the expert-slot reuse path calls. It must take the derived+ * state and leave the authoritative weight exactly as it was. */+ unsigned char q4_before[256]; float sc_before[8];+ memcpy(q4_before, q4, sizeof q4); memcpy(sc_before, scales, sizeof scales);+ const void *q4_ptr = t.q4; const void *s_ptr = t.s;+ int fmt_before = t.fmt, I_before = t.I, O_before = t.O, gs_before = t.gs;++ qt_xdna_reset(&t);++ ck(t.xdna == NULL, "reset detaches the derived state");+ ck(coli_xdna_prepared_total_bytes() == 0, "and returns its bytes");+ ck(coli_xdna_prepared_live_objects() == 0, "and frees the object exactly once");+ ck(t.q4 == q4_ptr && t.s == s_ptr, "authoritative pointers untouched");+ ck(memcmp(q4, q4_before, sizeof q4) == 0, "fmt4 bytes untouched");+ ck(memcmp(scales, sc_before, sizeof scales) == 0, "scales untouched");+ ck(t.fmt == fmt_before && t.I == I_before && t.O == O_before && t.gs == gs_before,+ "QT metadata untouched");++ /* Repeated reset, and reset of a tensor that never had derived state. */+ qt_xdna_reset(&t);+ qt_xdna_reset(&t);+ ck(t.xdna == NULL, "repeated reset is safe");++ QT plain;+ memset(&plain, 0, sizeof plain);+ plain.fmt = 4; plain.I = 8; plain.O = 8; plain.gs = 8;+ qt_xdna_reset(&plain);+ ck(plain.xdna == NULL, "reset of a tensor with no derived state is safe");++ ck(coli_xdna_prepared_live_objects() == 0, "no object leaked");+ ck(coli_xdna_prepared_total_bytes() == 0, "no bytes leaked");++ printf("test_xdna_qt_state: %s\n", g_fail ? "FAIL" : "ok");+ return g_fail;+}