Skip to content

armgit / janas

Public Imported from GitHub
0

37 tok/s from Qwen3-Next-80B (48 GB) on a 32 GB laptop, 24 without drafts vs 2.8 for llama.cpp; reading 62 vs 16 tok/s. Faster than llama.cpp on all 13 models compared in Q4_K_M. LLMs bigger than your RAM, pure C, CPU or GPU.

Release 2026-10-01: experts read ahead, steadier drafts, every weight type on the GPU

camauri699f23236b8a
diff --git a/ChangeLog.md b/ChangeLog.md
index b4052c9..7a3ba3a 100644
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -2,6 +2,74 @@
> Curated, user-facing summary of completed work, newest first.
+## [2026-10-01] - Experts read ahead, steadier drafts, every weight type on the GPU
+
+- **The drafts no longer switch themselves off for good.** The planner of
+ the multi-token prediction drafts judges each number of drafts by the
+ cost of a pass of that many tokens, as last timed. One pass of two
+ tokens timed while the disk was busy made it refuse every draft, and with
+ no drafts that cost was never timed again: in some sessions the drafts
+ stopped after the first hundred tokens and never came back, which is why
+ the same chat ran at 22 tokens/s one time and 26 the next. It now drafts
+ one pass in sixteen even when it chose none, as the drafts copied from
+ the conversation already did. Qwen3-Next-80B in `janas-chat`, three
+ replies of 600 tokens, two rounds alternated with the release of 28
+ September: 26.0 tokens/s (25.5-26.5) against 24.3 (22.5-26.1), +7%.
+- **The same seed gives the same conversation, drafts or not.** A reply
+ cut short - by `--max`, or stopped - after a pass that had accepted
+ drafts past its end dropped those tokens but not the random numbers drawn
+ for them, so every later reply of the conversation came out different
+ from the one without drafts. The numbers are given back now: with the
+ same seed the replies are identical with and without drafts, cut or not.
+- **A reply's statistics count the experts read ahead**; left out, they
+ made the cache look warmer and the disk idler than they were.
+- **Experts read ahead, where the cache misses many.** A mixture whose
+ experts do not fit in memory waited for the disk one layer at a time:
+ Qwen3-Next-80B with every bit and a 4 GiB cache spent half of each token
+ waiting, with the disk busy only 60% of the time. Now the next layer's
+ router is applied ahead, and of its first ten experts up to two not in
+ the cache are read while the current layer computes (on that model the
+ prediction held 91% of the experts chosen). Reading ahead costs on every
+ token and pays only when the cache misses many experts, so it turns
+ itself on above 60 missed experts a token and off below 40. Qwen3-Next-80B,
+ every bit, a fresh cache, three rounds alternated with it off: 4 GiB
+ 10.9-11.1 to 11.7-11.8 tokens/s (+6%), 8 GiB 15.6-15.7 to 16.2-16.3
+ (+4%); with a warm 20 GiB cache it never turns on and the speed is the
+ same; in `janas-chat`, with a 4 GiB cache and every expert, 12.6
+ tokens/s against 12.1 of the release of 28 September (+3.6%). The
+ results are the same bits, on or off. `JANAS_PREFETCH=0` turns it off.
+- **The expert cache without transparent-huge-page advice.** With the
+ kernel's huge pages on "always" and their defrag on "madvise" (the
+ common setting), the advice made every first write to the cache try a
+ synchronous compaction of memory, which looked like waiting for the
+ disk. Without it, a reply of Qwen3-Next-80B from a fresh 20 GiB cache
+ went from 17.5-17.7 to 19.7 tokens/s, and a prompt from a warm one from
+ 51 to 55; other sizes are even. `JANAS_ARENA_HUGE=1` asks for huge pages
+ as before.
+- **Every quantized type on the GPU**: Q8_0, Q4_0, Q4_1, Q5_1, IQ4_NL,
+ IQ4_XS, Q3_K and IQ3_S join Q4_K, Q5_K and Q6_K, bit for bit the CPU's
+ results (`gpu_check`: 1680 shapes). Gemma-4-26B keeps its attention, its
+ dense feed-forward and its output head in Q8_0; Qwen3.5-9B's "UD" mix
+ keeps some layers in IQ4_XS and Q8_0.
+- **A whole token on the GPU, as an experiment** (`JANAS_GPU_TOKEN=1`,
+ dense Qwen3 models, integrated GPUs): every step of a token - norms,
+ RoPE, attention, products, output head - in one submission, recorded
+ once. `JANAS_GPU_BLOCK=1` does the same for blocks of up to 64 tokens (a
+ prompt, the drafts a speculative pass checks), the same bits as one token
+ at a time; `JANAS_GPU_REPACK=1` gives the Q6_K weights an aligned copy
+ for it (some 0.8 GB more for Qwen3-4B). On the development laptop's
+ integrated GPU it runs level with the CPU: Qwen3-4B writes 24.3-24.7
+ tokens/s against the CPU's 24.8, and in blocks reads a 2000-token prompt
+ at 107 tokens/s where a token at a time gave 61. It is off unless asked
+ for.
+- Tools for measures: `llm_gen cpus=` puts the compute threads on chosen
+ CPUs; `bench_long` reports how long the disk was busy beside how long
+ the engine waited for it, prints the experts' bits and count in use
+ (`BENCH_EXACT=1` keeps every bit and the model's own count), and can
+ save the prompt and the reply; the library can hand a caller the
+ experts each layer routes a token to, and a prediction of the next
+ layer's.
+
## [2026-09-28] - More of the work on the GPU
- **The experts' weights go to the GPU too** once every expert of every
diff --git a/INSTALL.md b/INSTALL.md
index bd58c3f..a6f689e 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -85,6 +85,8 @@ It takes a few minutes: it measures prompt processing and generation speed for e
## Troubleshooting
- `JANAS_GPU=0` turns the GPU off; `JANAS_GPU_DEVICE=integrated` or `discrete` picks one when there are both.
+- `JANAS_PREFETCH=0` never reads experts ahead (by default it turns itself on when the cache misses many experts a token).
+- `JANAS_ARENA_HUGE=1` asks the kernel for huge pages for the expert cache, as before 30 September 2026 (with transparent huge pages on `always` and their defrag on `madvise` it made the first writes to the cache slow).
- `JANAS_KERNELS=avx2` uses the AVX2 kernels even where AVX-VNNI is available.
- `JANAS_TUNE=0` turns self-tuning off (fixed defaults); delete `~/.cache/janas/tuning.txt` to start tuning from scratch.
- `JANAS_TUNE_THREADS=0` keeps every usable thread instead of letting the first passes choose between every thread, one per performance core and the performance cores' threads; the choice, once made, is kept for that machine and model.
diff --git a/README.md b/README.md
index 40bf98f..3c2f666 100644
--- a/README.md
+++ b/README.md
@@ -48,7 +48,7 @@ Everything in this repository was written and measured on:
- **Linux Debian 13**, x86-64
- **Intel Core Ultra 9 185H** (6 performance cores, 8 efficiency, 2 low-power; AVX2, FMA, F16C, AVX-VNNI; integrated Arc GPU)
-- **32 GB** of RAM
+- **32 GB** of DDR5 RAM
- **1 TB NVMe SSD** (about 5.7 GB/s reading)
Everything the engine does is chosen from what it measures, so another machine
@@ -134,7 +134,13 @@ report from `janas-bench` is the single most useful thing you can send back**
where it has one, from the conversation where it does not, or from a small
model of the same family given with `--draft`.
- **Optional GPU** (Vulkan 1.3, integrated or discrete), used only where the
- engine measures that it helps. Results are identical with and without it.
+ engine measures that it helps, for every quantized type the CPU reads.
+ Results are identical with and without it.
+- **Experts read ahead** when the expert cache is too small for the model:
+ the next layer's router is applied early and the experts it picks that
+ are not in memory are read from disk while the current layer computes.
+ It turns itself on only when the cache misses many experts a token
+ (Qwen3-Next-80B with a 4 GiB cache: +6%) and changes no result.
On the machine above, with nothing else running, `janas-bench` reports this:
@@ -424,13 +430,24 @@ only where the token the model itself sampled is the very same one - at the
first disagreement the guess is thrown away and the model's own token stands.
So no wrong guess can survive into the text, and with the same seed the reply
is the one you would have got without any of it - checked on every run of the
-tests, 256 tokens with drafts and 256 without, from one seed, identical. On
+tests, 256 tokens with drafts and 256 without, from one seed, identical, and
+in `janas-chat` itself over a conversation of three replies cut at 600
+tokens, with and without drafts. How many guesses a pass checks is decided
+from what passes have cost on this machine, and a pass with a guess is still
+tried now and then when the engine has stopped guessing, so that a moment of
+a busy disk does not switch the guesses off for the rest of the session
+(until 1 October 2026 it could: the same chat of Qwen3-Next-80B then ran at
+22 tok/s one time and 26 the next). On
the development laptop `--mtp` takes Qwen3-Next-80B-A3B from 23 tok/s to 36
and Qwen3.5-9B from 13 to 22 on an English explanation, and Gemma 4's
assistants take its four models about one and a half times faster on an
Italian chat reply (E4B from 18 tok/s to 26, the 12B from 8.5 to 12.9);
how much it gives depends on the text, and on Italian prose a small Qwen
-gains little.
+gains little. It gives nothing either where the expert cache is much smaller
+than the model: two tokens in a pass call more experts than one, and the
+disk is already the limit (Qwen3-Next-80B with a 4 GiB cache: a run whose
+guesses had stopped after the first reply wrote at 12.75 tok/s, the five
+that kept them at 12.05-12.55).
`--no-spec` and `/spec off` turn it off; they buy nothing but time, and are
there to measure with.
diff --git a/include/janas/llm.h b/include/janas/llm.h
index ec522b8..7a3197c 100644
--- a/include/janas/llm.h
+++ b/include/janas/llm.h
@@ -558,7 +558,8 @@ struct janas_llm_chat_stats {
double output_seconds; /* writing the reply */
double total_seconds; /* from send to the end of the reply */
/* the routed experts of message and reply: those used, those read from
- the file (not in the cache), the bytes read, the time spent waiting */
+ the file (not in the cache, or read ahead for them), the bytes read
+ (reads ahead included, used or not), the time spent waiting */
uint64_t experts_used, experts_read, bytes_read;
double io_wait_seconds;
/* passes of the reply the engine ran without drafting although drafts
diff --git a/src/llm/api_reply.c b/src/llm/api_reply.c
index ffbeb72..ed35c93 100644
--- a/src/llm/api_reply.c
+++ b/src/llm/api_reply.c
@@ -113,8 +113,13 @@ void janas_api_update_stats(janas_llm_chat *c)
struct janas_expert_cache_stats cs;
janas_expert_cache_stats(janas_llm_model_cache(c->llm->m), &cs);
s->experts_used = cs.requests - c->cs0.requests;
- s->experts_read = cs.misses - c->cs0.misses;
- s->bytes_read = cs.bytes_read - c->cs0.bytes_read;
+ /* the experts read ahead count as read: they came from the file, and
+ left out they made the cache look warmer than it is and the disk
+ idler (1 Oct 2026: 108 GB "read" against 161 without them) */
+ s->experts_read =
+ cs.misses - c->cs0.misses + cs.prefetch_used - c->cs0.prefetch_used;
+ s->bytes_read = cs.bytes_read - c->cs0.bytes_read + cs.prefetch_bytes -
+ c->cs0.prefetch_bytes;
s->io_wait_seconds = cs.wait_seconds - c->cs0.wait_seconds;
/* the reading of the prompt, and the rest of what a reply costs */
uint32_t done = janas_llm_session_computed(c->s) - c->kv_from;
diff --git a/src/llm/expert_cache.c b/src/llm/expert_cache.c
index 6577cb0..9c25edd 100644
--- a/src/llm/expert_cache.c
+++ b/src/llm/expert_cache.c
@@ -27,6 +27,8 @@
#define URING_BATCH 4
/* and again from this many times the threads of the I/O pool on */
#define URING_DEEP_TIMES 4
+/* reads ahead at most, for one layer */
+#define PF_MAX 64
struct read_job {
uint64_t offset;
@@ -36,8 +38,9 @@ struct read_job {
struct janas_expert_cache {
const struct janas_jns *j;
- int level; /* 1 to 3: how much of a slot is read (see the header) */
- int fd; /* O_DIRECT, independent of the jns descriptor */
+ int level; /* 1 to 3: how much of a slot is read (see the header) */
+ int fd; /* O_DIRECT, independent of the jns descriptor */
+ int arena_foreign; /* the arena belongs to another (a GPU): not freed */
struct janas_pool *io;
uint64_t slot_bytes;
@@ -102,6 +105,22 @@ struct janas_expert_cache {
int outstanding; /* begin called, finish not yet (caller thread only) */
int stop;
int batch_rc;
+
+ /*
+ * Reads ahead (janas_expert_cache_prefetch), two sets: the engine reads
+ * ahead for layer l + 1 before layer l asks, so the set for l + 1 is
+ * made while the one for l still waits for its request. Each set has a
+ * ring of its own (by the layer's parity), so a request waits only for
+ * the reads ahead of its own layer, never for another layer's. The
+ * slots they fill are flagged (never a victim) until their layer's
+ * request settles them.
+ */
+ struct janas_uring *pf_ring[2];
+ uint8_t *pf_flag; /* per slot */
+ int32_t pf_slot[2][PF_MAX];
+ size_t pf_n[2];
+ uint32_t pf_layer[2];
+ int pf_inflight[2];
};
static double now(void)
@@ -165,6 +184,30 @@ static void push_front(struct janas_expert_cache *c, int32_t s)
c->tail = s;
}
+/* Last in line: the next to go (a read ahead not yet asked for). */
+static void push_back(struct janas_expert_cache *c, int32_t s)
+{
+ c->next[s] = NONE;
+ c->prev[s] = c->tail;
+ if (c->tail != NONE)
+ c->next[c->tail] = s;
+ c->tail = s;
+ if (c->head == NONE)
+ c->head = s;
+}
+
+static void layer_push_back(struct janas_expert_cache *c, int32_t s)
+{
+ uint32_t l = slot_layer(c, s);
+ c->lnext[s] = NONE;
+ c->lprev[s] = c->ltail[l];
+ if (c->ltail[l] != NONE)
+ c->lnext[c->ltail[l]] = s;
+ c->ltail[l] = s;
+ if (c->lhead[l] == NONE)
+ c->lhead[l] = s;
+}
+
static void touch(struct janas_expert_cache *c, int32_t s)
{
if (c->head != s) {
@@ -190,12 +233,12 @@ static int32_t victim(struct janas_expert_cache *c)
for (uint32_t d = 0; d < nl; d++) {
uint32_t l = (c->cur_layer + nl - d) % nl;
for (int32_t s = c->ltail[l]; s != NONE; s = c->lprev[s])
- if (c->stamp[s] != c->request)
+ if (c->stamp[s] != c->request && !c->pf_flag[s])
return s;
}
}
for (int32_t s = c->tail; s != NONE; s = c->prev[s])
- if (c->stamp[s] != c->request)
+ if (c->stamp[s] != c->request && !c->pf_flag[s])
return s;
return NONE;
}
@@ -447,15 +490,29 @@ struct janas_expert_cache *janas_expert_cache_create(const struct janas_jns *j,
c->lnext = malloc(n_slots * sizeof(int32_t));
c->lhead = malloc(((size_t)j->h.n_layer + 1) * sizeof(int32_t));
c->ltail = malloc(((size_t)j->h.n_layer + 1) * sizeof(int32_t));
+ c->pf_flag = calloc(n_slots, 1);
if (c->fd < 0 || !c->arena || !c->where || !c->key || !c->prev ||
!c->next || !c->stamp || !c->jobs || !c->lprev || !c->lnext ||
- !c->lhead || !c->ltail) {
+ !c->lhead || !c->ltail || !c->pf_flag) {
snprintf(err, err_len, "cannot allocate %zu slots of %llu bytes",
n_slots, (unsigned long long)slot_bytes);
janas_expert_cache_destroy(c);
return NULL;
}
- madvise(c->arena, arena_bytes, MADV_HUGEPAGE);
+ /*
+ * No MADV_HUGEPAGE: with the kernel's transparent huge pages on
+ * "always" and their defrag on "madvise" (as on the development
+ * laptop), a region so marked makes every first write to a page try a
+ * synchronous compaction of memory, which on a machine with fragmented
+ * memory fails and only costs. Measured on 30 Sep 2026 (Qwen3-Next-80B, a
+ * fresh 20 GiB cache): ~1,800-8,800 failed compactions a reply, decode
+ * 17.5 -> 19.7 tokens/s without it, prefill 51 -> 55, and no loss once
+ * the cache is warm (23.0-23.6 against 23.1-23.3) - the kernel still
+ * gives huge pages where they are free. JANAS_ARENA_HUGE=1 asks for
+ * them again.
+ */
+ if (getenv("JANAS_ARENA_HUGE") && atoi(getenv("JANAS_ARENA_HUGE")) > 0)
+ madvise(c->arena, arena_bytes, MADV_HUGEPAGE);
pthread_mutex_init(&c->api_lock, NULL);
pthread_mutex_init(&c->lock, NULL);
pthread_cond_init(&c->cond, NULL);
@@ -470,6 +527,14 @@ struct janas_expert_cache *janas_expert_cache_create(const struct janas_jns *j,
const char *ur = getenv("JANAS_URING");
if (!ur || atoi(ur) != 0)
c->ring = janas_uring_create(URING_QUEUE);
+ if (c->ring) {
+ c->pf_ring[0] = janas_uring_create(PF_MAX);
+ c->pf_ring[1] = c->pf_ring[0] ? janas_uring_create(PF_MAX) : NULL;
+ if (!c->pf_ring[1]) {
+ janas_uring_destroy(c->pf_ring[0]);
+ c->pf_ring[0] = NULL;
+ }
+ }
c->ring_batch = URING_BATCH;
/* deep enough that the kernel has made more readers than the pool has
threads: measured on 21 Sep 2026 at 32 reads, with eight of them */
@@ -513,6 +578,12 @@ void janas_expert_cache_destroy(struct janas_expert_cache *c)
}
free(c->warm_counts);
free(c->warm_order);
+ for (int p = 0; p < 2; p++) {
+ if (c->pf_ring[p] && c->pf_inflight[p]) /* no read may land after */
+ janas_uring_wait(c->pf_ring[p]);
+ janas_uring_destroy(c->pf_ring[p]);
+ }
+ free(c->pf_flag);
if (c->has_coordinator) {
pthread_mutex_lock(&c->lock);
while (c->pending)
@@ -528,7 +599,8 @@ void janas_expert_cache_destroy(struct janas_expert_cache *c)
pthread_mutex_destroy(&c->api_lock);
if (c->fd >= 0)
close(c->fd);
- free(c->arena);
+ if (!c->arena_foreign)
+ free(c->arena);
free(c->where);
free(c->key);
free(c->prev);
@@ -674,7 +746,8 @@ const uint8_t *janas_expert_cache_resident(struct janas_expert_cache *c,
if (c->n_slots < total || c->outstanding)
return NULL;
pthread_mutex_lock(&c->api_lock);
- int busy = c->has_warmer && !atomic_load(&c->warm_over);
+ int busy = (c->has_warmer && !atomic_load(&c->warm_over)) || c->pf_n[0] ||
+ c->pf_n[1];
pthread_mutex_lock(&c->lock);
busy |= c->pending;
pthread_mutex_unlock(&c->lock);
@@ -687,6 +760,34 @@ const uint8_t *janas_expert_cache_resident(struct janas_expert_cache *c,
return c->arena;
}
+int janas_expert_cache_rebase(struct janas_expert_cache *c, uint8_t *arena)
+{
+ pthread_mutex_lock(&c->api_lock);
+ int busy = c->outstanding || c->pf_n[0] || c->pf_n[1] ||
+ (c->has_warmer && !atomic_load(&c->warm_over));
+ pthread_mutex_lock(&c->lock);
+ busy |= c->pending;
+ pthread_mutex_unlock(&c->lock);
+ /* the new memory takes no O_DIRECT reads (a GPU driver's mapping):
+ the file opened again without it, for the loads that may still come */
+ char path[64];
+ snprintf(path, sizeof(path), "/proc/self/fd/%d", c->j->fd);
+ int fd = busy ? -1 : open(path, O_RDONLY | O_CLOEXEC);
+ if (fd < 0) {
+ pthread_mutex_unlock(&c->api_lock);
+ return -1;
+ }
+ memcpy(arena, c->arena, c->n_slots * c->slot_bytes);
+ close(c->fd);
+ c->fd = fd;
+ if (!c->arena_foreign)
+ free(c->arena);
+ c->arena = arena;
+ c->arena_foreign = 1;
+ pthread_mutex_unlock(&c->api_lock);
+ return 0;
+}
+
uint64_t janas_expert_cache_loads(const struct janas_expert_cache *c)
{
return atomic_load(&((struct janas_expert_cache *)c)->loads);
@@ -745,6 +846,97 @@ int janas_expert_cache_warm(struct janas_expert_cache *c,
return rc;
}
+/* A set of reads ahead complete (under api_lock); on an I/O error their
+ slots are emptied, so that nothing takes them for what they were to
+ hold. */
+static void pf_collect(struct janas_expert_cache *c, int p)
+{
+ if (!c->pf_inflight[p])
+ return;
+ double t0 = now();
+ int rc = janas_uring_wait(c->pf_ring[p]);
+ c->st.wait_seconds += now() - t0;
+ c->pf_inflight[p] = 0;
+ if (rc == 0)
+ return;
+ for (size_t i = 0; i < c->pf_n[p]; i++) {
+ int32_t s = c->pf_slot[p][i];
+ c->where[c->key[s]] = NONE;
+ layer_unlink(c, s);
+ c->key[s] = NONE;
+ c->filled--;
+ }
+}
+
+/* A set settled: complete, and no longer kept (under api_lock). */
+static void pf_settle(struct janas_expert_cache *c, int p)
+{
+ pf_collect(c, p);
+ for (size_t i = 0; i < c->pf_n[p]; i++)
+ c->pf_flag[c->pf_slot[p][i]] = 0;
+ c->pf_n[p] = 0;
+}
+
+int janas_expert_cache_prefetch(struct janas_expert_cache *c, uint32_t layer,
+ const uint32_t *ids, size_t n, size_t max)
+{
+ int p = (int)(layer & 1);
+ if (!c->pf_ring[p] || layer >= c->j->h.n_layer || c->outstanding)
+ return 0;
+ pthread_mutex_lock(&c->api_lock);
+ pf_settle(c, p); /* a set left over (its layer never asked) */
+ size_t base = (size_t)layer * c->j->h.n_expert, count = 0;
+ uint64_t bytes = c->j->layers[layer].level_bytes[c->level - 1];
+ for (size_t i = 0; i < n && count < max && count < PF_MAX; i++) {
+ if (ids[i] >= c->j->h.n_expert || c->where[base + ids[i]] != NONE)
+ continue;
+ int32_t s = victim(c);
+ if (s == NONE)
+ break;
+ if (c->key[s] != NONE) {
+ c->where[c->key[s]] = NONE;
+ layer_unlink(c, s);
+ } else {
+ c->filled++;
+ }
+ atomic_fetch_add(&c->loads, 1);
+ int64_t k = (int64_t)base + ids[i];
+ c->key[s] = k;
+ c->where[k] = s;
+ layer_push_back(c, s);
+ unlink_slot(c, s);
+ push_back(c, s);
+ if (janas_uring_read(c->pf_ring[p], c->fd,
+ c->arena + (size_t)s * c->slot_bytes, bytes,
+ janas_jns_expert_offset(c->j, layer, ids[i])) !=
+ 0) { /* the ring is full: this one stays unread */
+ c->where[k] = NONE;
+ layer_unlink(c, s);
+ c->key[s] = NONE;
+ c->filled--;
+ break;
+ }
+ c->pf_flag[s] = 1;
+ c->pf_slot[p][c->pf_n[p]++] = s;
+ count++;
+ }
+ if (count) {
+ c->pf_layer[p] = layer;
+ c->pf_inflight[p] = 1;
+ c->st.prefetch_reads += count;
+ c->st.prefetch_bytes += count * bytes;
+ if (janas_uring_submit(c->pf_ring[p]) != 0)
+ pf_settle(c, p); /* waits and empties what did not start */
+ }
+ pthread_mutex_unlock(&c->api_lock);
+ return (int)count;
+}
+
+int janas_expert_cache_can_prefetch(const struct janas_expert_cache *c)
+{
+ return c->pf_ring[0] != NULL;
+}
+
int janas_expert_cache_begin(struct janas_expert_cache *c, uint32_t layer,
const uint32_t *ids, size_t n,
const uint8_t **slots, uint8_t *ready)
@@ -762,6 +954,15 @@ int janas_expert_cache_begin(struct janas_expert_cache *c, uint32_t layer,
}
c->cur_layer = layer;
c->pass_asked += n;
+ /* reads ahead for this layer (or for one it went past): wait for them;
+ counted as used where this request asks for them, then settled. The
+ set of a later layer stays as it is, still in flight. */
+ int pf_here[2];
+ for (int p = 0; p < 2; p++) {
+ pf_here[p] = c->pf_n[p] && layer >= c->pf_layer[p];
+ if (pf_here[p])
+ pf_collect(c, p);
+ }
int32_t s[256];
size_t base = (size_t)layer * c->j->h.n_expert;
/* hits first, so that they are stamped before any victim is chosen */
@@ -773,10 +974,19 @@ int janas_expert_cache_begin(struct janas_expert_cache *c, uint32_t layer,
s[i] = c->where[base + ids[i]];
ready[i] = s[i] != NONE;
if (s[i] != NONE) {
+ /* a read ahead for this very layer: its set is settled here */
+ if (c->pf_flag[s[i]] == 1 && pf_here[layer & 1] &&
+ c->pf_layer[layer & 1] == layer) {
+ c->st.prefetch_used++;
+ c->pf_flag[s[i]] = 2; /* counted once */
+ }
touch(c, s[i]);
c->st.hits++;
}
}
+ for (int p = 0; p < 2; p++)
+ if (pf_here[p])
+ pf_settle(c, p); /* the unused ones: last in line, free to go */
int queued = 0;
for (size_t i = 0; i < n; i++)
if (s[i] == NONE) {
diff --git a/src/llm/expert_cache.h b/src/llm/expert_cache.h
index d7592ee..c15843c 100644
--- a/src/llm/expert_cache.h
+++ b/src/llm/expert_cache.h
@@ -27,6 +27,10 @@ struct janas_expert_cache_stats {
uint64_t warm_bytes; /* and for the filling in the background */
double io_seconds; /* wall time of the reads (in the background) */
double wait_seconds; /* time the caller actually waited for them */
+ /* reads ahead (janas_expert_cache_prefetch): experts read, of those
+ the ones their layer then asked for, and the bytes (not in
+ bytes_read) */
+ uint64_t prefetch_reads, prefetch_used, prefetch_bytes;
};
struct janas_expert_cache;
@@ -63,6 +67,14 @@ size_t janas_expert_cache_slots(const struct janas_expert_cache *c);
const uint8_t *janas_expert_cache_resident(struct janas_expert_cache *c,
uint64_t *bytes, uint64_t *loads);
uint64_t janas_expert_cache_loads(const struct janas_expert_cache *c);
+/*
+ * The arena moved to arena (n_slots x slot bytes, owned by the caller, not
+ * freed here), its contents copied, the file read without O_DIRECT from
+ * then on: for memory a GPU's driver allocated, which it reads faster
+ * than imported pages. Only when nothing is being read (as _resident); 0,
+ * or -1 with nothing changed.
+ */
+int janas_expert_cache_rebase(struct janas_expert_cache *c, uint8_t *arena);
/*
* Loads up to the cache capacity the experts with the highest counts
@@ -120,6 +132,24 @@ int janas_expert_cache_begin(struct janas_expert_cache *c, uint32_t layer,
const uint8_t **slots, uint8_t *ready);
int janas_expert_cache_finish(struct janas_expert_cache *c);
+/*
+ * Reads ahead up to max of the experts ids of the layer that are not in the
+ * cache, in the order given (the most likely first), while the caller goes
+ * on: for a layer that will ask soon. They take the least recently used
+ * slots and stay last in line, and until that layer's next request they are
+ * never taken back (a read in flight must not land in a slot given to
+ * another); that request waits for them, counts those it asks for as hits,
+ * and leaves the others first in line to go. Called between requests, not
+ * between begin and finish; one layer ahead at a time (a new call for
+ * another layer settles the one before). Only where the kernel has io_uring,
+ * on a ring of its own, so that a request never waits for reads ahead of
+ * another layer. Returns the number of reads started (0: none, or no ring).
+ */
+int janas_expert_cache_prefetch(struct janas_expert_cache *c, uint32_t layer,
+ const uint32_t *ids, size_t n, size_t max);
+/* Whether this cache can read ahead at all (the kernel has io_uring). */
+int janas_expert_cache_can_prefetch(const struct janas_expert_cache *c);
+
void janas_expert_cache_stats(const struct janas_expert_cache *c,
struct janas_expert_cache_stats *s);
void janas_expert_cache_reset_stats(struct janas_expert_cache *c);
diff --git a/src/llm/generate.c b/src/llm/generate.c
index 2f16ad9..f826027 100644
--- a/src/llm/generate.c
+++ b/src/llm/generate.c
@@ -640,6 +640,7 @@ int janas_llm_session_truncate(struct janas_llm_session *s, uint32_t n)
uint32_t kv = n > 0 ? n - 1 : 0;
if (kv < s->n_kv && janas_llm_model_recurrent(s->m))
return -1;
+ janas_sampler_rewind(s->smp, s->n - s->ret); /* drawn, never returned */
s->n = s->ret = n;
if (s->n_kv > kv)
s->n_kv = kv;
@@ -678,7 +679,11 @@ int janas_llm_session_append(struct janas_llm_session *s, const int32_t *tokens,
if (s->ret < s->n) {
/* drop the generated tokens nobody has seen; if the last kept one
already ran, run it again: its MTP row paired it with a dropped
- token */
+ token. Each was drawn, so the random sequence goes back as many:
+ otherwise a reply cut short with drafts accepted past the cut
+ left every later reply of the conversation drawn from other
+ numbers than without drafts (1 Oct 2026) */
+ janas_sampler_rewind(s->smp, s->n - s->ret);
s->n = s->ret;
if (s->n > 0 && s->n_kv > s->n - 1)
s->n_kv = s->n - 1;
@@ -920,6 +925,13 @@ int janas_llm_session_next(struct janas_llm_session *s, int32_t *token)
}
if (s->mtp && drafts_wanted && s->off_left == 0 && !probe) {
nd = plan ? plan_drafts(&s->pl, s->msurv, s->n_mdraft) : s->n_mdraft;
+ /* one pass in sixteen drafts anyway, as the copies do: a pass of
+ two tokens timed once while the disk was busy made the planner
+ refuse every draft, and with none its cost was never timed again
+ - Qwen3-Next-80B with a 4 GiB cache drafted 33 times in a
+ session and then never (1 Oct 2026) */
+ if (plan && nd == 0 && s->n_mdraft > 0 && s->st.passes % 16 == 0)
+ nd = 1;
memcpy(block + 1, s->mdraft, (size_t)nd * sizeof(int32_t));
}
if ((uint32_t)nd > s->cap - s->n)
diff --git a/src/llm/gpu.c b/src/llm/gpu.c
index 524f839..5a3bc65 100644
--- a/src/llm/gpu.c
+++ b/src/llm/gpu.c
@@ -16,174 +16,22 @@
#if defined(JANAS_GPU_SPV) && __has_include(<vulkan/vulkan.h>)
-#define VK_NO_PROTOTYPES
-#include <dlfcn.h>
-#include <immintrin.h>
-#include <pthread.h>
-#include <stdatomic.h>
-#include <unistd.h>
-#include <vulkan/vulkan.h>
-
-#include "q4k_matvec.h" /* janas_spv_q4k_matvec, generated by build.sh */
-#include "q6k_matvec.h" /* janas_spv_q6k_matvec */
-#include "q6kp_matvec.h" /* janas_spv_q6kp_matvec */
-#include "q5k_matvec.h" /* janas_spv_q5k_matvec */
-#include "expert_act.h" /* janas_spv_expert_act */
-
-#define MAX_REGIONS 32
-#define MAX_PENDING 64
-#define MAX_XCACHE 8
-#define X_STAGE_BYTES ((size_t)8 << 20)
-#define Y_STAGE_BYTES ((size_t)32 << 20)
-#define ROWS_PER_GROUP 64 /* local_size_x of the shader */
-#define NV_PER_GROUP 8 /* its NV */
-#define GPU_BLOCK 320 /* a Q8_K block in the shader's layout */
-#define SHARE_SLOTS 64
-#define MAX_GROUP 64
-
-/* instance-level functions, then device-level ones */
-#define VK_INSTANCE_FUNCS(X) \
- X(vkDestroyInstance) \
- X(vkEnumeratePhysicalDevices) \
- X(vkGetPhysicalDeviceProperties) \
- X(vkGetPhysicalDeviceProperties2) \
- X(vkGetPhysicalDeviceFeatures2) \
- X(vkGetPhysicalDeviceMemoryProperties) \
- X(vkGetPhysicalDeviceQueueFamilyProperties) \
- X(vkEnumerateDeviceExtensionProperties) \
- X(vkCreateDevice) \
- X(vkGetDeviceProcAddr)
-#define VK_DEVICE_FUNCS(X) \
- X(vkDestroyDevice) \
- X(vkGetDeviceQueue) \
- X(vkCreateBuffer) \
- X(vkDestroyBuffer) \
- X(vkGetBufferMemoryRequirements) \
- X(vkAllocateMemory) \
- X(vkFreeMemory) \
- X(vkBindBufferMemory) \
- X(vkMapMemory) \
- X(vkInvalidateMappedMemoryRanges) \
- X(vkFlushMappedMemoryRanges) \
- X(vkGetBufferDeviceAddress) \
- X(vkGetMemoryHostPointerPropertiesEXT) \
- X(vkCreateShaderModule) \
- X(vkDestroyShaderModule) \
- X(vkCreatePipelineLayout) \
- X(vkDestroyPipelineLayout) \
- X(vkCreateComputePipelines) \
- X(vkDestroyPipeline) \
- X(vkCreateCommandPool) \
- X(vkDestroyCommandPool) \
- X(vkAllocateCommandBuffers) \
- X(vkResetCommandBuffer) \
- X(vkBeginCommandBuffer) \
- X(vkEndCommandBuffer) \
- X(vkCmdBindPipeline) \
- X(vkCmdPushConstants) \
- X(vkCmdDispatch) \
- X(vkCmdPipelineBarrier) \
- X(vkCmdCopyBuffer) \
- X(vkWaitForFences) \
- X(vkCreateFence) \
- X(vkDestroyFence) \
- X(vkResetFences) \
- X(vkGetFenceStatus) \
- X(vkQueueSubmit)
-
-struct region {
- const uint8_t *host;
- size_t bytes;
- VkBuffer buf;
- VkDeviceMemory mem;
- VkDeviceAddress addr;
- int coherent; /* allocated regions: else flushed after host writes */
-};
-
-struct stage {
- VkBuffer buf;
- VkDeviceMemory mem;
- uint8_t *map;
- VkDeviceAddress addr;
- size_t bytes;
- int coherent; /* else invalidated before the host reads it */
-};
-
-struct pending {
- float *y; /* the task's output */
- size_t rows, nv; /* rows computed by the GPU, vectors */
- size_t y_stride; /* the task's */
- size_t off; /* in the Y stage */
-};
-
-/* The push constants of the shaders (level and the bare planes: Q6_K_P
- only). */
-struct push {
- uint32_t w[2], x[2], y[2];
- uint32_t rows, nb, nv, xs, ys, level;
- uint32_t p1[2], p0[2];
-};
-
-struct janas_gpu {
- void *lib;
- PFN_vkGetInstanceProcAddr gipa;
-#define DECL(f) PFN_##f f;
- VK_INSTANCE_FUNCS(DECL)
- VK_DEVICE_FUNCS(DECL)
-#undef DECL
- VkInstance inst;
- VkPhysicalDevice pd;
- VkDevice dev;
- VkQueue queue;
- VkShaderModule sm, sm6, sm6p, sm5, sma;
- VkPipelineLayout pl;
- VkPipeline pipe, pipe6, pipe6p, pipe5, pipea; /* Q4_K, Q6_K, Q6_K_P,
- Q5_K, experts'
- activation */
- VkCommandPool cp;
- VkCommandBuffer cb;
- VkFence fence;
- VkPhysicalDeviceMemoryProperties mp;
- struct region reg[MAX_REGIONS];
- int n_reg;
- struct stage xs, ys;
- struct pending pend[MAX_PENDING];
- size_t n_pend;
- int busy, broken;
- char name[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE];
- uint32_t sg; /* subgroup size the shader runs with */
- int discrete; /* weights copied to its memory, not shared */
- int host_import; /* VK_EXT_external_memory_host available */
- int sg_control; /* the size is required (else the device's fixed one) */
- /* the GPU's share of the rows, per product shape */
- struct share {
- uint64_t key;
- float f;
- uint32_t calls, waits;
- double t_begin, t_cpu, t_wait, t_copy; /* seconds, verbose only */
- uint64_t rows_gpu, rows_all;
- uint32_t off; /* calls left on the CPU alone */
- uint32_t seen; /* its tasks printed (JANAS_GPU_VERBOSE=2) */
- } share[SHARE_SLOTS];
- size_t min_n;
- size_t full_n; /* from this many vectors the GPU takes every row */
- int verbose, nospin, block_wait;
- double t_waited; /* last janas_gpu_finish */
- size_t y_used; /* bytes of the Y stage written by the last group */
- double t_conv, t_rec, t_sub; /* verbose: time in janas_gpu_begin */
- VkDeviceSize atom; /* nonCoherentAtomSize */
- /* keep-alive: an empty dispatch every keep_us while running, so that
- the GPU does not fall asleep between products (waking it costs up to
- ~0.5 ms per submission) */
- pthread_mutex_t qlock; /* the queue is shared with the keep-alive */
- pthread_t ka;
- int ka_running;
- atomic_int ka_stop;
- atomic_int ka_wanted; /* only while passes use the GPU */
- unsigned keep_us;
- VkCommandBuffer ka_cb;
- VkFence ka_fence;
-};
+#include "gpu_impl.h"
+
+#include "q4k_matvec.h" /* janas_spv_q4k_matvec, generated by build.sh */
+#include "q6k_matvec.h" /* janas_spv_q6k_matvec */
+#include "q6kp_matvec.h" /* janas_spv_q6kp_matvec */
+#include "q5k_matvec.h" /* janas_spv_q5k_matvec */
+#include "q8_0_matvec.h" /* janas_spv_q8_0_matvec */
+#include "b32_matvec.h" /* janas_spv_b32_matvec */
+#include "iq4xs_matvec.h" /* janas_spv_iq4xs_matvec */
+#include "q3k_matvec.h" /* janas_spv_q3k_matvec */
+#include "iq3s_matvec.h" /* janas_spv_iq3s_matvec */
+#include "expert_act.h" /* janas_spv_expert_act */
+#include "q4k_row.h" /* janas_spv_q4k_row */
+#include "q6k_row.h" /* janas_spv_q6k_row */
+#include "q6kp_row.h" /* janas_spv_q6kp_row */
+#include "q6ka_row.h" /* janas_spv_q6ka_row */
static double now(void)
{
@@ -199,8 +47,8 @@ static int set_err(char *err, size_t len, const char *what, VkResult r)
}
/* A memory type among bits with the wanted flags, preferring cached. */
-static int mem_type(const struct janas_gpu *g, uint32_t bits,
- VkMemoryPropertyFlags want)
+int janas_g_mem_type(const struct janas_gpu *g, uint32_t bits,
+ VkMemoryPropertyFlags want)
{
int best = -1;
for (uint32_t i = 0; i < g->mp.memoryTypeCount; i++) {
@@ -215,7 +63,7 @@ static int mem_type(const struct janas_gpu *g, uint32_t bits,
return best;
}
-static VkDeviceAddress buffer_address(struct janas_gpu *g, VkBuffer b)
+VkDeviceAddress janas_g_buffer_address(struct janas_gpu *g, VkBuffer b)
{
VkBufferDeviceAddressInfo ai = {
.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, .buffer = b};
@@ -225,8 +73,8 @@ static VkDeviceAddress buffer_address(struct janas_gpu *g, VkBuffer b)
/* A mapped buffer in host-cached memory if there is any (on the Arc iGPU
the coherent type is uncached: reading 1 MB costs ~0.9 ms and writing
300 KB ~0.7 ms), flushed and invalidated by hand when not coherent. */
-static int make_stage(struct janas_gpu *g, struct stage *s, size_t bytes,
- int cached)
+int janas_g_make_stage(struct janas_gpu *g, struct stage *s, size_t bytes,
+ int cached)
{
VkBufferCreateInfo bi = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.size = bytes,
@@ -237,14 +85,15 @@ static int make_stage(struct janas_gpu *g, struct stage *s, size_t bytes,
return -1;
VkMemoryRequirements req;
g->vkGetBufferMemoryRequirements(g->dev, s->buf, &req);
- int t = mem_type(g, req.memoryTypeBits,
- VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
- (cached ? VK_MEMORY_PROPERTY_HOST_CACHED_BIT
- : VK_MEMORY_PROPERTY_HOST_COHERENT_BIT));
+ int t =
+ janas_g_mem_type(g, req.memoryTypeBits,
+ VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
+ (cached ? VK_MEMORY_PROPERTY_HOST_CACHED_BIT
+ : VK_MEMORY_PROPERTY_HOST_COHERENT_BIT));
if (t < 0)
- t = mem_type(g, req.memoryTypeBits,
- VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
- VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
+ t = janas_g_mem_type(g, req.memoryTypeBits,
+ VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
+ VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
if (t < 0)
return -1;
s->coherent = (g->mp.memoryTypes[t].propertyFlags &
@@ -261,7 +110,7 @@ static int make_stage(struct janas_gpu *g, struct stage *s, size_t bytes,
g->vkMapMemory(g->dev, s->mem, 0, VK_WHOLE_SIZE, 0, (void **)&s->map) !=
VK_SUCCESS)
return -1;
- s->addr = buffer_address(g, s->buf);
+ s->addr = janas_g_buffer_address(g, s->buf);
s->bytes = bytes;
if (getenv("JANAS_GPU_VERBOSE"))
fprintf(stderr, "gpu stage %zu MiB: memory type %d, flags %#x\n",
@@ -373,6 +222,8 @@ static int pick_device(struct janas_gpu *g, uint32_t *family, char *err,
REJECT("subgroup size not usable")
g->sg = sg;
g->sg_control = control;
+ g->sg_min = p13.minSubgroupSize;
+ g->sg_max = p13.maxSubgroupSize;
uint32_t nf = 0;
g->vkGetPhysicalDeviceQueueFamilyProperties(g->pd, &nf, NULL);
VkQueueFamilyProperties qf[16];
@@ -459,9 +310,18 @@ static int record_keep_alive(struct janas_gpu *g)
/* A compute pipeline for a product shader: NV vectors per workgroup, the
chosen subgroup size (required when the device lets it be chosen). */
+VkResult janas_g_make_pipeline(struct janas_gpu *g, const uint32_t *code,
+ size_t bytes, VkShaderModule *sm,
+ VkPipeline *pipe, uint32_t kind)
+{
+ return janas_g_make_pipeline_nv(g, code, bytes, sm, pipe, kind,
+ NV_PER_GROUP);
+}
+
static VkResult make_pipeline(struct janas_gpu *g, const uint32_t *code,
size_t bytes, VkShaderModule *sm,
- VkPipeline *pipe)
+ VkPipeline *pipe, uint32_t kind, uint32_t nv,
+ uint32_t sg)
{
VkShaderModuleCreateInfo smi = {
.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
@@ -470,16 +330,19 @@ static VkResult make_pipeline(struct janas_gpu *g, const uint32_t *code,
VkResult r = g->vkCreateShaderModule(g->dev, &smi, NULL, sm);
if (r != VK_SUCCESS)
return r;
- uint32_t spec[2] = {NV_PER_GROUP, g->sg};
- VkSpecializationMapEntry me[2] = {
+ /* constant 2, the kind of a shader that serves several types (ignored
+ by the others) */
+ uint32_t spec[3] = {nv, sg, kind};
+ VkSpecializationMapEntry me[3] = {
{.constantID = 0, .offset = 0, .size = 4},
- {.constantID = 1, .offset = 4, .size = 4}};
+ {.constantID = 1, .offset = 4, .size = 4},
+ {.constantID = 2, .offset = 8, .size = 4}};
VkSpecializationInfo si = {
- .mapEntryCount = 2, .pMapEntries = me, .dataSize = 8, .pData = spec};
+ .mapEntryCount = 3, .pMapEntries = me, .dataSize = 12, .pData = spec};
VkPipelineShaderStageRequiredSubgroupSizeCreateInfo rss = {
.sType =
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO,
- .requiredSubgroupSize = g->sg};
+ .requiredSubgroupSize = sg};
VkComputePipelineCreateInfo cpi = {
.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
.stage =
@@ -498,6 +361,26 @@ static VkResult make_pipeline(struct janas_gpu *g, const uint32_t *code,
pipe);
}
+VkResult janas_g_make_pipeline_nv(struct janas_gpu *g, const uint32_t *code,
+ size_t bytes, VkShaderModule *sm,
+ VkPipeline *pipe, uint32_t kind, uint32_t nv)
+{
+ return make_pipeline(g, code, bytes, sm, pipe, kind, nv, g->sg);
+}
+
+uint32_t janas_g_make_pipeline_sg(struct janas_gpu *g, const uint32_t *code,
+ size_t bytes, VkShaderModule *sm,
+ VkPipeline *pipe, uint32_t kind, uint32_t sg)
+{
+ if (!g->sg_control || sg < g->sg_min || sg > g->sg_max ||
+ (sg & (sg - 1)) != 0)
+ sg = g->sg;
+ return make_pipeline(g, code, bytes, sm, pipe, kind, NV_PER_GROUP, sg) ==
+ VK_SUCCESS
+ ? sg
+ : 0;
+}
+
struct janas_gpu *janas_gpu_create(char *err, size_t err_len)
{
struct janas_gpu *g = calloc(1, sizeof(*g));
@@ -541,6 +424,7 @@ struct janas_gpu *janas_gpu_create(char *err, size_t err_len)
g->vkGetPhysicalDeviceProperties(g->pd, &pp);
g->atom =
pp.limits.nonCoherentAtomSize ? pp.limits.nonCoherentAtomSize : 64;
+ g->ts_period = pp.limits.timestampPeriod;
float prio = 1.0f;
VkDeviceQueueCreateInfo qci = {
@@ -576,31 +460,133 @@ struct janas_gpu *janas_gpu_create(char *err, size_t err_len)
g->vkGetDeviceQueue(g->dev, family, 0, &g->queue);
VkPushConstantRange pcr = {.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT,
- .size = sizeof(struct push)};
+ .size = JANAS_G_PUSH_BYTES};
VkPipelineLayoutCreateInfo pli = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.pushConstantRangeCount = 1,
.pPushConstantRanges = &pcr};
if ((r = g->vkCreatePipelineLayout(g->dev, &pli, NULL, &g->pl)) !=
VK_SUCCESS ||
- (r = make_pipeline(g, janas_spv_q4k_matvec,
- sizeof(janas_spv_q4k_matvec), &g->sm, &g->pipe)) !=
- VK_SUCCESS ||
- (r = make_pipeline(g, janas_spv_q6k_matvec,
- sizeof(janas_spv_q6k_matvec), &g->sm6, &g->pipe6)) !=
- VK_SUCCESS ||
- (r = make_pipeline(g, janas_spv_q6kp_matvec,
- sizeof(janas_spv_q6kp_matvec), &g->sm6p,
- &g->pipe6p)) != VK_SUCCESS ||
- (r = make_pipeline(g, janas_spv_q5k_matvec,
- sizeof(janas_spv_q5k_matvec), &g->sm5, &g->pipe5)) !=
- VK_SUCCESS ||
- (r = make_pipeline(g, janas_spv_expert_act,
- sizeof(janas_spv_expert_act), &g->sma, &g->pipea)) !=
- VK_SUCCESS) {
+ (r = janas_g_make_pipeline(g, janas_spv_q4k_matvec,
+ sizeof(janas_spv_q4k_matvec), &g->sm,
+ &g->pipe, 0)) != VK_SUCCESS ||
+ (r = janas_g_make_pipeline(g, janas_spv_q6k_matvec,
+ sizeof(janas_spv_q6k_matvec), &g->sm6,
+ &g->pipe6, 0)) != VK_SUCCESS ||
+ (r = janas_g_make_pipeline(g, janas_spv_q6kp_matvec,
+ sizeof(janas_spv_q6kp_matvec), &g->sm6p,
+ &g->pipe6p, 0)) != VK_SUCCESS ||
+ (r = janas_g_make_pipeline(g, janas_spv_q5k_matvec,
+ sizeof(janas_spv_q5k_matvec), &g->sm5,
+ &g->pipe5, 0)) != VK_SUCCESS ||
+ (r = janas_g_make_pipeline(g, janas_spv_q8_0_matvec,
+ sizeof(janas_spv_q8_0_matvec), &g->sm80,
+ &g->pipe80, 0)) != VK_SUCCESS ||
+ (r = janas_g_make_pipeline(g, janas_spv_expert_act,
+ sizeof(janas_spv_expert_act), &g->sma,
+ &g->pipea, 0)) != VK_SUCCESS) {
+ set_err(err, err_len, "cannot create the shaders", r);
+ goto fail;
+ }
+ if ((r = janas_g_make_pipeline(g, janas_spv_iq4xs_matvec,
+ sizeof(janas_spv_iq4xs_matvec), &g->smx4,
+ &g->pipex4, 0)) != VK_SUCCESS ||
+ (r = janas_g_make_pipeline(g, janas_spv_q3k_matvec,
+ sizeof(janas_spv_q3k_matvec), &g->sm3,
+ &g->pipe3, 0)) != VK_SUCCESS ||
+ (r = janas_g_make_pipeline(g, janas_spv_iq3s_matvec,
+ sizeof(janas_spv_iq3s_matvec), &g->smi3,
+ &g->pipei3, 0)) != VK_SUCCESS) {
set_err(err, err_len, "cannot create the shaders", r);
goto fail;
}
+ /* each product shader made for a single vector too */
+ {
+ const struct {
+ const uint32_t *code;
+ size_t bytes;
+ uint32_t kind;
+ } one[N_PROD] = {
+ {janas_spv_q4k_matvec, sizeof(janas_spv_q4k_matvec), 0},
+ {janas_spv_q6k_matvec, sizeof(janas_spv_q6k_matvec), 0},
+ {janas_spv_q6kp_matvec, sizeof(janas_spv_q6kp_matvec), 0},
+ {janas_spv_q5k_matvec, sizeof(janas_spv_q5k_matvec), 0},
+ {janas_spv_q8_0_matvec, sizeof(janas_spv_q8_0_matvec), 0},
+ {janas_spv_b32_matvec, sizeof(janas_spv_b32_matvec), 0},
+ {janas_spv_b32_matvec, sizeof(janas_spv_b32_matvec), 1},
+ {janas_spv_b32_matvec, sizeof(janas_spv_b32_matvec), 2},
+ {janas_spv_b32_matvec, sizeof(janas_spv_b32_matvec), 3},
+ {janas_spv_iq4xs_matvec, sizeof(janas_spv_iq4xs_matvec), 0},
+ {janas_spv_q3k_matvec, sizeof(janas_spv_q3k_matvec), 0},
+ {janas_spv_iq3s_matvec, sizeof(janas_spv_iq3s_matvec), 0}};
+ for (int i = 0; i < N_PROD; i++)
+ if ((r = janas_g_make_pipeline_nv(g, one[i].code, one[i].bytes,
+ &g->pm1[i], &g->pp1[i],
+ one[i].kind, 1)) != VK_SUCCESS) {
+ set_err(err, err_len, "cannot create the shaders", r);
+ goto fail;
+ }
+ /* the subgroup-per-row shaders written so far */
+ if ((r = janas_g_make_pipeline_nv(g, janas_spv_q4k_row,
+ sizeof(janas_spv_q4k_row), &g->rm[0],
+ &g->rp[0], 0, 1)) != VK_SUCCESS) {
+ set_err(err, err_len, "cannot create the shaders", r);
+ goto fail;
+ }
+ if ((r = janas_g_make_pipeline_nv(g, janas_spv_q6k_row,
+ sizeof(janas_spv_q6k_row), &g->rm[1],
+ &g->rp[1], 0, 1)) != VK_SUCCESS) {
+ set_err(err, err_len, "cannot create the shaders", r);
+ goto fail;
+ }
+ if ((r = janas_g_make_pipeline_nv(g, janas_spv_q6kp_row,
+ sizeof(janas_spv_q6kp_row), &g->rm[2],
+ &g->rp[2], 0, 1)) != VK_SUCCESS) {
+ set_err(err, err_len, "cannot create the shaders", r);
+ goto fail;
+ }
+ if ((r = janas_g_make_pipeline_nv(
+ g, janas_spv_q6ka_row, sizeof(janas_spv_q6ka_row), &g->rm_q6ka,
+ &g->rp_q6ka, 0, 1)) != VK_SUCCESS) {
+ set_err(err, err_len, "cannot create the shaders", r);
+ goto fail;
+ }
+ /* the tiled copies (constant 2: the rows of a tile) */
+ if ((r = janas_g_make_pipeline_nv(g, janas_spv_q4k_row,
+ sizeof(janas_spv_q4k_row),
+ &g->rm_tile[0], &g->rp_tile[0],
+ JANAS_TILE, 1)) != VK_SUCCESS ||
+ (r = janas_g_make_pipeline_nv(g, janas_spv_q6ka_row,
+ sizeof(janas_spv_q6ka_row),
+ &g->rm_tile[1], &g->rp_tile[1],
+ JANAS_TILE, 1)) != VK_SUCCESS) {
+ set_err(err, err_len, "cannot create the shaders", r);
+ goto fail;
+ }
+ /* and for 2, 4 and 8 vectors at once */
+ {
+ const uint32_t *code[4] = {janas_spv_q4k_row, janas_spv_q6k_row,
+ janas_spv_q6kp_row, janas_spv_q6ka_row};
+ size_t bytes[4] = {
+ sizeof(janas_spv_q4k_row), sizeof(janas_spv_q6k_row),
+ sizeof(janas_spv_q6kp_row), sizeof(janas_spv_q6ka_row)};
+ for (int k = 0; k < 3; k++)
+ for (int i = 0; i < 4; i++)
+ if ((r = janas_g_make_pipeline_nv(
+ g, code[i], bytes[i], &g->rmv[k][i], &g->rpv[k][i],
+ 0, 2u << k)) != VK_SUCCESS) {
+ set_err(err, err_len, "cannot create the shaders", r);
+ goto fail;
+ }
+ }
+ }
+ for (uint32_t k = 0; k < 4; k++)
+ if ((r = janas_g_make_pipeline(
+ g, janas_spv_b32_matvec, sizeof(janas_spv_b32_matvec),
+ &g->sm32[k], &g->pipe32[k], k)) != VK_SUCCESS) {
+ set_err(err, err_len, "cannot create the shaders", r);
+ goto fail;
+ }
VkCommandPoolCreateInfo cpci = {
.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
@@ -614,8 +600,9 @@ struct janas_gpu *janas_gpu_create(char *err, size_t err_len)
(cba.commandPool = g->cp,
g->vkAllocateCommandBuffers(g->dev, &cba, &g->cb) != VK_SUCCESS) ||
g->vkCreateFence(g->dev, &fci, NULL, &g->fence) != VK_SUCCESS ||
- make_stage(g, &g->xs, X_STAGE_BYTES, !getenv("JANAS_GPU_XCOH")) != 0 ||
- make_stage(g, &g->ys, Y_STAGE_BYTES, 1) != 0) {
+ janas_g_make_stage(g, &g->xs, X_STAGE_BYTES,
+ !getenv("JANAS_GPU_XCOH")) != 0 ||
+ janas_g_make_stage(g, &g->ys, Y_STAGE_BYTES, 1) != 0) {
snprintf(err, err_len, "cannot create the GPU buffers");
goto fail;
}
@@ -703,6 +690,53 @@ void janas_gpu_destroy(struct janas_gpu *g)
g->vkDestroyPipeline(g->dev, g->pipe6p, NULL);
if (g->pipe5)
g->vkDestroyPipeline(g->dev, g->pipe5, NULL);
+ if (g->pipe80)
+ g->vkDestroyPipeline(g->dev, g->pipe80, NULL);
+ if (g->rp_q6ka)
+ g->vkDestroyPipeline(g->dev, g->rp_q6ka, NULL);
+ if (g->rm_q6ka)
+ g->vkDestroyShaderModule(g->dev, g->rm_q6ka, NULL);
+ for (int i = 0; i < 2; i++) {
+ if (g->rp_tile[i])
+ g->vkDestroyPipeline(g->dev, g->rp_tile[i], NULL);
+ if (g->rm_tile[i])
+ g->vkDestroyShaderModule(g->dev, g->rm_tile[i], NULL);
+ }
+ for (int k = 0; k < 3; k++)
+ for (int i = 0; i < 4; i++) {
+ if (g->rpv[k][i])
+ g->vkDestroyPipeline(g->dev, g->rpv[k][i], NULL);
+ if (g->rmv[k][i])
+ g->vkDestroyShaderModule(g->dev, g->rmv[k][i], NULL);
+ }
+ for (int i = 0; i < N_PROD; i++) {
+ if (g->pp1[i])
+ g->vkDestroyPipeline(g->dev, g->pp1[i], NULL);
+ if (g->pm1[i])
+ g->vkDestroyShaderModule(g->dev, g->pm1[i], NULL);
+ if (g->rp[i])
+ g->vkDestroyPipeline(g->dev, g->rp[i], NULL);
+ if (g->rm[i])
+ g->vkDestroyShaderModule(g->dev, g->rm[i], NULL);
+ }
+ if (g->pipex4)
+ g->vkDestroyPipeline(g->dev, g->pipex4, NULL);
+ if (g->pipe3)
+ g->vkDestroyPipeline(g->dev, g->pipe3, NULL);
+ if (g->pipei3)
+ g->vkDestroyPipeline(g->dev, g->pipei3, NULL);
+ if (g->sm3)
+ g->vkDestroyShaderModule(g->dev, g->sm3, NULL);
+ if (g->smi3)
+ g->vkDestroyShaderModule(g->dev, g->smi3, NULL);
+ if (g->smx4)
+ g->vkDestroyShaderModule(g->dev, g->smx4, NULL);
+ for (int k = 0; k < 4; k++) {
+ if (g->pipe32[k])
+ g->vkDestroyPipeline(g->dev, g->pipe32[k], NULL);
+ if (g->sm32[k])
+ g->vkDestroyShaderModule(g->dev, g->sm32[k], NULL);
+ }
if (g->pipea)
g->vkDestroyPipeline(g->dev, g->pipea, NULL);
if (g->sma)
@@ -713,6 +747,8 @@ void janas_gpu_destroy(struct janas_gpu *g)
g->vkDestroyShaderModule(g->dev, g->sm6p, NULL);
if (g->sm5)
g->vkDestroyShaderModule(g->dev, g->sm5, NULL);
+ if (g->sm80)
+ g->vkDestroyShaderModule(g->dev, g->sm80, NULL);
if (g->pl)
g->vkDestroyPipelineLayout(g->dev, g->pl, NULL);
if (g->sm)
@@ -811,9 +847,9 @@ static int copy_to_device(struct janas_gpu *g, const void *p, size_t bytes)
if (g->vkCreateBuffer(g->dev, &sbi, NULL, &st.buf) != VK_SUCCESS)
goto fail;
g->vkGetBufferMemoryRequirements(g->dev, st.buf, &req);
- int ts = mem_type(g, req.memoryTypeBits,
- VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
- VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
+ int ts = janas_g_mem_type(g, req.memoryTypeBits,
+ VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
+ VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
VkMemoryAllocateInfo sai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.allocationSize = req.size,
.memoryTypeIndex = (uint32_t)ts};
@@ -852,7 +888,7 @@ static int copy_to_device(struct janas_gpu *g, const void *p, size_t bytes)
goto fail;
rg->host = p;
rg->bytes = bytes;
- rg->addr = buffer_address(g, rg->buf);
+ rg->addr = janas_g_buffer_address(g, rg->buf);
rg->coherent = 1;
g->n_reg++;
return 0;
@@ -892,7 +928,7 @@ int janas_gpu_import(struct janas_gpu *g, const void *p, size_t bytes)
return -1;
VkMemoryRequirements req;
g->vkGetBufferMemoryRequirements(g->dev, rg->buf, &req);
- int t = mem_type(g, hp.memoryTypeBits & req.memoryTypeBits, 0);
+ int t = janas_g_mem_type(g, hp.memoryTypeBits & req.memoryTypeBits, 0);
VkImportMemoryHostPointerInfoEXT imp = {
.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT,
.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
@@ -917,7 +953,7 @@ int janas_gpu_import(struct janas_gpu *g, const void *p, size_t bytes)
}
rg->host = p;
rg->bytes = bytes;
- rg->addr = buffer_address(g, rg->buf);
+ rg->addr = janas_g_buffer_address(g, rg->buf);
rg->coherent = 1;
g->n_reg++;
return 0;
@@ -938,9 +974,9 @@ void *janas_gpu_alloc(struct janas_gpu *g, size_t bytes)
return NULL;
VkMemoryRequirements req;
g->vkGetBufferMemoryRequirements(g->dev, rg->buf, &req);
- int t = mem_type(g, req.memoryTypeBits,
- VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
- VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
+ int t = janas_g_mem_type(g, req.memoryTypeBits,
+ VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
+ VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
VkMemoryAllocateFlagsInfo fl = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO,
.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT};
@@ -963,7 +999,7 @@ void *janas_gpu_alloc(struct janas_gpu *g, size_t bytes)
}
rg->host = p;
rg->bytes = bytes;
- rg->addr = buffer_address(g, rg->buf);
+ rg->addr = janas_g_buffer_address(g, rg->buf);
rg->coherent = (g->mp.memoryTypes[t].propertyFlags &
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0;
g->n_reg++;
@@ -990,8 +1026,8 @@ void janas_gpu_flush(struct janas_gpu *g, const void *p, size_t bytes)
}
/* The region holding [p, p + bytes), or NULL. */
-static const struct region *find_region(const struct janas_gpu *g,
- const void *p, size_t bytes)
+const struct region *janas_g_find_region(const struct janas_gpu *g,
+ const void *p, size_t bytes)
{
const uint8_t *b = p;
for (int i = 0; i < g->n_reg; i++)
@@ -1001,13 +1037,23 @@ static const struct region *find_region(const struct janas_gpu *g,
return NULL;
}
-/* Bytes the shader may read for rows of a task: Q6_K and the high plane of
- Q6_K_P read up to 2 bytes past the last block (whole words). */
+/* Bytes the shader may read for rows of a task: Q6_K, the high plane of
+ Q6_K_P, Q3_K and IQ3_S read up to 2 bytes past the last block (whole
+ words). */
static size_t read_bytes(const struct janas_matvec_task *t, size_t rows)
{
size_t nb = t->cols / JANAS_QK;
- return rows * nb * janas_qtype_block_size(t->type) +
- (t->type == JANAS_Q6_K || t->type == JANAS_Q6_K_P ? 4 : 0);
+ if (t->type == JANAS_Q4_K_T || t->type == JANAS_Q6_K_AT)
+ return (t->rows + JANAS_TILE - 1) / JANAS_TILE * JANAS_TILE * nb *
+ (t->type == JANAS_Q4_K_T ? janas_qtype_block_size(JANAS_Q4_K)
+ : JANAS_Q6KA_BLOCK);
+ size_t bs = t->type == JANAS_Q6_K_A ? JANAS_Q6KA_BLOCK
+ : janas_qtype_block_size(t->type);
+ return rows * nb * bs + (t->type == JANAS_Q6_K || t->type == JANAS_Q6_K_P ||
+ t->type == JANAS_Q3_K ||
+ t->type == JANAS_IQ3_S
+ ? 4
+ : 0);
}
/* The bare planes of a Q6_K_P task: level 3 (both), 2 (plane[0]) or 1. */
@@ -1021,42 +1067,74 @@ static const struct region *plane_region(const struct janas_gpu *g,
const void *p, size_t rows, size_t nb)
{
return (uintptr_t)p % 4 == 0
- ? find_region(g, p, rows * nb * JANAS_Q6KP_PLANE)
+ ? janas_g_find_region(g, p, rows * nb * JANAS_Q6KP_PLANE)
: NULL;
}
+static int b32_kind(int type);
+
int janas_gpu_can(const struct janas_gpu *g, const struct janas_matvec_task *t)
{
size_t nb = t->cols / JANAS_QK, nv = t->n_vec ? t->n_vec : 1;
int typed =
(t->type == JANAS_Q4_K && (uintptr_t)t->w % 16 == 0) ||
(t->type == JANAS_Q5_K && (uintptr_t)t->w % 16 == 0) ||
+ ((t->type == JANAS_Q8_0 || t->type == JANAS_IQ4_XS ||
+ t->type == JANAS_Q3_K || t->type == JANAS_IQ3_S ||
+ b32_kind(t->type) >= 0) &&
+ (uintptr_t)t->w % 4 == 0) ||
(t->type == JANAS_Q6_K && (uintptr_t)t->w % 4 == 0) ||
+ (t->type == JANAS_Q6_K_A && (uintptr_t)t->w % 16 == 0 &&
+ (nv == 1 || g->rpv[2][3])) ||
+ ((t->type == JANAS_Q4_K_T || t->type == JANAS_Q6_K_AT) &&
+ (uintptr_t)t->w % 16 == 0 && nv == 1) ||
(t->type == JANAS_Q6_K_P && (uintptr_t)t->w % 4 == 0 &&
(plane_level(t) < 2 || plane_region(g, t->plane[0], t->rows, nb)) &&
(plane_level(t) < 3 || plane_region(g, t->plane[1], t->rows, nb)));
return !g->broken && typed && t->cols % JANAS_QK == 0 &&
nv * nb * GPU_BLOCK <= X_STAGE_BYTES &&
t->rows * nv * sizeof(float) <= Y_STAGE_BYTES &&
- find_region(g, t->w, read_bytes(t, t->rows));
+ janas_g_find_region(g, t->w, read_bytes(t, t->rows));
}
/* Copies nv vectors of nb Q8_K blocks into the shader's layout. */
static void convert_x(uint8_t *dst, const struct janas_block_q8k *x, size_t xs,
- size_t nv, size_t nb)
+ size_t nv, size_t nb, int k32)
{
_Alignas(64) uint8_t blk[GPU_BLOCK] = {0};
for (size_t v = 0; v < nv; v++)
for (size_t b = 0; b < nb; b++, dst += GPU_BLOCK) {
const struct janas_block_q8k *s = x + v * xs + b;
- memcpy(blk, s->qs, JANAS_QK);
- memcpy(blk + JANAS_QK, s->bsums, sizeof(s->bsums));
- memcpy(blk + JANAS_QK + sizeof(s->bsums), &s->d, sizeof(float));
+ if (k32) {
+ /* for the weights in blocks of 32: qs32, bsums32, d32 */
+ memcpy(blk, s->qs32, JANAS_QK);
+ memcpy(blk + JANAS_QK, s->bsums32, sizeof(s->bsums32));
+ memcpy(blk + JANAS_QK + sizeof(s->bsums32), s->d32,
+ sizeof(s->d32));
+ } else {
+ memcpy(blk, s->qs, JANAS_QK);
+ memcpy(blk + JANAS_QK, s->bsums, sizeof(s->bsums));
+ memcpy(blk + JANAS_QK + sizeof(s->bsums), &s->d, sizeof(float));
+ }
memcpy(dst, blk, GPU_BLOCK);
}
}
-static void push_addr(uint32_t out[2], VkDeviceAddress a);
+/* The KIND of b32_matvec for a type, -1 if it is not one of its. */
+static int b32_kind(int type)
+{
+ return type == JANAS_Q4_0 ? 0
+ : type == JANAS_IQ4_NL ? 1
+ : type == JANAS_Q4_1 ? 2
+ : type == JANAS_Q5_1 ? 3
+ : -1;
+}
+
+/* Whether a type reads the activations in blocks of 32 (convert_x). */
+int janas_g_x_in_32(int type)
+{
+ return type == JANAS_Q8_0 || b32_kind(type) >= 0;
+}
int janas_gpu_begin(struct janas_gpu *g, const struct janas_matvec_task *tasks,
const size_t *gpu_rows, size_t n)
@@ -1067,6 +1145,7 @@ int janas_gpu_begin(struct janas_gpu *g, const struct janas_matvec_task *tasks,
struct {
const void *x;
size_t nv, xs, nb, off;
+ int k32;
} xc[MAX_XCACHE];
size_t n_xc = 0, x_used = 0, y_used = 0;
g->n_pend = 0;
@@ -1082,26 +1161,20 @@ int janas_gpu_begin(struct janas_gpu *g, const struct janas_matvec_task *tasks,
if (gpu_rows[i] == 0)
continue;
const struct janas_matvec_task *t = &tasks[i];
- VkPipeline want = t->type == JANAS_Q6_K ? g->pipe6
- : t->type == JANAS_Q6_K_P ? g->pipe6p
- : t->type == JANAS_Q5_K ? g->pipe5
- : g->pipe;
- if (want != bound) {
- g->vkCmdBindPipeline(g->cb, VK_PIPELINE_BIND_POINT_COMPUTE, want);
- bound = want;
- }
size_t nb = t->cols / JANAS_QK, nv = t->n_vec ? t->n_vec : 1;
size_t xs = t->x_stride ? t->x_stride : nb;
size_t k = 0;
- while (k < n_xc && !(xc[k].x == t->x && xc[k].nv == nv &&
- xc[k].xs == xs && xc[k].nb == nb))
+ int k32 = janas_g_x_in_32(t->type);
+ while (k < n_xc &&
+ !(xc[k].x == t->x && xc[k].nv == nv && xc[k].xs == xs &&
+ xc[k].nb == nb && xc[k].k32 == k32))
k++;
if (k == n_xc) {
size_t bytes = nv * nb * GPU_BLOCK;
if (n_xc == MAX_XCACHE || x_used + bytes > X_STAGE_BYTES)
return -1;
double tc = g->verbose ? now() : 0;
- convert_x(g->xs.map + x_used, t->x, xs, nv, nb);
+ convert_x(g->xs.map + x_used, t->x, xs, nv, nb, k32);
if (g->verbose)
g->t_conv += now() - tc;
xc[k].x = t->x;
@@ -1109,44 +1182,17 @@ int janas_gpu_begin(struct janas_gpu *g, const struct janas_matvec_task *tasks,
xc[k].xs = xs;
xc[k].nb = nb;
xc[k].off = x_used;
+ xc[k].k32 = k32;
x_used += bytes;
n_xc++;
}
size_t ybytes = gpu_rows[i] * nv * sizeof(float);
- const struct region *rg =
- find_region(g, t->w, read_bytes(t, gpu_rows[i]));
- if (!rg || g->n_pend == MAX_PENDING || y_used + ybytes > Y_STAGE_BYTES)
+ if (g->n_pend == MAX_PENDING || y_used + ybytes > Y_STAGE_BYTES)
+ return -1;
+ if (janas_g_record_task(g, &bound, t, gpu_rows[i],
+ g->xs.addr + xc[k].off, g->ys.addr + y_used,
+ gpu_rows[i]) != 0)
return -1;
- VkDeviceAddress wa =
- rg->addr + (VkDeviceAddress)((const uint8_t *)t->w - rg->host);
- VkDeviceAddress xa = g->xs.addr + xc[k].off, ya = g->ys.addr + y_used;
- struct push pc = {.w = {(uint32_t)wa, (uint32_t)(wa >> 32)},
- .x = {(uint32_t)xa, (uint32_t)(xa >> 32)},
- .y = {(uint32_t)ya, (uint32_t)(ya >> 32)},
- .rows = (uint32_t)gpu_rows[i],
- .nb = (uint32_t)nb,
- .nv = (uint32_t)nv,
- .xs = (uint32_t)nb,
- .ys = (uint32_t)gpu_rows[i]};
- if (t->type == JANAS_Q6_K_P) {
- pc.level = (uint32_t)plane_level(t);
- for (int q = 0; q < (int)pc.level - 1; q++) {
- const struct region *pr =
- plane_region(g, t->plane[q], gpu_rows[i], nb);
- if (!pr)
- return -1;
- push_addr(q == 0 ? pc.p1 : pc.p0,
- pr->addr +
- (VkDeviceAddress)((const uint8_t *)t->plane[q] -
- pr->host));
- }
- }
- g->vkCmdPushConstants(g->cb, g->pl, VK_SHADER_STAGE_COMPUTE_BIT, 0,
- sizeof(pc), &pc);
- g->vkCmdDispatch(
- g->cb,
- (uint32_t)((gpu_rows[i] + ROWS_PER_GROUP - 1) / ROWS_PER_GROUP),
- (uint32_t)((nv + NV_PER_GROUP - 1) / NV_PER_GROUP), 1);
g->pend[g->n_pend++] =
(struct pending){.y = t->y,
.rows = gpu_rows[i],
@@ -1199,12 +1245,118 @@ struct push_act {
uint32_t blocks;
};
-static void push_addr(uint32_t out[2], VkDeviceAddress a)
+void janas_g_push_addr(uint32_t out[2], VkDeviceAddress a)
{
out[0] = (uint32_t)a;
out[1] = (uint32_t)(a >> 32);
}
+/* The index of a type's product shader in the single-vector table, -1 if
+ none: Q4_K, Q6_K, Q6_K_P, Q5_K, Q8_0, the four of b32 (Q4_0, IQ4_NL,
+ Q4_1, Q5_1), IQ4_XS, Q3_K, IQ3_S. */
+static int prod_index(int type)
+{
+ static const int types[N_PROD] = {JANAS_Q4_K, JANAS_Q6_K, JANAS_Q6_K_P,
+ JANAS_Q5_K, JANAS_Q8_0, JANAS_Q4_0,
+ JANAS_IQ4_NL, JANAS_Q4_1, JANAS_Q5_1,
+ JANAS_IQ4_XS, JANAS_Q3_K, JANAS_IQ3_S};
+ for (int i = 0; i < N_PROD; i++)
+ if (types[i] == type)
+ return i;
+ return -1;
+}
+
+int janas_g_record_task(struct janas_gpu *g, VkPipeline *bound,
+ const struct janas_matvec_task *t, size_t rows,
+ VkDeviceAddress xa, VkDeviceAddress ya, size_t ys)
+{
+ VkPipeline want = t->type == JANAS_Q6_K ? g->pipe6
+ : t->type == JANAS_Q6_K_P ? g->pipe6p
+ : t->type == JANAS_Q5_K ? g->pipe5
+ : t->type == JANAS_Q8_0 ? g->pipe80
+ : t->type == JANAS_IQ4_XS ? g->pipex4
+ : t->type == JANAS_Q3_K ? g->pipe3
+ : t->type == JANAS_IQ3_S ? g->pipei3
+ : b32_kind(t->type) >= 0 ? g->pipe32[b32_kind(t->type)]
+ : g->pipe;
+ size_t nb = t->cols / JANAS_QK, nv = t->n_vec ? t->n_vec : 1;
+ /* a single vector: a subgroup per row where there is such a shader
+ (rows_wg rows a workgroup), else the shader made for one vector */
+ uint32_t nvg = NV_PER_GROUP, rows_wg = ROWS_PER_GROUP;
+ int pk = prod_index(t->type);
+ /* up to row_nv vectors (JANAS_GPU_ROW_NV, 0 to 8; 4 by default) a row
+ shader takes them, its variant for 2, 4 or 8 (kv), where the
+ shaders reading a row per invocation are slower; more, those */
+ static int row_nv = -1;
+ if (row_nv < 0)
+ row_nv =
+ getenv("JANAS_GPU_ROW_NV") ? atoi(getenv("JANAS_GPU_ROW_NV")) : 4;
+ int kv = nv <= 2 ? 0 : nv <= 4 ? 1 : 2;
+ if (t->type == JANAS_Q4_K_T || t->type == JANAS_Q6_K_AT) {
+ VkPipeline rp = g->rp_tile[t->type == JANAS_Q6_K_AT];
+ if (nv != 1 || !rp)
+ return -1;
+ want = rp;
+ nvg = 1;
+ rows_wg = 64 / g->sg;
+ } else if (t->type == JANAS_Q6_K_A) {
+ /* the aligned copy: its row shaders, eight vectors at a time */
+ VkPipeline rp = nv == 1 ? g->rp_q6ka : g->rpv[kv][3];
+ if (!rp)
+ return -1;
+ want = rp;
+ nvg = nv == 1 ? 1 : 2u << kv;
+ rows_wg = 64 / g->sg;
+ } else if (nv == 1 && pk >= 0 && g->rp[pk] && nb <= 128 &&
+ !getenv("JANAS_GPU_NO_ROW")) {
+ want = g->rp[pk];
+ nvg = 1;
+ rows_wg = 64 / g->sg; /* a subgroup per row */
+ } else if (nv > 1 && (int)nv <= row_nv && pk >= 0 && pk < 3 &&
+ g->rpv[kv][pk] && nb <= 128 && !getenv("JANAS_GPU_NO_ROW")) {
+ want = g->rpv[kv][pk];
+ nvg = 2u << kv;
+ rows_wg = 64 / g->sg;
+ } else if (nv == 1 && pk >= 0 && g->pp1[pk]) {
+ want = g->pp1[pk];
+ nvg = 1;
+ }
+ if (want != *bound) {
+ g->vkCmdBindPipeline(g->cb, VK_PIPELINE_BIND_POINT_COMPUTE, want);
+ *bound = want;
+ }
+ const struct region *rg = janas_g_find_region(g, t->w, read_bytes(t, rows));
+ if (!rg)
+ return -1;
+ VkDeviceAddress wa =
+ rg->addr + (VkDeviceAddress)((const uint8_t *)t->w - rg->host);
+ struct push pc = {.rows = (uint32_t)rows,
+ .nb = (uint32_t)nb,
+ .nv = (uint32_t)nv,
+ .xs = (uint32_t)nb,
+ .ys = (uint32_t)ys};
+ janas_g_push_addr(pc.w, wa);
+ janas_g_push_addr(pc.x, xa);
+ janas_g_push_addr(pc.y, ya);
+ if (t->type == JANAS_Q6_K_P) {
+ pc.level = (uint32_t)plane_level(t);
+ for (int q = 0; q < (int)pc.level - 1; q++) {
+ const struct region *pr = plane_region(g, t->plane[q], rows, nb);
+ if (!pr)
+ return -1;
+ janas_g_push_addr(
+ q == 0 ? pc.p1 : pc.p0,
+ pr->addr +
+ (VkDeviceAddress)((const uint8_t *)t->plane[q] - pr->host));
+ }
+ }
+ g->vkCmdPushConstants(g->cb, g->pl, VK_SHADER_STAGE_COMPUTE_BIT, 0,
+ sizeof(pc), &pc);
+ g->vkCmdDispatch(g->cb, (uint32_t)((rows + rows_wg - 1) / rows_wg),
+ (uint32_t)((nv + nvg - 1) / nvg), 1);
+ return 0;
+}
+
/* A product of one weight matrix (rows x cols of type) with one vector. */
static int record_product(struct janas_gpu *g, VkPipeline *bound, int type,
const void *w, size_t rows, size_t cols,
@@ -1212,7 +1364,7 @@ static int record_product(struct janas_gpu *g, VkPipeline *bound, int type,
{
struct janas_matvec_task t = {
.type = type, .w = w, .rows = rows, .cols = cols, .n_vec = 1};
- const struct region *rg = find_region(g, w, read_bytes(&t, rows));
+ const struct region *rg = janas_g_find_region(g, w, read_bytes(&t, rows));
if (!rg || (type != JANAS_Q4_K && type != JANAS_Q6_K))
return -1;
VkPipeline want = type == JANAS_Q6_K ? g->pipe6 : g->pipe;
@@ -1228,9 +1380,9 @@ static int record_product(struct janas_gpu *g, VkPipeline *bound, int type,
.nv = 1,
.xs = (uint32_t)nb,
.ys = (uint32_t)rows};
- push_addr(pc.w, wa);
- push_addr(pc.x, xa);
- push_addr(pc.y, ya);
+ janas_g_push_addr(pc.w, wa);
+ janas_g_push_addr(pc.x, xa);
+ janas_g_push_addr(pc.y, ya);
g->vkCmdPushConstants(g->cb, g->pl, VK_SHADER_STAGE_COMPUTE_BIT, 0,
sizeof(pc), &pc);
g->vkCmdDispatch(
@@ -1238,7 +1390,7 @@ static int record_product(struct janas_gpu *g, VkPipeline *bound, int type,
return 0;
}
-static void compute_barrier(struct janas_gpu *g)
+void janas_g_compute_barrier(struct janas_gpu *g)
{
VkMemoryBarrier mb = {.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT,
@@ -1261,7 +1413,7 @@ int janas_gpu_ffn_begin(struct janas_gpu *g, const struct janas_gpu_expert *e,
if (hoff + n * nbh * GPU_BLOCK > X_STAGE_BYTES ||
down_off + n * d * sizeof(float) > Y_STAGE_BYTES)
return -1;
- convert_x(g->xs.map, x, nbx, 1, nbx);
+ convert_x(g->xs.map, x, nbx, 1, nbx, 0);
if (g->vkResetCommandBuffer(g->cb, 0) != VK_SUCCESS)
return -1;
VkCommandBufferBeginInfo bb = {
@@ -1277,17 +1429,17 @@ int janas_gpu_ffn_begin(struct janas_gpu *g, const struct janas_gpu_expert *e,
record_product(g, &bound, e[i].up_type, e[i].up, ff, d, X,
Y + up_off + i * ff * sizeof(float)) != 0)
return -1;
- compute_barrier(g);
+ janas_g_compute_barrier(g);
g->vkCmdBindPipeline(g->cb, VK_PIPELINE_BIND_POINT_COMPUTE, g->pipea);
bound = g->pipea;
struct push_act pa = {.blocks = (uint32_t)(n * nbh)};
- push_addr(pa.g, Y);
- push_addr(pa.u, Y + up_off);
- push_addr(pa.x, X + hoff);
+ janas_g_push_addr(pa.g, Y);
+ janas_g_push_addr(pa.u, Y + up_off);
+ janas_g_push_addr(pa.x, X + hoff);
g->vkCmdPushConstants(g->cb, g->pl, VK_SHADER_STAGE_COMPUTE_BIT, 0,
sizeof(pa), &pa);
g->vkCmdDispatch(g->cb, (uint32_t)(n * nbh), 1, 1);
- compute_barrier(g);
+ janas_g_compute_barrier(g);
for (size_t i = 0; i < n; i++)
if (record_product(g, &bound, e[i].down_type, e[i].down, d, ff,
X + hoff + i * nbh * GPU_BLOCK,
@@ -1399,15 +1551,27 @@ void janas_gpu_matvec_group(struct janas_gpu *g, struct janas_pool *pool,
uint64_t key = (uint64_t)n << 48 ^ (uint64_t)tasks[0].rows << 24 ^
(uint64_t)tasks[0].cols << 8 ^ nv;
struct share *sh = find_share(g, key);
- /* JANAS_GPU_VERBOSE=2: each shape once, with its tasks' types and
- whether the GPU can take them */
- if (g->verbose > 1 && sh && sh->calls == 0 && !sh->seen) {
- sh->seen = 1;
- fprintf(stderr, "gpu shape %016llx:", (unsigned long long)key);
+ /* JANAS_GPU_VERBOSE=2: each shape once for every set of weight types
+ it comes with (up to four; layers of the same shape can differ, as
+ the down matrices of a Q4_K_M model), with whether the GPU takes
+ them */
+ if (g->verbose > 1 && sh) {
+ uint32_t ts = 2166136261u;
for (size_t i = 0; i < n; i++)
- fprintf(stderr, " type %d %zux%zu%s", tasks[i].type, tasks[i].rows,
- tasks[i].cols, janas_gpu_can(g, &tasks[i]) ? "" : " (CPU)");
- fprintf(stderr, "\n");
+ ts = (ts ^ (uint32_t)tasks[i].type) * 16777619u;
+ ts |= 1; /* never 0, which marks a free entry */
+ int k = 0;
+ while (k < 4 && sh->seen[k] && sh->seen[k] != ts)
+ k++;
+ if (k < 4 && !sh->seen[k]) {
+ sh->seen[k] = ts;
+ fprintf(stderr, "gpu shape %016llx:", (unsigned long long)key);
+ for (size_t i = 0; i < n; i++)
+ fprintf(stderr, " type %d %zux%zu%s", tasks[i].type,
+ tasks[i].rows, tasks[i].cols,
+ janas_gpu_can(g, &tasks[i]) ? "" : " (CPU)");
+ fprintf(stderr, "\n");
+ }
}
if (sh && sh->off > 0) {
/* the GPU was late even with the smallest share: CPU for a while */
diff --git a/src/llm/gpu.h b/src/llm/gpu.h
index 24cc9a1..a94b287 100644
--- a/src/llm/gpu.h
+++ b/src/llm/gpu.h
@@ -23,6 +23,29 @@
struct janas_gpu;
+/*
+ * Q6_K in the GPU's aligned copy (JANAS_GPU_REPACK=1 with the whole token,
+ * model_gpu.c): each 210-byte block padded to 224 - ql 128, qh 64, scales
+ * 16, d at byte 208 - so that every part starts on 16 bytes. Only the GPU
+ * reads it, only for single vectors; a Q6_K_P block with its three planes
+ * becomes the Q6_K block it came from.
+ */
+#define JANAS_Q6_K_A 216
+#define JANAS_Q6KA_BLOCK 224
+
+/*
+ * The single token's copies in tiles of JANAS_TILE rows (JANAS_GPU_REPACK=2:
+ * the Q6_K and the Q4_K matrices with rows of 32 blocks and more; 3: every
+ * Q4_K), block b of a tile's rows side by side, so that the subgroups (a
+ * row each) read neighbouring memory at the same time: faster for long
+ * rows (Qwen3-4B's down matrices), slower for short ones on the
+ * development laptop's integrated GPU. Block b of row r is block ((r / T)
+ * nb + b) T + r % T; rows padded to a whole tile.
+ */
+#define JANAS_TILE 64
+#define JANAS_Q4_K_T 217
+#define JANAS_Q6_K_AT 218
+
struct janas_gpu *janas_gpu_create(char *err, size_t err_len);
void janas_gpu_destroy(struct janas_gpu *g);
diff --git a/src/llm/gpu_impl.h b/src/llm/gpu_impl.h
new file mode 100644
index 0000000..7297739
--- /dev/null
+++ b/src/llm/gpu_impl.h
@@ -0,0 +1,246 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * gpu_impl.h - the insides of the GPU (private to gpu.c and gpu_token.c):
+ * the Vulkan functions it loads, its regions and stages, and the helpers
+ * that record a product for a command buffer. Only with the GPU in the
+ * build.
+ */
+#ifndef JANAS_LLM_GPU_IMPL_H
+#define JANAS_LLM_GPU_IMPL_H
+
+#include "gpu.h"
+
+#if defined(JANAS_GPU_SPV) && __has_include(<vulkan/vulkan.h>)
+
+/* The push constants a shader may take: every Vulkan device gives 128. */
+#define JANAS_G_PUSH_BYTES 128
+/* the kinds of product shader (gpu.c's prod_index) */
+#define N_PROD 12
+
+#define VK_NO_PROTOTYPES
+#include <dlfcn.h>
+#include <immintrin.h>
+#include <pthread.h>
+#include <stdatomic.h>
+#include <unistd.h>
+#include <vulkan/vulkan.h>
+
+#define MAX_REGIONS 32
+#define MAX_PENDING 64
+#define MAX_XCACHE 8
+#define X_STAGE_BYTES ((size_t)8 << 20)
+#define Y_STAGE_BYTES ((size_t)32 << 20)
+#define ROWS_PER_GROUP 64 /* local_size_x of the shader */
+#define NV_PER_GROUP 8 /* its NV */
+#define GPU_BLOCK 320 /* a Q8_K block in the shader's layout */
+#define SHARE_SLOTS 64
+#define MAX_GROUP 64
+
+/* instance-level functions, then device-level ones */
+#define VK_INSTANCE_FUNCS(X) \
+ X(vkDestroyInstance) \
+ X(vkEnumeratePhysicalDevices) \
+ X(vkGetPhysicalDeviceProperties) \
+ X(vkGetPhysicalDeviceProperties2) \
+ X(vkGetPhysicalDeviceFeatures2) \
+ X(vkGetPhysicalDeviceMemoryProperties) \
+ X(vkGetPhysicalDeviceQueueFamilyProperties) \
+ X(vkEnumerateDeviceExtensionProperties) \
+ X(vkCreateDevice) \
+ X(vkGetDeviceProcAddr)
+#define VK_DEVICE_FUNCS(X) \
+ X(vkDestroyDevice) \
+ X(vkGetDeviceQueue) \
+ X(vkCreateBuffer) \
+ X(vkDestroyBuffer) \
+ X(vkGetBufferMemoryRequirements) \
+ X(vkAllocateMemory) \
+ X(vkFreeMemory) \
+ X(vkBindBufferMemory) \
+ X(vkMapMemory) \
+ X(vkInvalidateMappedMemoryRanges) \
+ X(vkFlushMappedMemoryRanges) \
+ X(vkGetBufferDeviceAddress) \
+ X(vkGetMemoryHostPointerPropertiesEXT) \
+ X(vkCreateShaderModule) \
+ X(vkDestroyShaderModule) \
+ X(vkCreatePipelineLayout) \
+ X(vkDestroyPipelineLayout) \
+ X(vkCreateComputePipelines) \
+ X(vkDestroyPipeline) \
+ X(vkCreateCommandPool) \
+ X(vkDestroyCommandPool) \
+ X(vkAllocateCommandBuffers) \
+ X(vkFreeCommandBuffers) \
+ X(vkResetCommandBuffer) \
+ X(vkBeginCommandBuffer) \
+ X(vkEndCommandBuffer) \
+ X(vkCmdBindPipeline) \
+ X(vkCmdPushConstants) \
+ X(vkCmdDispatch) \
+ X(vkCmdPipelineBarrier) \
+ X(vkCmdCopyBuffer) \
+ X(vkWaitForFences) \
+ X(vkCreateFence) \
+ X(vkDestroyFence) \
+ X(vkResetFences) \
+ X(vkGetFenceStatus) \
+ X(vkQueueSubmit) \
+ X(vkCreateQueryPool) \
+ X(vkDestroyQueryPool) \
+ X(vkCmdResetQueryPool) \
+ X(vkCmdWriteTimestamp) \
+ X(vkGetQueryPoolResults)
+
+struct region {
+ const uint8_t *host;
+ size_t bytes;
+ VkBuffer buf;
+ VkDeviceMemory mem;
+ VkDeviceAddress addr;
+ int coherent; /* allocated regions: else flushed after host writes */
+};
+
+struct stage {
+ VkBuffer buf;
+ VkDeviceMemory mem;
+ uint8_t *map;
+ VkDeviceAddress addr;
+ size_t bytes;
+ int coherent; /* else invalidated before the host reads it */
+};
+
+struct pending {
+ float *y; /* the task's output */
+ size_t rows, nv; /* rows computed by the GPU, vectors */
+ size_t y_stride; /* the task's */
+ size_t off; /* in the Y stage */
+};
+
+/* The push constants of the shaders (level and the bare planes: Q6_K_P
+ only). */
+struct push {
+ uint32_t w[2], x[2], y[2];
+ uint32_t rows, nb, nv, xs, ys, level;
+ uint32_t p1[2], p0[2];
+};
+
+struct janas_gpu {
+ void *lib;
+ PFN_vkGetInstanceProcAddr gipa;
+#define DECL(f) PFN_##f f;
+ VK_INSTANCE_FUNCS(DECL)
+ VK_DEVICE_FUNCS(DECL)
+#undef DECL
+ VkInstance inst;
+ VkPhysicalDevice pd;
+ VkDevice dev;
+ VkQueue queue;
+ VkShaderModule sm, sm6, sm6p, sm5, sm80, sm32[4], smx4, sm3, smi3, sma;
+ VkPipelineLayout pl;
+ VkPipeline pipe, pipe6, pipe6p, pipe5, pipe80, pipea; /* Q4_K, Q6_K,
+ Q6_K_P, Q5_K,
+ Q8_0, experts'
+ activation */
+ /* blocks of 32: Q4_0, IQ4_NL, Q4_1, Q5_1 (b32_matvec's KIND) */
+ VkPipeline pipe32[4];
+ VkPipeline pipex4, pipe3, pipei3; /* IQ4_XS, Q3_K, IQ3_S */
+ /* the product shaders made for a single vector (prod_index) */
+ VkShaderModule pm1[N_PROD];
+ VkPipeline pp1[N_PROD];
+ /* ... and a subgroup per row for a single vector, where written (NULL:
+ pp1): neighbouring lanes read neighbouring memory */
+ VkShaderModule rm[N_PROD];
+ VkPipeline rp[N_PROD];
+ VkShaderModule rm_q6ka; /* ... and the aligned copy of Q6_K */
+ VkPipeline rp_q6ka;
+ VkShaderModule rm_tile[2]; /* ... and the tiled copies: Q4_K_T, Q6_K_AT */
+ VkPipeline rp_tile[2];
+ /* the same for several vectors at once (a speculative pass's drafts):
+ [k] up to 2 << k of them; [][3] the aligned Q6_K */
+ VkShaderModule rmv[3][4];
+ VkPipeline rpv[3][4];
+ VkCommandPool cp;
+ VkCommandBuffer cb;
+ VkFence fence;
+ VkPhysicalDeviceMemoryProperties mp;
+ struct region reg[MAX_REGIONS];
+ int n_reg;
+ struct stage xs, ys;
+ struct pending pend[MAX_PENDING];
+ size_t n_pend;
+ int busy, broken;
+ char name[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE];
+ uint32_t sg; /* subgroup size the shader runs with */
+ int discrete; /* weights copied to its memory, not shared */
+ int host_import; /* VK_EXT_external_memory_host available */
+ int sg_control; /* the size is required (else the device's fixed one) */
+ uint32_t sg_min, sg_max; /* the sizes it may be given (sg_control) */
+ /* the GPU's share of the rows, per product shape */
+ struct share {
+ uint64_t key;
+ float f;
+ uint32_t calls, waits;
+ double t_begin, t_cpu, t_wait, t_copy; /* seconds, verbose only */
+ uint64_t rows_gpu, rows_all;
+ uint32_t off; /* calls left on the CPU alone */
+ uint32_t seen[4]; /* the type sets printed (JANAS_GPU_VERBOSE=2) */
+ } share[SHARE_SLOTS];
+ size_t min_n;
+ size_t full_n; /* from this many vectors the GPU takes every row */
+ int verbose, nospin, block_wait;
+ double t_waited; /* last janas_gpu_finish */
+ size_t y_used; /* bytes of the Y stage written by the last group */
+ double t_conv, t_rec, t_sub; /* verbose: time in janas_gpu_begin */
+ VkDeviceSize atom; /* nonCoherentAtomSize */
+ float ts_period; /* nanoseconds a timestamp tick */
+ /* keep-alive: an empty dispatch every keep_us while running, so that
+ the GPU does not fall asleep between products (waking it costs up to
+ ~0.5 ms per submission) */
+ pthread_mutex_t qlock; /* the queue is shared with the keep-alive */
+ pthread_t ka;
+ int ka_running;
+ atomic_int ka_stop;
+ atomic_int ka_wanted; /* only while passes use the GPU */
+ unsigned keep_us;
+ VkCommandBuffer ka_cb;
+ VkFence ka_fence;
+};
+
+/* Helpers shared by gpu.c and gpu_token.c (defined in gpu.c). */
+int janas_g_mem_type(const struct janas_gpu *g, uint32_t bits,
+ VkMemoryPropertyFlags want);
+VkDeviceAddress janas_g_buffer_address(struct janas_gpu *g, VkBuffer b);
+int janas_g_make_stage(struct janas_gpu *g, struct stage *s, size_t bytes,
+ int cached);
+VkResult janas_g_make_pipeline(struct janas_gpu *g, const uint32_t *code,
+ size_t bytes, VkShaderModule *sm,
+ VkPipeline *pipe, uint32_t kind);
+/* ... with nv vectors per workgroup instead of eight */
+VkResult janas_g_make_pipeline_nv(struct janas_gpu *g, const uint32_t *code,
+ size_t bytes, VkShaderModule *sm,
+ VkPipeline *pipe, uint32_t kind, uint32_t nv);
+/* ... with subgroups of sg lanes where the device lets the size be chosen
+ and allows it (else the chosen size): the size the pipeline got, 0 on
+ failure. */
+uint32_t janas_g_make_pipeline_sg(struct janas_gpu *g, const uint32_t *code,
+ size_t bytes, VkShaderModule *sm,
+ VkPipeline *pipe, uint32_t kind, uint32_t sg);
+const struct region *janas_g_find_region(const struct janas_gpu *g,
+ const void *p, size_t bytes);
+void janas_g_push_addr(uint32_t out[2], VkDeviceAddress a);
+void janas_g_compute_barrier(struct janas_gpu *g);
+int janas_g_x_in_32(int type);
+/*
+ * Records the product of rows of a task (its weights in a region the GPU
+ * holds) with nv = t->n_vec vectors at xa (the shader's layout, blocks of
+ * GPU_BLOCK bytes: the 32-block one where janas_g_x_in_32), into ya with
+ * row stride ys floats: binds its pipeline if bound is another. 0 or -1.
+ */
+int janas_g_record_task(struct janas_gpu *g, VkPipeline *bound,
+ const struct janas_matvec_task *t, size_t rows,
+ VkDeviceAddress xa, VkDeviceAddress ya, size_t ys);
+
+#endif
+#endif
diff --git a/src/llm/gpu_token.c b/src/llm/gpu_token.c
new file mode 100644
index 0000000..5aba459
--- /dev/null
+++ b/src/llm/gpu_token.c
@@ -0,0 +1,696 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * gpu_token.c - a whole token on the GPU with one submission (see
+ * gpu_token.h).
+ */
+#include "gpu_token.h"
+
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "gpu_impl.h"
+#include "quant.h"
+
+#if defined(JANAS_GPU_SPV) && __has_include(<vulkan/vulkan.h>)
+
+#include "norm_quant.h" /* janas_spv_norm_quant */
+#include "qk_rope.h" /* janas_spv_qk_rope */
+#include "attn_decode.h" /* janas_spv_attn_decode */
+#include "attn_merge.h" /* janas_spv_attn_merge */
+
+/* The push constants of each shader, laid out as its GLSL block. */
+struct push_nq {
+ uint32_t x[2], add[2], w[2], xo[2], q256[2], q32[2];
+ uint32_t d;
+ float eps;
+};
+struct push_qk {
+ uint32_t qkv[2], qn[2], kn[2], rope[2], kc[2], vc[2], ks[2], vs[2];
+ uint32_t n_head, n_kv, hd, n_rot, cap, qs;
+ float eps;
+ uint32_t pad, pos[2]; /* the position's buffer, 8-byte aligned */
+};
+struct push_at {
+ uint32_t q[2], kc[2], vc[2], ks[2], vs[2], part[2];
+ uint32_t n_head, n_kv, hd, cap, nch;
+ float scale;
+ uint32_t qs, ps;
+ uint32_t pos[2]; /* the position's buffer */
+};
+struct push_am {
+ uint32_t part[2], q256[2], q32[2];
+ uint32_t hd, nch, ps, pad;
+ uint32_t pos[2]; /* 8-byte aligned, as the GLSL block puts it */
+};
+/* The attention's positions a run (attn_decode.comp C), and the shapes its
+ shared memory takes: the query heads of a KV head times hd, and times a
+ run. */
+#define ATT_RUN 128
+#define ATT_MAXQ 2048
+#define ATT_MAXS 1024
+
+/* The attention's first step in subgroups of 16 where the size may be
+ chosen (JANAS_GPU_ATT_SG=n another): twice the lanes a hardware thread
+ of the integrated GPU, its latencies better hidden - 11.7 -> 9.9 ms a
+ token at 4000 positions - where the products lose with them. */
+static uint32_t att_sg(void)
+{
+ const char *e = getenv("JANAS_GPU_ATT_SG");
+ return e ? (uint32_t)atoi(e) : 16;
+}
+struct push_ac {
+ uint32_t g[2], u[2], x[2];
+ uint32_t blocks;
+};
+_Static_assert(sizeof(struct push_qk) <= JANAS_G_PUSH_BYTES, "push size");
+_Static_assert(sizeof(struct push_at) <= JANAS_G_PUSH_BYTES, "push size");
+/* the uvec2 members where GLSL puts them: on 8 bytes */
+_Static_assert(offsetof(struct push_qk, pos) % 8 == 0, "push layout");
+_Static_assert(offsetof(struct push_at, pos) % 8 == 0, "push layout");
+_Static_assert(offsetof(struct push_am, pos) % 8 == 0, "push layout");
+/* The most tokens a block takes (the model's own blocks: model.h
+ JANAS_LLM_MAX_BLOCK), and the memory the attention's runs may take for
+ them. */
+#define TOK_MAX_BLOCK 64
+#define TOK_PART_BUDGET ((size_t)64 << 20)
+
+/* JANAS_GPU_TOKEN_PROFILE=1: the GPU's own timestamps after each phase of
+ the token, summed per phase and printed when the model is closed */
+enum {
+ PH_NORM,
+ PH_QKV,
+ PH_ROPE,
+ PH_ATTN,
+ PH_MERGE,
+ PH_WO,
+ PH_GATEUP,
+ PH_ACT,
+ PH_DOWN,
+ PH_OUT,
+ PH_N
+};
+static const char *const ph_name[PH_N] = {
+ "norm+quant", "q k v", "q k norm+rope", "attention", "attn merge",
+ "wo", "gate+up", "act", "down", "output"};
+#define MAX_TS 1024
+
+struct janas_gpu_tok {
+ /* its own command buffers, one per number of tokens n (1 .. nb) and
+ logits of the last token, of all or of none ([n][all]: 0, 1, 2),
+ each recorded once:
+ the position is read from the buffer at o_pos, so every block of n
+ tokens submits the same commands */
+ uint32_t nb;
+ VkCommandBuffer cb[TOK_MAX_BLOCK + 1][3];
+ int prof; /* timestamps in the commands being recorded (n = 1) */
+ VkQueryPool qp; /* timestamps, if profiling */
+ uint32_t n_ts; /* written this token */
+ uint8_t ph_of[MAX_TS]; /* the phase each timestamp closes */
+ double ph_ns[PH_N];
+ double wall_ns; /* submission to the fence, as the CPU sees it */
+ double copy_ns; /* the logits copied out */
+ uint64_t tokens;
+ VkShaderModule sm_nq, sm_qk, sm_at, sm_am;
+ VkPipeline p_nq, p_qk, p_at, p_am;
+ struct stage buf; /* every intermediate, one allocation */
+ /* offsets into buf, each nb tokens' worth */
+ uint32_t nch; /* the attention's runs of positions, for the cache */
+ size_t part_tok; /* a token's runs, floats */
+ size_t o_part;
+ size_t o_x, o_x1, o_q256, o_q32, o_qkv, o_ywo, o_gu, o_h, o_yd, o_rope,
+ o_logits, o_pos;
+};
+
+int janas_gpu_shares_host(const struct janas_gpu *g)
+{
+ return g && !g->broken && !g->discrete && g->host_import &&
+ !getenv("JANAS_GPU_COPY");
+}
+
+/* The GPU's address of host memory in one of its regions, 0 if none. */
+static VkDeviceAddress addr_of(const struct janas_gpu *g, const void *p,
+ size_t bytes)
+{
+ const struct region *rg = janas_g_find_region(g, p, bytes);
+ return rg ? rg->addr + (VkDeviceAddress)((const uint8_t *)p - rg->host) : 0;
+}
+
+static size_t take(size_t *at, size_t bytes)
+{
+ size_t o = *at;
+ *at += (bytes + 255) / 256 * 256;
+ return o;
+}
+
+static int fail(char *err, size_t len, const char *why)
+{
+ snprintf(err, len, "%s", why);
+ return -1;
+}
+
+/* Whether the model's pieces are all where the GPU can read them. */
+static int check_model(const struct janas_gpu *g,
+ const struct janas_gpu_tok_model *md, char *err,
+ size_t len)
+{
+ uint32_t qd = md->n_head * md->hd, kvd = md->n_kv * md->hd;
+ if (md->dm % JANAS_QK || qd % JANAS_QK || md->ff % JANAS_QK ||
+ md->dm > 8192 || qd > 8192 || md->hd > 512 || md->hd % 16 ||
+ md->n_rot > md->hd || md->n_kv == 0 || md->n_head % md->n_kv ||
+ md->n_head / md->n_kv * md->hd > ATT_MAXQ ||
+ md->n_head / md->n_kv * ATT_RUN > ATT_MAXS)
+ return fail(err, len, "a shape the token's shaders do not take");
+ for (uint32_t l = 0; l < md->n_layer; l++) {
+ const struct janas_gpu_tok_layer *ly = &md->layers[l];
+ const struct janas_matvec_task *t[7] = {
+ &ly->wq, &ly->wk, &ly->wv, &ly->wo, &ly->gate, &ly->up, &ly->down};
+ for (int i = 0; i < 7; i++)
+ if (!janas_gpu_can(g, t[i]))
+ return fail(err, len, "a weight the GPU cannot compute");
+ if (janas_g_x_in_32(ly->down.type))
+ return fail(err, len, "a down matrix in blocks of 32");
+ size_t cache = (size_t)md->n_kv * md->cap * md->hd;
+ if (!addr_of(g, ly->attn_norm, md->dm * 4) ||
+ !addr_of(g, ly->ffn_norm, md->dm * 4) ||
+ !addr_of(g, ly->q_norm, md->hd * 4) ||
+ !addr_of(g, ly->k_norm, md->hd * 4) || !addr_of(g, ly->kc, cache) ||
+ !addr_of(g, ly->vc, cache) ||
+ !addr_of(g, ly->ks, (size_t)md->n_kv * md->cap * 4) ||
+ !addr_of(g, ly->vs, (size_t)md->n_kv * md->cap * 4))
+ return fail(err, len,
+ "a norm or the KV cache out of the GPU's "
+ "reach");
+ }
+ if (!janas_gpu_can(g, &md->output) || !addr_of(g, md->out_norm, md->dm * 4))
+ return fail(err, len, "the output head out of the GPU's reach");
+ (void)kvd;
+ return 0;
+}
+
+struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
+ const struct janas_gpu_tok_model *md,
+ char *err, size_t err_len)
+{
+ if (!janas_gpu_shares_host(g)) {
+ fail(err, err_len, "the GPU does not read the host's memory in place");
+ return NULL;
+ }
+ if (check_model(g, md, err, err_len) != 0)
+ return NULL;
+ struct janas_gpu_tok *t = calloc(1, sizeof(*t));
+ if (!t) {
+ fail(err, err_len, "out of memory");
+ return NULL;
+ }
+ uint32_t qd = md->n_head * md->hd, kvd = md->n_kv * md->hd;
+ size_t big = md->dm > qd ? md->dm : qd;
+ size_t at = 0;
+ /* the attention's runs: per token, query head and run, hd sums, m and
+ l; as many tokens a block as they leave room for */
+ t->nch = (md->cap + ATT_RUN - 1) / ATT_RUN;
+ t->part_tok = (size_t)md->n_head * t->nch * (md->hd + 2);
+ size_t nb = TOK_PART_BUDGET / (t->part_tok * 4);
+ t->nb = nb < 1 ? 1 : nb > TOK_MAX_BLOCK ? TOK_MAX_BLOCK : (uint32_t)nb;
+ nb = t->nb;
+ t->o_x = take(&at, nb * md->dm * 4);
+ t->o_x1 = take(&at, nb * md->dm * 4); /* the residual's other buffer */
+ t->o_q256 = take(&at, nb * big / JANAS_QK * 320);
+ t->o_q32 = take(&at, nb * big / JANAS_QK * 320);
+ t->o_qkv = take(&at, nb * (qd + 2 * kvd) * 4);
+ t->o_ywo = take(&at, nb * md->dm * 4);
+ t->o_gu = take(&at, nb * md->ff * 2 * 4);
+ t->o_h = take(&at, nb * md->ff / JANAS_QK * 320);
+ t->o_yd = take(&at, nb * md->dm * 4);
+ t->o_rope = take(&at, nb * md->n_rot * 4);
+ t->o_logits = take(&at, nb * md->n_vocab * 4);
+ t->o_pos = take(&at, 16);
+ t->o_part = take(&at, nb * t->part_tok * 4);
+ /* cached for the host (the logits are read on the CPU: 2.5 ms a token
+ from uncached memory on the development laptop), flushed and
+ invalidated by hand where it is not coherent */
+ if (janas_g_make_stage(g, &t->buf, at, 1) != 0 ||
+ janas_g_make_pipeline(g, janas_spv_norm_quant,
+ sizeof(janas_spv_norm_quant), &t->sm_nq, &t->p_nq,
+ 0) != VK_SUCCESS ||
+ janas_g_make_pipeline(g, janas_spv_qk_rope, sizeof(janas_spv_qk_rope),
+ &t->sm_qk, &t->p_qk, 0) != VK_SUCCESS ||
+ janas_g_make_pipeline_sg(
+ g, janas_spv_attn_decode, sizeof(janas_spv_attn_decode), &t->sm_at,
+ &t->p_at, md->n_head / md->n_kv, att_sg()) == 0 ||
+ janas_g_make_pipeline(g, janas_spv_attn_merge,
+ sizeof(janas_spv_attn_merge), &t->sm_am, &t->p_am,
+ 0) != VK_SUCCESS) {
+ fail(err, err_len, "cannot create the token's buffers or shaders");
+ janas_gpu_tok_destroy(g, t);
+ return NULL;
+ }
+ const char *pe = getenv("JANAS_GPU_TOKEN_PROFILE");
+ if (pe && atoi(pe) > 0 && g->ts_period > 0) {
+ VkQueryPoolCreateInfo qi = {
+ .sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
+ .queryType = VK_QUERY_TYPE_TIMESTAMP,
+ .queryCount = MAX_TS};
+ if (g->vkCreateQueryPool(g->dev, &qi, NULL, &t->qp) != VK_SUCCESS)
+ t->qp = VK_NULL_HANDLE;
+ }
+ return t;
+}
+
+void janas_gpu_tok_destroy(struct janas_gpu *g, struct janas_gpu_tok *t)
+{
+ if (!t)
+ return;
+ if (t->qp) {
+ double all = 0;
+ for (int i = 0; i < PH_N; i++)
+ all += t->ph_ns[i];
+ if (t->tokens) {
+ fprintf(stderr,
+ "gpu token profile, %llu tokens, %.2f ms a token "
+ "(%.2f ms from submission to fence, %.2f ms copying the "
+ "logits):\n",
+ (unsigned long long)t->tokens, all / t->tokens * 1e-6,
+ t->wall_ns / t->tokens * 1e-6,
+ t->copy_ns / t->tokens * 1e-6);
+ for (int i = 0; i < PH_N; i++)
+ fprintf(stderr, " %-14s %7.3f ms %5.1f%%\n", ph_name[i],
+ t->ph_ns[i] / t->tokens * 1e-6,
+ all > 0 ? 100.0 * t->ph_ns[i] / all : 0.0);
+ }
+ g->vkDestroyQueryPool(g->dev, t->qp, NULL);
+ }
+ for (uint32_t n = 0; n <= TOK_MAX_BLOCK; n++)
+ for (int a = 0; a < 3; a++)
+ if (t->cb[n][a])
+ g->vkFreeCommandBuffers(g->dev, g->cp, 1, &t->cb[n][a]);
+ VkPipeline p[4] = {t->p_nq, t->p_qk, t->p_at, t->p_am};
+ VkShaderModule s[4] = {t->sm_nq, t->sm_qk, t->sm_at, t->sm_am};
+ for (int i = 0; i < 4; i++) {
+ if (p[i])
+ g->vkDestroyPipeline(g->dev, p[i], NULL);
+ if (s[i])
+ g->vkDestroyShaderModule(g->dev, s[i], NULL);
+ }
+ if (t->buf.buf)
+ g->vkDestroyBuffer(g->dev, t->buf.buf, NULL);
+ if (t->buf.mem)
+ g->vkFreeMemory(g->dev, t->buf.mem, NULL);
+ free(t);
+}
+
+/* Bytes [off, off + bytes) of the token's buffer out of the CPU's caches
+ (flush) or reloaded from memory (!flush), where it is not coherent. */
+static void sync_range(struct janas_gpu *g, struct janas_gpu_tok *t, size_t off,
+ size_t bytes, int flush)
+{
+ if (t->buf.coherent)
+ return;
+ VkDeviceSize a = off / g->atom * g->atom;
+ VkDeviceSize e = (off + bytes + g->atom - 1) / g->atom * g->atom;
+ VkMappedMemoryRange mr = {.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
+ .memory = t->buf.mem,
+ .offset = a,
+ .size =
+ e >= t->buf.bytes ? VK_WHOLE_SIZE : e - a};
+ if (flush)
+ g->vkFlushMappedMemoryRanges(g->dev, 1, &mr);
+ else
+ g->vkInvalidateMappedMemoryRanges(g->dev, 1, &mr);
+}
+
+/* A timestamp closing phase ph (with profiling on). */
+static void stamp(struct janas_gpu *g, struct janas_gpu_tok *t, int ph)
+{
+ if (!t->qp || !t->prof || t->n_ts >= MAX_TS)
+ return;
+ g->vkCmdWriteTimestamp(g->cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, t->qp,
+ t->n_ts);
+ t->ph_of[t->n_ts++] = (uint8_t)ph;
+}
+
+static void bind(struct janas_gpu *g, VkPipeline *bound, VkPipeline p)
+{
+ if (*bound != p) {
+ g->vkCmdBindPipeline(g->cb, VK_PIPELINE_BIND_POINT_COMPUTE, p);
+ *bound = p;
+ }
+}
+
+static void push(struct janas_gpu *g, const void *pc, size_t bytes)
+{
+ g->vkCmdPushConstants(g->cb, g->pl, VK_SHADER_STAGE_COMPUTE_BIT, 0,
+ (uint32_t)bytes, pc);
+}
+
+/* x (+ add, then stored at xo) normalized by w (0: not), quantized into
+ q256 and q32: a workgroup per block of 256 values. */
+static void rec_norm_quant(struct janas_gpu *g, struct janas_gpu_tok *t,
+ VkPipeline *bound, VkDeviceAddress x,
+ VkDeviceAddress add, VkDeviceAddress w,
+ VkDeviceAddress xo, uint32_t d, float eps,
+ uint32_t n)
+{
+ struct push_nq pc = {.d = d, .eps = eps};
+ janas_g_push_addr(pc.x, x);
+ janas_g_push_addr(pc.add, add);
+ janas_g_push_addr(pc.w, w);
+ janas_g_push_addr(pc.xo, xo);
+ janas_g_push_addr(pc.q256, t->buf.addr + t->o_q256);
+ janas_g_push_addr(pc.q32, t->buf.addr + t->o_q32);
+ bind(g, bound, t->p_nq);
+ push(g, &pc, sizeof(pc));
+ g->vkCmdDispatch(g->cb, d / JANAS_QK, n, 1); /* y: the vector */
+ janas_g_compute_barrier(g);
+}
+
+/* A product of the task's weights with n quantized vectors (from byte xoff
+ of the q256 or q32 layout, cols / 256 blocks apart), into y (ys floats
+ apart; 0: rows). */
+static int rec_product(struct janas_gpu *g, struct janas_gpu_tok *t,
+ VkPipeline *bound, const struct janas_matvec_task *w,
+ size_t xoff, VkDeviceAddress y, uint32_t n, size_t ys)
+{
+ struct janas_matvec_task k = *w;
+ k.n_vec = n;
+ k.x_stride = 0;
+ k.y_stride = 0;
+ VkDeviceAddress xa =
+ t->buf.addr + xoff + (janas_g_x_in_32(k.type) ? t->o_q32 : t->o_q256);
+ return janas_g_record_task(g, bound, &k, k.rows, xa, y, ys ? ys : k.rows);
+}
+
+/* The commands of a block of n tokens into g->cb (the caller points it at
+ the block's buffer): every layer, then the output head for the tokens
+ from first on (none if first is n); the position of the first token
+ comes from the buffer.
+ A single token takes the layers' GPU copies (JANAS_GPU_REPACK), a block
+ the weights as they are (the copies' shaders take one vector). */
+static int record(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md, uint32_t n,
+ uint32_t first)
+{
+ uint32_t qd = md->n_head * md->hd, kvd = md->n_kv * md->hd;
+ size_t qs = qd + 2 * kvd;
+ const struct janas_gpu_tok_layer *layers =
+ n > 1 && md->blayers ? md->blayers : md->layers;
+ const struct janas_matvec_task *output =
+ n > 1 && md->blayers ? &md->boutput : &md->output;
+ /* the residual: read from X, the sum with a layer's output written to
+ XN, the two swapped (every block starts from o_x, the same commands) */
+ VkDeviceAddress B = t->buf.addr, X = B + t->o_x, XN = B + t->o_x1, SW,
+ QKV = B + t->o_qkv, YWO = B + t->o_ywo, GU = B + t->o_gu,
+ H = B + t->o_h, YD = B + t->o_yd, ROPE = B + t->o_rope,
+ POS = B + t->o_pos;
+ if (g->vkResetCommandBuffer(g->cb, 0) != VK_SUCCESS)
+ return -1;
+ VkCommandBufferBeginInfo bb = {
+ .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = 0};
+ if (g->vkBeginCommandBuffer(g->cb, &bb) != VK_SUCCESS)
+ return -1;
+ VkPipeline bound = VK_NULL_HANDLE;
+ size_t cache = (size_t)md->n_kv * md->cap * md->hd;
+ t->prof = n == 1;
+ if (t->qp && t->prof) {
+ t->n_ts = 0;
+ g->vkCmdResetQueryPool(g->cb, t->qp, 0, MAX_TS);
+ stamp(g, t, PH_N); /* the start */
+ }
+ for (uint32_t l = 0; l < md->n_layer; l++) {
+ const struct janas_gpu_tok_layer *ly = &layers[l];
+ /* the previous layer's feed-forward added, then this one's norm */
+ rec_norm_quant(g, t, &bound, X, l ? YD : 0,
+ addr_of(g, ly->attn_norm, md->dm * 4), l ? XN : 0,
+ md->dm, md->eps, n);
+ if (l)
+ SW = X, X = XN, XN = SW;
+ stamp(g, t, PH_NORM);
+ /* q, k and v of each token side by side, qs floats a token */
+ if (rec_product(g, t, &bound, &ly->wq, 0, QKV, n, qs) != 0 ||
+ rec_product(g, t, &bound, &ly->wk, 0, QKV + (size_t)qd * 4, n,
+ qs) != 0 ||
+ rec_product(g, t, &bound, &ly->wv, 0, QKV + (size_t)(qd + kvd) * 4,
+ n, qs) != 0)
+ return -1;
+ janas_g_compute_barrier(g);
+ stamp(g, t, PH_QKV);
+ struct push_qk pq = {.n_head = md->n_head,
+ .n_kv = md->n_kv,
+ .hd = md->hd,
+ .n_rot = md->n_rot,
+ .cap = md->cap,
+ .qs = (uint32_t)qs,
+ .eps = md->eps};
+ janas_g_push_addr(pq.pos, POS);
+ janas_g_push_addr(pq.qkv, QKV);
+ janas_g_push_addr(pq.qn, addr_of(g, ly->q_norm, md->hd * 4));
+ janas_g_push_addr(pq.kn, addr_of(g, ly->k_norm, md->hd * 4));
+ janas_g_push_addr(pq.rope, ROPE);
+ janas_g_push_addr(pq.kc, addr_of(g, ly->kc, cache));
+ janas_g_push_addr(pq.vc, addr_of(g, ly->vc, cache));
+ janas_g_push_addr(pq.ks, addr_of(g, ly->ks, cache / md->hd * 4));
+ janas_g_push_addr(pq.vs, addr_of(g, ly->vs, cache / md->hd * 4));
+ bind(g, &bound, t->p_qk);
+ push(g, &pq, sizeof(pq));
+ g->vkCmdDispatch(g->cb, md->n_head + md->n_kv, n, 1);
+ janas_g_compute_barrier(g);
+ stamp(g, t, PH_ROPE);
+ /* the attention: runs of positions per KV head, then joined; token
+ j of the block sees positions 0 .. pos + j, the block's own keys
+ and values written above */
+ struct push_at pa = {.n_head = md->n_head,
+ .n_kv = md->n_kv,
+ .hd = md->hd,
+ .cap = md->cap,
+ .nch = t->nch,
+ .scale = md->attn_scale,
+ .qs = (uint32_t)qs,
+ .ps = (uint32_t)t->part_tok};
+ janas_g_push_addr(pa.pos, POS);
+ janas_g_push_addr(pa.q, QKV);
+ janas_g_push_addr(pa.kc, addr_of(g, ly->kc, cache));
+ janas_g_push_addr(pa.vc, addr_of(g, ly->vc, cache));
+ janas_g_push_addr(pa.ks, addr_of(g, ly->ks, cache / md->hd * 4));
+ janas_g_push_addr(pa.vs, addr_of(g, ly->vs, cache / md->hd * 4));
+ janas_g_push_addr(pa.part, B + t->o_part);
+ bind(g, &bound, t->p_at);
+ push(g, &pa, sizeof(pa));
+ g->vkCmdDispatch(g->cb, md->n_kv * t->nch, n, 1);
+ janas_g_compute_barrier(g);
+ stamp(g, t, PH_ATTN);
+ /* the runs joined and the output quantized for wo, a workgroup a
+ block of 256 */
+ struct push_am pm = {
+ .hd = md->hd, .nch = t->nch, .ps = (uint32_t)t->part_tok};
+ janas_g_push_addr(pm.part, B + t->o_part);
+ janas_g_push_addr(pm.q256, B + t->o_q256);
+ janas_g_push_addr(pm.q32, B + t->o_q32);
+ janas_g_push_addr(pm.pos, POS);
+ bind(g, &bound, t->p_am);
+ push(g, &pm, sizeof(pm));
+ g->vkCmdDispatch(g->cb, qd / JANAS_QK, n, 1);
+ janas_g_compute_barrier(g);
+ stamp(g, t, PH_MERGE);
+ /* the output projection */
+ if (rec_product(g, t, &bound, &ly->wo, 0, YWO, n, 0) != 0)
+ return -1;
+ janas_g_compute_barrier(g);
+ stamp(g, t, PH_WO);
+ rec_norm_quant(g, t, &bound, X, YWO,
+ addr_of(g, ly->ffn_norm, md->dm * 4), XN, md->dm,
+ md->eps, n);
+ SW = X, X = XN, XN = SW;
+ stamp(g, t, PH_NORM);
+ /* the feed-forward: gate, up (the n tokens' gates, then their ups),
+ SiLU(gate) up quantized, down */
+ VkDeviceAddress UP = GU + (size_t)n * md->ff * 4;
+ if (rec_product(g, t, &bound, &ly->gate, 0, GU, n, 0) != 0 ||
+ rec_product(g, t, &bound, &ly->up, 0, UP, n, 0) != 0)
+ return -1;
+ janas_g_compute_barrier(g);
+ stamp(g, t, PH_GATEUP);
+ struct push_ac ac = {.blocks = n * md->ff / JANAS_QK};
+ janas_g_push_addr(ac.g, GU);
+ janas_g_push_addr(ac.u, UP);
+ janas_g_push_addr(ac.x, H);
+ bind(g, &bound, g->pipea);
+ push(g, &ac, sizeof(ac));
+ g->vkCmdDispatch(g->cb, n * md->ff / JANAS_QK, 1, 1);
+ janas_g_compute_barrier(g);
+ stamp(g, t, PH_ACT);
+ struct janas_matvec_task dn = ly->down;
+ if (janas_g_record_task(
+ g, &bound,
+ &(struct janas_matvec_task){.type = dn.type,
+ .w = dn.w,
+ .plane = {dn.plane[0], dn.plane[1]},
+ .rows = dn.rows,
+ .cols = dn.cols,
+ .n_vec = n},
+ dn.rows, H, YD, dn.rows) != 0)
+ return -1;
+ janas_g_compute_barrier(g);
+ stamp(g, t, PH_DOWN);
+ }
+ /* the last feed-forward added, the final norm, the output head for
+ tokens first .. n - 1 (none: the residual left in X, the next block's
+ keys and values already in the cache) */
+ if (first < n) {
+ rec_norm_quant(g, t, &bound, X, YD,
+ addr_of(g, md->out_norm, md->dm * 4), 0, md->dm, md->eps,
+ n);
+ if (rec_product(g, t, &bound, output,
+ (size_t)first * (md->dm / JANAS_QK) * 320,
+ B + t->o_logits, n - first, 0) != 0)
+ return -1;
+ }
+ stamp(g, t, PH_OUT);
+ VkMemoryBarrier mb = {.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
+ .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT,
+ .dstAccessMask = VK_ACCESS_HOST_READ_BIT};
+ g->vkCmdPipelineBarrier(g->cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
+ VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &mb, 0, NULL, 0,
+ NULL);
+ if (g->vkEndCommandBuffer(g->cb) != VK_SUCCESS)
+ return -1;
+ return 0;
+}
+
+uint32_t janas_gpu_tok_max_block(const struct janas_gpu_tok *t)
+{
+ return t ? t->nb : 0;
+}
+
+int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md, const float *x,
+ const float *cs, const float *sn, uint32_t pos,
+ uint32_t n, int all, float *logits)
+{
+ if (!t || g->busy || g->broken || n < 1 || n > t->nb || pos + n > md->cap)
+ return -1;
+ uint32_t half = md->n_rot / 2, first = all == 1 ? 0 : all == 2 ? n : n - 1;
+ memcpy(t->buf.map + t->o_x, x, (size_t)n * md->dm * sizeof(float));
+ for (uint32_t j = 0; j < n; j++) {
+ uint8_t *r = t->buf.map + t->o_rope + (size_t)j * md->n_rot * 4;
+ memcpy(r, cs + (size_t)j * half, half * sizeof(float));
+ memcpy(r + half * sizeof(float), sn + (size_t)j * half,
+ half * sizeof(float));
+ }
+ memcpy(t->buf.map + t->o_pos, &pos, sizeof(pos));
+ sync_range(g, t, t->o_x, (size_t)n * md->dm * sizeof(float), 1);
+ sync_range(g, t, t->o_rope, (size_t)n * md->n_rot * sizeof(float), 1);
+ sync_range(g, t, t->o_pos, sizeof(pos), 1);
+ VkCommandBuffer *cb = &t->cb[n][all == 1 && n == 1 ? 0 : all];
+ if (!*cb) {
+ VkCommandBufferAllocateInfo ca = {
+ .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
+ .commandPool = g->cp,
+ .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
+ .commandBufferCount = 1};
+ if (g->vkAllocateCommandBuffers(g->dev, &ca, cb) != VK_SUCCESS) {
+ *cb = VK_NULL_HANDLE;
+ return -1;
+ }
+ VkCommandBuffer keep = g->cb;
+ g->cb = *cb; /* the helpers record into g->cb */
+ int rc = record(g, t, md, n, first);
+ g->cb = keep;
+ if (rc != 0) {
+ g->vkFreeCommandBuffers(g->dev, g->cp, 1, cb);
+ *cb = VK_NULL_HANDLE;
+ return -1;
+ }
+ }
+ VkSubmitInfo sub = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
+ .commandBufferCount = 1,
+ .pCommandBuffers = cb};
+ struct timespec w0, w1;
+ clock_gettime(CLOCK_MONOTONIC, &w0);
+ pthread_mutex_lock(&g->qlock);
+ VkResult r = g->vkQueueSubmit(g->queue, 1, &sub, g->fence);
+ pthread_mutex_unlock(&g->qlock);
+ if (r == VK_SUCCESS)
+ r = g->vkWaitForFences(g->dev, 1, &g->fence, VK_TRUE, UINT64_MAX);
+ if (r != VK_SUCCESS) {
+ g->broken = 1;
+ return -1;
+ }
+ clock_gettime(CLOCK_MONOTONIC, &w1);
+ g->vkResetFences(g->dev, 1, &g->fence);
+ size_t lb = (size_t)(n - first) * md->n_vocab * 4;
+ if (lb) {
+ sync_range(g, t, t->o_logits, lb, 0);
+ memcpy(logits, t->buf.map + t->o_logits, lb);
+ }
+ struct timespec w2;
+ clock_gettime(CLOCK_MONOTONIC, &w2);
+ if (t->qp && n == 1 && t->n_ts > 1) {
+ uint64_t ts[MAX_TS];
+ if (g->vkGetQueryPoolResults(g->dev, t->qp, 0, t->n_ts, sizeof(ts), ts,
+ sizeof(uint64_t),
+ VK_QUERY_RESULT_64_BIT) == VK_SUCCESS) {
+ for (uint32_t i = 1; i < t->n_ts; i++)
+ t->ph_ns[t->ph_of[i]] +=
+ (double)(ts[i] - ts[i - 1]) * g->ts_period;
+ t->tokens++;
+ t->wall_ns += (double)(w1.tv_sec - w0.tv_sec) * 1e9 +
+ (double)(w1.tv_nsec - w0.tv_nsec);
+ t->copy_ns += (double)(w2.tv_sec - w1.tv_sec) * 1e9 +
+ (double)(w2.tv_nsec - w1.tv_nsec);
+ }
+ }
+ return 0;
+}
+
+#else /* no GPU in this build */
+
+struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
+ const struct janas_gpu_tok_model *md,
+ char *err, size_t err_len)
+{
+ (void)g;
+ (void)md;
+ snprintf(err, err_len, "no GPU in this build");
+ return NULL;
+}
+
+void janas_gpu_tok_destroy(struct janas_gpu *g, struct janas_gpu_tok *t)
+{
+ (void)g;
+ (void)t;
+}
+
+uint32_t janas_gpu_tok_max_block(const struct janas_gpu_tok *t)
+{
+ (void)t;
+ return 0;
+}
+
+int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md, const float *x,
+ const float *cs, const float *sn, uint32_t pos,
+ uint32_t n, int all, float *logits)
+{
+ (void)n;
+ (void)all;
+ (void)g;
+ (void)t;
+ (void)md;
+ (void)x;
+ (void)cs;
+ (void)sn;
+ (void)pos;
+ (void)logits;
+ return -1;
+}
+
+int janas_gpu_shares_host(const struct janas_gpu *g)
+{
+ (void)g;
+ return 0;
+}
+
+#endif
diff --git a/src/llm/gpu_token.h b/src/llm/gpu_token.h
new file mode 100644
index 0000000..71c162c
--- /dev/null
+++ b/src/llm/gpu_token.h
@@ -0,0 +1,78 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * gpu_token.h - a whole token on the GPU, with one submission: every layer's
+ * norms, products, RoPE, KV cache and attention, the feed-forward and the
+ * output head recorded in one command buffer, the logits back at the end
+ * (private to the library).
+ *
+ * For now the dense attention models (qwen3's shape: q and k norms, NeoX
+ * RoPE, an eight-bit KV cache, SiLU feed-forward) on a GPU that shares the
+ * host's memory: the weights, the experts' arena and the KV cache are the
+ * CPU's own memory, imported, so the CPU's passes (a prompt in blocks) and
+ * the GPU's tokens read and write the same cache. The products are the
+ * CPU's bit for bit (their shaders); the norms and the attention sum in
+ * the GPU's order.
+ */
+#ifndef JANAS_LLM_GPU_TOKEN_H
+#define JANAS_LLM_GPU_TOKEN_H
+
+#include <stdint.h>
+
+#include "gpu.h"
+#include "matvec.h"
+
+/* One layer: host pointers, all in regions the GPU holds. The products'
+ tasks give type, weights (and planes), rows and cols; their x, y and
+ n_vec are the GPU's own. */
+struct janas_gpu_tok_layer {
+ const float *attn_norm, *q_norm, *k_norm, *ffn_norm;
+ struct janas_matvec_task wq, wk, wv, wo, gate, up, down;
+ int8_t *kc, *vc; /* the layer's KV cache: n_kv x cap x hd bytes */
+ float *ks, *vs; /* its scales: n_kv x cap */
+};
+
+struct janas_gpu_tok_model {
+ uint32_t n_layer, dm, n_head, n_kv, hd, n_rot, ff, n_vocab, cap;
+ float eps, attn_scale;
+ const struct janas_gpu_tok_layer *layers;
+ const float *out_norm;
+ struct janas_matvec_task output;
+ /* for blocks of more than one token, where layers and output hold the
+ GPU's single-vector copies (JANAS_GPU_REPACK): the weights as they
+ are; NULL: layers and output */
+ const struct janas_gpu_tok_layer *blayers;
+ struct janas_matvec_task boutput;
+};
+
+struct janas_gpu_tok;
+
+/* Buffers and shaders for a model of that shape; NULL (the GPU cannot, or
+ out of memory) with the reason in err. */
+struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
+ const struct janas_gpu_tok_model *md,
+ char *err, size_t err_len);
+void janas_gpu_tok_destroy(struct janas_gpu *g, struct janas_gpu_tok *t);
+
+/* The most tokens janas_gpu_tok_run takes at once (0 without t). */
+uint32_t janas_gpu_tok_max_block(const struct janas_gpu_tok *t);
+
+/*
+ * A block of n tokens (1 .. janas_gpu_tok_max_block) whose embeddings are x
+ * (n x dm floats), token j at position pos + j (its keys and values go to
+ * row pos + j of the cache; positions 0 .. pos + j attended), cs and sn
+ * their RoPE tables (n x n_rot / 2 each): the logits (n_vocab each) of
+ * the last token (all 0), of every token (1) or of none (2) into logits. 0, or
+ * -1 with nothing changed but the cache rows pos .. pos + n - 1 (the caller
+ * runs the block on the CPU then).
+ */
+int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md, const float *x,
+ const float *cs, const float *sn, uint32_t pos,
+ uint32_t n, int all, float *logits);
+
+/* Whether the GPU reads the host's memory in place (an integrated GPU with
+ the host-memory import, not JANAS_GPU_COPY): what the token needs. */
+int janas_gpu_shares_host(const struct janas_gpu *g);
+
+#endif
diff --git a/src/llm/model.c b/src/llm/model.c
index fbd4a9f..bb9769c 100644
--- a/src/llm/model.c
+++ b/src/llm/model.c
@@ -331,6 +331,36 @@ int janas_llm_model_shift(struct janas_llm_model *m, uint32_t keep,
static int forward(struct janas_llm_model *m, const int32_t *tokens, uint32_t n,
uint32_t pos0, float *logits, int all_logits);
+/*
+ * Reading ahead where it pays: it costs a router and the reads' submission
+ * on every token (~4 ms on Qwen3-Next-80B), and gains only where the cache
+ * misses many experts. Measured on 30 Sep 2026 (that model, every bit): -3%
+ * at ~12 misses a token, even at ~40, +4.5% at ~77, +5-7.5% at ~145. So on
+ * above PF_ON experts a token the cache would have missed (its misses and
+ * those the reads ahead spared it), off below PF_OFF, as it was between
+ * them; off, it costs nothing.
+ */
+#define PF_WINDOW 32
+#define PF_ON 60
+#define PF_OFF 40
+
+static void prefetch_decide(struct janas_llm_model *m,
+ const struct janas_expert_cache_stats *a,
+ const struct janas_expert_cache_stats *b)
+{
+ m->pf_would +=
+ (b->misses - a->misses) + (b->prefetch_used - a->prefetch_used);
+ if (++m->pf_tokens < PF_WINDOW)
+ return;
+ uint64_t per = m->pf_would / m->pf_tokens;
+ if (!m->pf_on && per > PF_ON)
+ m->pf_on = 1;
+ else if (m->pf_on && per < PF_OFF)
+ m->pf_on = 0;
+ m->pf_tokens = 0;
+ m->pf_would = 0;
+}
+
int janas_llm_model_forward(struct janas_llm_model *m, const int32_t *tokens,
uint32_t n, uint32_t pos0, float *logits,
int all_logits)
@@ -353,6 +383,8 @@ int janas_llm_model_forward(struct janas_llm_model *m, const int32_t *tokens,
from them, or a slow start decides the whole session */
if (r == 0 && dt > 0 && !janas_llm_model_settling(m))
janas_tuner_record(&m->tuner, cls, cand, dt / n);
+ if (r == 0 && n == 1 && m->pf_mode == 1)
+ prefetch_decide(m, &c0, &c1);
janas_m_arena_to_gpu(m);
return r;
}
@@ -402,6 +434,12 @@ static int forward(struct janas_llm_model *m, const int32_t *tokens, uint32_t n,
if (m->ple_dim && janas_m_ple_inputs(m, tokens, n) != 0)
return -1;
set_rope(m, n, pos0);
+ /* a token (or, with JANAS_GPU_BLOCK=1, a block) on the GPU, whole,
+ where it can (model_gpu.c) */
+ if (logits && janas_m_gpu_token(m, pos0, n, all_logits, logits) == 0) {
+ m->ring_hi = pos0 + n;
+ return 0;
+ }
for (uint32_t l = 0; l < m->n_layer; l++) {
const struct layer *ly = &m->layers[l];
janas_m_norm_quant(m, f32(m, ly->attn_norm), 0, n);
@@ -410,6 +448,14 @@ static int forward(struct janas_llm_model *m, const int32_t *tokens, uint32_t n,
janas_m_rec_layer(m, ly, n);
else
janas_m_attn_layer(m, ly, n, pos0);
+ /* the early predictor: layer l + 1's router on the state before
+ layer l's experts (its norm and router buffers are made again
+ just below) */
+ if (m->pred_fn && m->pred_early && l + 1 < m->n_layer &&
+ janas_m_route_predict(m, l + 1, n) != 0)
+ return -1;
+ if (m->pf_on && n == 1 && l + 1 < m->n_layer)
+ janas_m_prefetch(m, l);
janas_m_norm_quant(m, f32(m, ly->ffn_norm), 0, n);
trace_row(m, "post_norm", m->xn + (size_t)(n - 1) * dm, dm);
if (ly->post_ffn) {
@@ -448,6 +494,9 @@ static int forward(struct janas_llm_model *m, const int32_t *tokens, uint32_t n,
}
if (m->ple_dim)
janas_m_ple_layer(m, ly, l, n);
+ if (m->pred_fn && !m->pred_early && l + 1 < m->n_layer &&
+ janas_m_route_predict(m, l + 1, n) != 0)
+ return -1;
if (m->trace) {
/* JANAS_TRACE=1: the state after each layer, last token of the
block, to compare with another implementation */
diff --git a/src/llm/model.h b/src/llm/model.h
index 0b42726..6c82539 100644
--- a/src/llm/model.h
+++ b/src/llm/model.h
@@ -270,6 +270,34 @@ uint32_t janas_llm_model_experts(const struct janas_llm_model *m,
uint32_t *most);
int janas_llm_model_set_experts(struct janas_llm_model *m, uint32_t n);
+/*
+ * The router's choices as they are made: after each MoE layer of the main
+ * model routes a pass of n tokens, fn gets the layer and, token after
+ * token, the k experts each chose (exp[j * k + i]). For measures of which
+ * experts a text uses; NULL stops it. Runs on the calling thread, inside
+ * the pass: it must be quick and must not call the model.
+ */
+typedef void (*janas_llm_route_fn)(void *ctx, uint32_t layer, uint32_t n,
+ uint32_t k, const uint32_t *exp);
+void janas_llm_model_route_observer(struct janas_llm_model *m,
+ janas_llm_route_fn fn, void *ctx);
+/*
+ * For measures of prefetching: after each layer l of the main model, the
+ * router of layer l + 1 applied ahead to the state after l (normed as l + 1
+ * will norm it, without l + 1's attention in between), and fn gets layer
+ * l + 1 and, token after token, the k experts it ranks first (k <= 32). Costs
+ * a router and a norm per layer while set; NULL stops it. The pass itself
+ * is unchanged.
+ */
+void janas_llm_model_route_predictor(struct janas_llm_model *m,
+ janas_llm_route_fn fn, void *ctx,
+ uint32_t k);
+/* With early set, the prediction for layer l + 1 is made sooner: on the
+ state after layer l's attention, before its experts (more time to read
+ ahead, a state further from the one l + 1 routes). */
+void janas_llm_model_route_predictor_early(struct janas_llm_model *m,
+ int early);
+
/* The GPU in use, or NULL. */
struct janas_gpu *janas_llm_model_gpu(struct janas_llm_model *m);
/* Without one, why: the driver's or the build's reason, or that it was
diff --git a/src/llm/model_ffn.c b/src/llm/model_ffn.c
index 664c7cd..85bd5fe 100644
--- a/src/llm/model_ffn.c
+++ b/src/llm/model_ffn.c
@@ -263,6 +263,62 @@ static void run_experts(struct janas_llm_model *m,
m->compute, t2, n_runs));
}
+int janas_m_route_rank(struct janas_llm_model *m, uint32_t l, uint32_t n,
+ uint32_t k, uint32_t *ids)
+{
+ const struct layer *ly = &m->layers[l];
+ uint32_t ne = m->n_expert;
+ if (!ly->router16 || !ly->ffn_norm || k == 0 || k > 32 || k > ne)
+ return -1;
+ /* xn and router are free between layers: l + 1 norms into xn first */
+ janas_m_norm_quant(m, f32(m, ly->ffn_norm), 0, n);
+ struct router_job rj = {m, ly->router16, n};
+ janas_pool_run(m->compute, router_worker, &rj); /* 512 x 2048 a layer */
+ for (uint32_t j = 0; j < n; j++) {
+ float *r = m->router + (size_t)j * ne;
+ for (uint32_t i = 0; i < k; i++) {
+ uint32_t best = 0;
+ for (uint32_t e = 1; e < ne; e++)
+ if (r[e] > r[best])
+ best = e;
+ ids[(size_t)j * k + i] = best;
+ r[best] = -INFINITY;
+ }
+ }
+ return 0;
+}
+
+int janas_m_route_predict(struct janas_llm_model *m, uint32_t l, uint32_t n)
+{
+ uint32_t k = m->pred_k;
+ uint32_t *ids = malloc((size_t)n * (k ? k : 1) * sizeof(*ids));
+ if (!ids)
+ return -1;
+ if (janas_m_route_rank(m, l, n, k, ids) == 0)
+ m->pred_fn(m->pred_ctx, l, n, k, ids);
+ free(ids);
+ return 0;
+}
+
+/*
+ * Reads ahead the experts layer l + 1 is likely to want, of a single token:
+ * its router applied to the state before layer l's experts - the time of
+ * those experts and of layer l + 1's attention to read them in, some 0.8 ms
+ * or more on Qwen3-Next-80B, against 0.6 for a read. On that model its
+ * first 12 held 91% of the experts chosen and 85-88% of those the cache
+ * would miss (30 Sep 2026). Only the likeliest, and at most pf_max: past
+ * them the reads are mostly wasted and the disk fills up.
+ */
+void janas_m_prefetch(struct janas_llm_model *m, uint32_t l)
+{
+ double t0 = now();
+ uint32_t ids[32];
+ if (janas_m_route_rank(m, l + 1, 1, m->pf_rank, ids) == 0)
+ janas_expert_cache_prefetch(m->cache, l + 1, ids, m->pf_rank,
+ m->pf_max);
+ m->phase[JANAS_PH_ROUTER] += now() - t0;
+}
+
/* The router's choice for token j: softmax, top-k, normalized weights. */
static void route_tok(struct janas_llm_model *m, uint32_t j)
{
@@ -348,6 +404,8 @@ int janas_m_moe_block(struct janas_llm_model *m, const struct layer *ly,
if (ly->exp_scale)
for (uint32_t p = 0; p < n * k; p++)
m->pair_w[p] *= ly->exp_scale[m->pair_exp[p]];
+ if (m->route_fn && cache == m->cache)
+ m->route_fn(m->route_ctx, l, n, k, m->pair_exp);
}
/* counting sort of the pairs by expert */
uint32_t np = n * k;
diff --git a/src/llm/model_gpu.c b/src/llm/model_gpu.c
new file mode 100644
index 0000000..7bfce4a
--- /dev/null
+++ b/src/llm/model_gpu.c
@@ -0,0 +1,352 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * model_gpu.c - the model's side of the whole token on the GPU
+ * (gpu_token.h): which models it takes, their layers described for it, the
+ * KV cache shared with it, and the call from the forward pass.
+ *
+ * For now opt-in (JANAS_GPU_TOKEN=1) and for the dense attention models of
+ * qwen3's shape on a GPU that reads the host's memory in place, with the
+ * feed-forward weights (the experts' arena) on it already.
+ */
+#include "model.h"
+
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "expert_cache.h"
+#include "gpu.h"
+#include "gpu_token.h"
+#include "quant.h"
+
+#include "model_impl.h"
+
+/* Why a model is not for the token on the GPU, NULL if it is. */
+static const char *not_for_gpu(const struct janas_llm_model *m)
+{
+ if (!m->gpu || m->gpu_off || !janas_gpu_shares_host(m->gpu))
+ return "no GPU reading the host's memory";
+ if (m->a->rec || m->a->swa || m->a->attn_gate || m->a->sandwich ||
+ m->a->gelu || m->kv16 || m->softcap > 0.0f || m->ple_dim || m->mtp ||
+ m->asst)
+ return "an architecture the token's shaders do not take yet";
+ if (m->n_expert != 1 || !m->cache)
+ return "not a dense model";
+ if (m->arena_gpu != 1 || m->arena_stale)
+ return "the feed-forward weights are not on the GPU";
+ for (uint32_t l = 0; l < m->n_layer; l++) {
+ const struct layer *ly = &m->layers[l];
+ if (ly->rec || ly->swa || !ly->wk || !ly->wv || !ly->q_norm ||
+ !ly->k_norm || ly->post_attn || ly->post_ffn || ly->pre_norm2 ||
+ m->kv_ring[ly->slot] || ly->hd != m->head_dim ||
+ ly->n_kv != m->n_head_kv || ly->n_rot != m->n_rot)
+ return "a layer the token's shaders do not take yet";
+ }
+ return NULL;
+}
+
+static struct janas_matvec_task task_of(const struct janas_llm_model *m,
+ const struct janas_jns_tensor *t,
+ uint32_t rows, uint32_t cols)
+{
+ return (struct janas_matvec_task){
+ .type = (int)t->type, .w = data(m, t), .rows = rows, .cols = cols};
+}
+
+/* Whether a product goes to the aligned copy: Q6_K, or Q6_K in planes with
+ all three (the Q6_K block it came from). */
+static int repackable(const struct janas_matvec_task *t, int tiles)
+{
+ /* Q4_K: rows of 32 blocks and more (the tiles slow the short ones
+ down), or all of them with tiles 2 */
+ return t->type == JANAS_Q6_K ||
+ (t->type == JANAS_Q6_K_P && t->plane[0] && t->plane[1]) ||
+ (tiles >= 1 && t->type == JANAS_Q4_K &&
+ (tiles >= 2 || t->cols / JANAS_QK >= 32));
+}
+
+/* Block b of row r of a copy in tiles (gpu.h JANAS_TILE) or not, its
+ size, the rows it takes. */
+static size_t tile_at(size_t r, size_t b, size_t nb, int tiles)
+{
+ return tiles ? ((r / JANAS_TILE) * nb + b) * JANAS_TILE + r % JANAS_TILE
+ : r * nb + b;
+}
+
+static size_t copy_bs(const struct janas_matvec_task *t)
+{
+ return t->type == JANAS_Q4_K ? janas_qtype_block_size(JANAS_Q4_K)
+ : JANAS_Q6KA_BLOCK;
+}
+
+static size_t copy_rows(const struct janas_matvec_task *t, int tiles)
+{
+ return tiles ? (t->rows + JANAS_TILE - 1) / JANAS_TILE * JANAS_TILE
+ : t->rows;
+}
+
+/* Row r of a Q6_K or three-plane Q6_K_P task into dst, 224 bytes a block:
+ ql, qh, scales, d at byte 208, the rest zero. */
+static void repack_row(const struct janas_matvec_task *t, size_t r,
+ uint8_t *dst)
+{
+ size_t nb = t->cols / JANAS_QK;
+ for (size_t b = 0; b < nb; b++, dst += JANAS_Q6KA_BLOCK) {
+ struct janas_block_q6k q;
+ size_t k = r * nb + b;
+ if (t->type == JANAS_Q6_K)
+ q = ((const struct janas_block_q6k *)t->w)[k];
+ else
+ janas_q6kp_to_q6k(
+ (const struct janas_block_q6kp *)t->w + k,
+ (const uint8_t *)t->plane[0] + k * JANAS_Q6KP_PLANE,
+ (const uint8_t *)t->plane[1] + k * JANAS_Q6KP_PLANE, 1, &q);
+ memset(dst, 0, JANAS_Q6KA_BLOCK);
+ memcpy(dst, q.ql, sizeof(q.ql));
+ memcpy(dst + 128, q.qh, sizeof(q.qh));
+ memcpy(dst + 192, q.scales, sizeof(q.scales));
+ memcpy(dst + 208, &q.d, sizeof(q.d));
+ }
+}
+
+/*
+ * JANAS_GPU_REPACK=1: the Q6_K products (and the three-plane Q6_K_P ones)
+ * copied for the GPU into an aligned form it reads with whole 16-byte
+ * loads, in one region of its driver's memory; the tasks pointed at it.
+ * tiles (JANAS_GPU_REPACK - 1): 1, those and the Q4_K matrices of long
+ * rows in tiles; 2, every Q4_K too (gpu.h JANAS_TILE). The CPU keeps its
+ * own; the copy costs that much memory more. 0, or -1 with the tasks
+ * unchanged.
+ */
+static int repack(struct janas_llm_model *m, int tiles)
+{
+ struct janas_matvec_task *t[8 * 1024];
+ size_t n = 0, bytes = 0;
+ for (uint32_t l = 0; l < m->n_layer; l++) {
+ struct janas_gpu_tok_layer *g = &m->gtok_layers[l];
+ struct janas_matvec_task *all[7] = {&g->wq, &g->wk, &g->wv, &g->wo,
+ &g->gate, &g->up, &g->down};
+ for (int i = 0; i < 7; i++)
+ if (repackable(all[i], tiles) && n < sizeof(t) / sizeof(*t))
+ t[n++] = all[i];
+ }
+ if (repackable(&m->gtok_md.output, tiles) && n < sizeof(t) / sizeof(*t))
+ t[n++] = &m->gtok_md.output;
+ for (size_t i = 0; i < n; i++)
+ bytes +=
+ copy_rows(t[i], tiles) * (t[i]->cols / JANAS_QK) * copy_bs(t[i]);
+ if (n == 0)
+ return 0;
+ if (!m->gtok_repack || m->gtok_repack_bytes < bytes) {
+ m->gtok_repack = janas_gpu_alloc(m->gpu, bytes);
+ m->gtok_repack_bytes = m->gtok_repack ? bytes : 0;
+ }
+ if (!m->gtok_repack)
+ return -1;
+ uint8_t *at = m->gtok_repack;
+ memset(at, 0, bytes); /* the tiles' padding rows */
+ for (size_t i = 0; i < n; i++) {
+ size_t nb = t[i]->cols / JANAS_QK, bs = copy_bs(t[i]);
+ uint8_t blk[JANAS_Q6KA_BLOCK];
+ for (size_t r = 0; r < t[i]->rows; r++)
+ for (size_t b = 0; b < nb; b++) {
+ uint8_t *dst = at + tile_at(r, b, nb, tiles) * bs;
+ if (t[i]->type == JANAS_Q4_K) {
+ memcpy(dst, (const uint8_t *)t[i]->w + (r * nb + b) * bs,
+ bs);
+ continue;
+ }
+ /* repack_row takes a whole row: one block through blk */
+ struct janas_matvec_task one = *t[i];
+ one.cols = JANAS_QK;
+ one.w =
+ t[i]->type == JANAS_Q6_K
+ ? (const void *)((const struct janas_block_q6k *)t[i]
+ ->w +
+ r * nb + b)
+ : (const void *)((const struct janas_block_q6kp *)t[i]
+ ->w +
+ r * nb + b);
+ if (t[i]->type == JANAS_Q6_K_P) {
+ one.plane[0] = (const uint8_t *)t[i]->plane[0] +
+ (r * nb + b) * JANAS_Q6KP_PLANE;
+ one.plane[1] = (const uint8_t *)t[i]->plane[1] +
+ (r * nb + b) * JANAS_Q6KP_PLANE;
+ }
+ repack_row(&one, 0, blk);
+ memcpy(dst, blk, bs);
+ }
+ size_t used = copy_rows(t[i], tiles) * nb * bs;
+ t[i]->type = t[i]->type == JANAS_Q4_K ? JANAS_Q4_K_T
+ : tiles ? JANAS_Q6_K_AT
+ : JANAS_Q6_K_A;
+ t[i]->w = at;
+ t[i]->plane[0] = t[i]->plane[1] = NULL;
+ at += used;
+ }
+ janas_gpu_flush(m->gpu, m->gtok_repack, bytes);
+ return 0;
+}
+
+/* The layers described for the GPU, the KV cache imported: 0, or -1. */
+static int build(struct janas_llm_model *m, char *err, size_t len)
+{
+ uint32_t dm = m->d_model, hd = m->head_dim, qd = m->n_head * hd,
+ kvd = m->n_head_kv * hd;
+ if (!m->gtok_kv) {
+ if (janas_gpu_import(m->gpu, m->kcache, m->kv_bytes) != 0 ||
+ janas_gpu_import(m->gpu, m->vcache, m->kv_bytes) != 0 ||
+ janas_gpu_import(m->gpu, m->kscale, m->ks_bytes) != 0 ||
+ janas_gpu_import(m->gpu, m->vscale, m->ks_bytes) != 0) {
+ snprintf(err, len, "the KV cache cannot be imported");
+ return -1;
+ }
+ m->gtok_kv = 1;
+ }
+ free(m->gtok_layers);
+ m->gtok_layers = calloc(m->n_layer, sizeof(*m->gtok_layers));
+ if (!m->gtok_layers) {
+ snprintf(err, len, "out of memory");
+ return -1;
+ }
+ uint32_t ff = 0;
+ for (uint32_t l = 0; l < m->n_layer; l++) {
+ const struct layer *ly = &m->layers[l];
+ const struct janas_jns_layer *jl = &m->j.layers[l];
+ struct janas_gpu_tok_layer *g = &m->gtok_layers[l];
+ uint32_t e0 = 0;
+ const uint8_t *slot;
+ if (janas_expert_cache_fetch(m->cache, l, &e0, 1, &slot) != 0) {
+ snprintf(err, len, "the feed-forward of layer %u unreadable", l);
+ return -1;
+ }
+ g->attn_norm = f32(m, ly->attn_norm);
+ g->q_norm = f32(m, ly->q_norm);
+ g->k_norm = f32(m, ly->k_norm);
+ g->ffn_norm = f32(m, ly->ffn_norm);
+ g->wq = task_of(m, ly->wq, qd, dm);
+ g->wk = task_of(m, ly->wk, kvd, dm);
+ g->wv = task_of(m, ly->wv, kvd, dm);
+ g->wo = task_of(m, ly->wo, dm, qd);
+ for (int p = 0; p < 3; p++) {
+ const struct janas_jns_matrix *mx = &jl->m[p];
+ struct janas_matvec_task t = {.type = (int)mx->type,
+ .w = slot + mx->offset,
+ .rows = mx->rows,
+ .cols = mx->cols};
+ if (p == 2) /* the down matrix's planes the cache holds */
+ for (int q = 0; q < m->exp_level - 1; q++)
+ if (jl->plane[q].type)
+ t.plane[q] = slot + jl->plane[q].offset;
+ *(p == 0 ? &g->gate : p == 1 ? &g->up : &g->down) = t;
+ }
+ if (l == 0)
+ ff = g->gate.rows;
+ if (g->gate.rows != ff || g->up.rows != ff || g->down.cols != ff) {
+ snprintf(err, len, "feed-forwards of different widths");
+ return -1;
+ }
+ g->kc = m->kcache + m->kv_off[ly->slot];
+ g->vc = m->vcache + m->kv_off[ly->slot];
+ g->ks = m->kscale + m->ks_off[ly->slot];
+ g->vs = m->vscale + m->ks_off[ly->slot];
+ }
+ m->gtok_md = (struct janas_gpu_tok_model){
+ .n_layer = m->n_layer,
+ .dm = dm,
+ .n_head = m->n_head,
+ .n_kv = m->n_head_kv,
+ .hd = hd,
+ .n_rot = m->n_rot,
+ .ff = ff,
+ .n_vocab = m->n_vocab,
+ .cap = m->kv_cap[m->layers[0].slot],
+ .eps = m->eps,
+ .attn_scale = 1.0f / sqrtf((float)hd),
+ .layers = m->gtok_layers,
+ .out_norm = f32(m, m->out_norm),
+ .output = task_of(m, m->output, m->n_vocab, dm)};
+ free(m->gblk_layers);
+ m->gblk_layers = NULL;
+ if (getenv("JANAS_GPU_REPACK") && atoi(getenv("JANAS_GPU_REPACK")) > 0) {
+ /* the blocks keep the weights as they are: the copy's shaders take
+ a single vector */
+ m->gblk_layers = malloc(m->n_layer * sizeof(*m->gblk_layers));
+ if (!m->gblk_layers) {
+ snprintf(err, len, "out of memory");
+ return -1;
+ }
+ memcpy(m->gblk_layers, m->gtok_layers,
+ m->n_layer * sizeof(*m->gblk_layers));
+ m->gtok_md.blayers = m->gblk_layers;
+ m->gtok_md.boutput = m->gtok_md.output;
+ if (repack(m, atoi(getenv("JANAS_GPU_REPACK")) - 1) != 0)
+ fprintf(stderr, "janas: no aligned copy for the GPU: out of its "
+ "memory\n");
+ }
+ janas_gpu_tok_destroy(m->gpu, m->gtok);
+ m->gtok = janas_gpu_tok_create(m->gpu, &m->gtok_md, err, len);
+ m->gtok_loads = janas_expert_cache_loads(m->cache);
+ return m->gtok ? 0 : -1;
+}
+
+int janas_m_gpu_token(struct janas_llm_model *m, uint32_t pos, uint32_t n,
+ int all, float *logits)
+{
+ if (m->gtok_state < 0)
+ return -1;
+ /* blocks of more than one token: opt-in for now (JANAS_GPU_BLOCK=1) */
+ static int blocks = -1;
+ if (blocks < 0)
+ blocks =
+ getenv("JANAS_GPU_BLOCK") && atoi(getenv("JANAS_GPU_BLOCK")) > 0;
+ if (n > 1 && !blocks)
+ return -1;
+ if (m->gtok_state == 0) {
+ const char *e = getenv("JANAS_GPU_TOKEN");
+ if (!e || atoi(e) <= 0) {
+ m->gtok_state = -1;
+ return -1;
+ }
+ }
+ const char *why = not_for_gpu(m);
+ if (why) {
+ /* the arena may reach the GPU later: wait for it, say nothing */
+ if (m->gtok_state == 0 && m->arena_gpu == 0 && m->gpu && !m->gpu_off)
+ return -1;
+ if (m->gtok_state == 0)
+ fprintf(stderr, "janas: no whole token on the GPU: %s\n", why);
+ m->gtok_state = -1;
+ return -1;
+ }
+ if (m->gtok_state == 0 ||
+ janas_expert_cache_loads(m->cache) != m->gtok_loads) {
+ char err[160];
+ if (build(m, err, sizeof(err)) != 0) {
+ fprintf(stderr, "janas: no whole token on the GPU: %s\n", err);
+ m->gtok_state = -1;
+ return -1;
+ }
+ m->gtok_state = 1;
+ }
+ /* a longer block (a prompt, only its last logits wanted) in pieces:
+ each piece's keys and values in the cache before the next */
+ uint32_t nb = janas_gpu_tok_max_block(m->gtok), half = m->n_rot / 2;
+ if (n > nb && all)
+ return -1;
+ for (uint32_t j = 0; j < n; j += nb) {
+ uint32_t k = n - j < nb ? n - j : nb;
+ if (janas_gpu_tok_run(m->gpu, m->gtok, &m->gtok_md,
+ m->x + (size_t)j * m->d_model,
+ m->rope_cos + (size_t)j * half,
+ m->rope_sin + (size_t)j * half, pos + j, k,
+ j + k < n ? 2
+ : all ? 1
+ : 0,
+ logits) != 0)
+ return -1;
+ }
+ return 0;
+}
diff --git a/src/llm/model_impl.h b/src/llm/model_impl.h
index 789e456..2772b11 100644
--- a/src/llm/model_impl.h
+++ b/src/llm/model_impl.h
@@ -18,6 +18,7 @@
#include "attention.h"
#include "common/pool.h"
#include "gpu.h"
+#include "gpu_token.h"
#include "jns.h"
#include "quant.h"
#include "tuner.h"
@@ -156,6 +157,21 @@ struct janas_llm_model {
* Half precision: attention at long context is bound by reading it.
*/
int8_t *kcache, *vcache;
+ size_t kv_bytes, ks_bytes; /* the caches' and the scales' allocations */
+ /* the whole token on the GPU (gpu_token.h, JANAS_GPU_TOKEN=1): 0 not
+ tried yet, 1 ready, -1 not for this model; loads: the experts' loads
+ it was built with (a change and it is built again) */
+ struct janas_gpu_tok *gtok;
+ struct janas_gpu_tok_model gtok_md;
+ struct janas_gpu_tok_layer *gtok_layers;
+ struct janas_gpu_tok_layer *gblk_layers; /* the weights as they are,
+ with a GPU copy */
+ int gtok_state, gtok_kv;
+ uint64_t gtok_loads;
+ /* the aligned copy of its Q6_K weights for the GPU (JANAS_GPU_REPACK),
+ in the GPU driver's memory, kept for a rebuild */
+ uint8_t *gtok_repack;
+ size_t gtok_repack_bytes;
float *kscale, *vscale; /* one per position and KV head */
/*
* Recurrent state in two buffers, a base and a tip, so that rolling back
@@ -249,7 +265,22 @@ struct janas_llm_model {
int exp_auto; /* the level was chosen from the memory available */
int k_auto; /* and so was the number of experts per token */
int warm_use; /* preload the most used experts, and count them */
- uint32_t *use_count; /* experts used this session, n_layer * n_expert */
+ uint32_t *use_count; /* experts used this session, n_layer * n_expert */
+ janas_llm_route_fn route_fn; /* janas_llm_model_route_observer */
+ void *route_ctx;
+ janas_llm_route_fn pred_fn; /* janas_llm_model_route_predictor */
+ void *pred_ctx;
+ uint32_t pred_k;
+ int pred_early; /* ahead of layer l's experts, not after layer l */
+ /* reads ahead (janas_m_prefetch): the next layer's router applied
+ before this layer's experts, of its first r experts at most b read
+ ahead. pf_mode 0 never, 1 where it pays (pf_on, decided every
+ PF_WINDOW tokens from the experts the cache would have missed), 2
+ always (JANAS_PREFETCH=0, unset, =r,b) */
+ uint32_t pf_rank, pf_max;
+ int pf_mode, pf_on;
+ uint32_t pf_tokens;
+ uint64_t pf_would;
uint64_t warm_experts; /* experts preloaded at open from the profile */
double warm_seconds;
@@ -333,6 +364,8 @@ void janas_m_init_tuner(struct janas_llm_model *m);
int janas_m_gpu_import(struct janas_llm_model *m, const uint8_t *p,
uint64_t bytes, uint64_t unit);
void janas_m_arena_to_gpu(struct janas_llm_model *m);
+int janas_m_gpu_token(struct janas_llm_model *m, uint32_t pos, uint32_t n,
+ int all, float *logits);
void janas_m_apply_candidate(struct janas_llm_model *m, int cand);
uint32_t *janas_m_profile_read(const struct janas_llm_model *m, size_t *used);
void janas_m_profile_write(const struct janas_llm_model *m);
@@ -366,6 +399,16 @@ int janas_m_exp_tracing(void);
void janas_m_exp_report(void);
/* which experts a moe_block call runs */
enum { MOE_ALL, MOE_SHARED, MOE_ROUTED };
+/* The router of layer l applied ahead to the state x (for the predictor
+ probe, janas_llm_model_route_predictor): 0 or -1. */
+int janas_m_route_predict(struct janas_llm_model *m, uint32_t l, uint32_t n);
+/* The router of layer l applied to the state x of n tokens: its first k
+ experts for each token into ids (n x k), best first. 0, or -1 when the
+ layer has no router to apply ahead. Uses xn, xq and router. */
+int janas_m_route_rank(struct janas_llm_model *m, uint32_t l, uint32_t n,
+ uint32_t k, uint32_t *ids);
+/* Reads ahead for layer l + 1 of a single token (JANAS_PREFETCH). */
+void janas_m_prefetch(struct janas_llm_model *m, uint32_t l);
int janas_m_moe_block(struct janas_llm_model *m, const struct layer *ly,
struct janas_expert_cache *cache,
const struct janas_jns_layer *jl, uint32_t l, uint32_t n,
diff --git a/src/llm/model_load.c b/src/llm/model_load.c
index 8c16264..0bfd15d 100644
--- a/src/llm/model_load.c
+++ b/src/llm/model_load.c
@@ -597,7 +597,12 @@ struct janas_llm_model *janas_llm_model_load(const char *path,
char gerr[256] = "";
m->gpu = janas_gpu_create(gerr, sizeof(gerr));
snprintf(m->gpu_why, sizeof(m->gpu_why), "%.150s", m->gpu ? "" : gerr);
- if (m->gpu && getenv("JANAS_GPU_ALLOC") &&
+ /* the resident region in the GPU driver's memory (JANAS_GPU_ALLOC,
+ or with the whole token on an integrated GPU): the GPU reads it
+ faster than imported pages, some 20% on the development laptop's */
+ if (m->gpu &&
+ (getenv("JANAS_GPU_ALLOC") ||
+ (getenv("JANAS_GPU_TOKEN") && janas_gpu_shares_host(m->gpu))) &&
(m->resident = janas_gpu_alloc(m->gpu, m->j.h.resident_bytes)))
m->resident_gpu = 1;
}
@@ -767,10 +772,16 @@ struct janas_llm_model *janas_llm_model_load(const char *path,
}
m->kv_off[n_slots] = kv_len;
m->ks_off[n_slots] = ks_len;
- m->kcache = malloc(kv_len ? kv_len : 1);
- m->vcache = malloc(kv_len ? kv_len : 1);
- m->kscale = malloc((ks_len ? ks_len : 1) * sizeof(float));
- m->vscale = malloc((ks_len ? ks_len : 1) * sizeof(float));
+ /* whole pages: an integrated GPU imports them for the token it runs
+ (gpu_token.h) */
+ size_t kvb = (kv_len + 4095) / 4096 * 4096,
+ ksb = (ks_len * sizeof(float) + 4095) / 4096 * 4096;
+ m->kcache = aligned_alloc(4096, kvb ? kvb : 4096);
+ m->vcache = aligned_alloc(4096, kvb ? kvb : 4096);
+ m->kscale = aligned_alloc(4096, ksb ? ksb : 4096);
+ m->vscale = aligned_alloc(4096, ksb ? ksb : 4096);
+ m->kv_bytes = kvb;
+ m->ks_bytes = ksb;
/* a pair's rows: the experts', or a wider shared feed-forward's */
m->ff_buf = m->d_ff;
for (uint32_t l = 0; l < m->n_layer; l++)
@@ -989,6 +1000,25 @@ struct janas_llm_model *janas_llm_model_load(const char *path,
m->io, err, err_len);
if (!m->cache)
goto fail;
+ /* reads ahead (model_ffn.c janas_m_prefetch): where they pay, of the
+ next layer's first 10 experts at most 2 (measured on 30 Sep 2026);
+ JANAS_PREFETCH=0 never, =r,b always with those */
+ if (janas_expert_cache_can_prefetch(m->cache)) {
+ const char *pf = getenv("JANAS_PREFETCH");
+ unsigned pr = 0, pb = 0;
+ m->pf_rank = 10;
+ m->pf_max = 2;
+ m->pf_mode = 1;
+ if (pf && atoi(pf) == 0) {
+ m->pf_mode = 0;
+ } else if (pf && sscanf(pf, "%u,%u", &pr, &pb) == 2 && pr >= 1 &&
+ pr <= 32 && pb >= 1) {
+ m->pf_rank = pr;
+ m->pf_max = pb;
+ m->pf_mode = 2;
+ m->pf_on = 1;
+ }
+ }
/* fill the cache with the experts this machine used most, before the
first reply has to find them one token at a time. A caller that does
not want this (a measurement) neither reads the profile nor adds to
@@ -1067,6 +1097,9 @@ void janas_llm_model_free(struct janas_llm_model *m)
free(m->use_count);
m->use_count = NULL;
}
+ janas_gpu_tok_destroy(m->gpu, m->gtok);
+ free(m->gtok_layers);
+ free(m->gblk_layers);
janas_gpu_destroy(m->gpu); /* before the memory it imported; frees
the resident region it allocated */
janas_expert_cache_destroy(m->cache);
@@ -1174,6 +1207,27 @@ int janas_llm_model_set_experts(struct janas_llm_model *m, uint32_t n)
return 1;
}
+void janas_llm_model_route_observer(struct janas_llm_model *m,
+ janas_llm_route_fn fn, void *ctx)
+{
+ m->route_fn = fn;
+ m->route_ctx = ctx;
+}
+
+void janas_llm_model_route_predictor(struct janas_llm_model *m,
+ janas_llm_route_fn fn, void *ctx,
+ uint32_t k)
+{
+ m->pred_fn = fn;
+ m->pred_ctx = ctx;
+ m->pred_k = k;
+}
+
+void janas_llm_model_route_predictor_early(struct janas_llm_model *m, int early)
+{
+ m->pred_early = early;
+}
+
struct janas_gpu *janas_llm_model_gpu(struct janas_llm_model *m)
{
return m->gpu;
@@ -1288,9 +1342,19 @@ void janas_m_arena_to_gpu(struct janas_llm_model *m)
if (!a)
return;
uint64_t slot = janas_expert_cache_slot_bytes(m->cache);
+ uint8_t *own = NULL;
if (getenv("JANAS_GPU_EXPERTS") && atoi(getenv("JANAS_GPU_EXPERTS")) == 0)
m->arena_gpu = -1;
- else if (janas_m_gpu_import(m, a, bytes, slot) == 0) {
+ else if ((getenv("JANAS_GPU_ALLOC") || getenv("JANAS_GPU_TOKEN")) &&
+ janas_gpu_shares_host(m->gpu) &&
+ (own = janas_gpu_alloc(m->gpu, bytes)) &&
+ janas_expert_cache_rebase(m->cache, own) == 0) {
+ /* moved into the GPU driver's memory, which it reads faster than
+ imported pages; the CPU reads the same memory */
+ janas_gpu_flush(m->gpu, own, bytes);
+ m->arena_gpu = 1;
+ m->arena_loads = loads;
+ } else if (janas_m_gpu_import(m, a, bytes, slot) == 0) {
m->arena_gpu = 1;
m->arena_loads = loads;
} else {
diff --git a/src/llm/sample.c b/src/llm/sample.c
index 12e507d..2d02f38 100644
--- a/src/llm/sample.c
+++ b/src/llm/sample.c
@@ -113,6 +113,16 @@ void janas_sampler_mark(struct janas_sampler *s)
s->n_seen = 0;
}
+#define SPLITMIX_STEP 0x9e3779b97f4a7c15ull /* splitmix64 below */
+
+/* A draw takes one number, and only above temperature 0 (draw() below):
+ the sequence is a counter, so going back is a subtraction. */
+void janas_sampler_rewind(struct janas_sampler *s, uint32_t n)
+{
+ if (s->p.temperature > 0)
+ s->rng -= (uint64_t)n * SPLITMIX_STEP;
+}
+
uint32_t janas_sampler_forced(const struct janas_sampler *s)
{
return s->forced;
@@ -120,7 +130,7 @@ uint32_t janas_sampler_forced(const struct janas_sampler *s)
static uint64_t splitmix64(uint64_t *x)
{
- uint64_t z = (*x += 0x9e3779b97f4a7c15ull);
+ uint64_t z = (*x += SPLITMIX_STEP);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
return z ^ (z >> 31);
diff --git a/src/llm/sample.h b/src/llm/sample.h
index 0dc704c..ca5aab8 100644
--- a/src/llm/sample.h
+++ b/src/llm/sample.h
@@ -65,6 +65,10 @@ int janas_sampler_bias(struct janas_sampler *s, const int32_t *ids,
/* The filter (NULL: none); the sampler keeps the pointer's contents. */
void janas_sampler_filter(struct janas_sampler *s,
const struct janas_sample_filter *f);
+/* The random sequence n draws back, as if the last n picks had not been
+ made: a speculative pass draws for drafts that a reply cut short never
+ returns. The penalties' counts are not undone (a mark resets them). */
+void janas_sampler_rewind(struct janas_sampler *s, uint32_t n);
/* The penalties count the tokens picked from here on. */
void janas_sampler_mark(struct janas_sampler *s);
diff --git a/src/llm/shaders/attn_decode.comp b/src/llm/shaders/attn_decode.comp
new file mode 100644
index 0000000..4a8cc9b
--- /dev/null
+++ b/src/llm/shaders/attn_decode.comp
@@ -0,0 +1,205 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Attention of one token, first step: one workgroup per KV head and run of
+// C positions of the layer's eight-bit KV cache (n_kv x cap x hd bytes, a
+// scale per position and KV head), for the G = n_head / n_kv query heads
+// that share the KV head - its keys read once for all of them.
+// For each query head h and run c: scores q.k x the key's scale x `scale`
+// (q at eight bits too, a scale per head, as llama.cpp takes it with an
+// eight-bit cache: the dot products are integer, four bytes at a time; q
+// left so by qk_rope.comp, hd / 4 words then the scale in a head's floats),
+// their maximum m, the sum l of e^(s - m), and the values weighted by e^(s
+// - m) (and the value's scale), written to part at (h nch + c)(hd + 2):
+// the hd sums, then m and l. attn_merge.comp joins the runs. Workgroup x =
+// kh nch + c; the runs past the token's position leave at once, so that
+// the dispatch recorded once serves every position. The GPU's own order of
+// the sums: not the CPU's bits (attention.c), the same result to rounding.
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_clustered : require
+#extension GL_EXT_integer_dot_product : require
+
+layout(local_size_x = 256) in;
+
+layout(constant_id = 2) const uint G = 4; /* query heads a KV head */
+const uint C = 128u; /* positions a run: gpu_token.c ATT_RUN */
+const uint MAXQ = 2048u; /* G x hd */
+const uint MAXS = 1024u; /* G x C */
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer R { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer B4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 8) readonly buffer B2 { uvec2 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer W { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer RP { uint v[]; };
+
+layout(push_constant) uniform P {
+ uvec2 q, kc, vc, ks, vs, part;
+ uint n_head, n_kv, hd, cap, nch;
+ float scale;
+ uint qs, ps; /* floats from a token's qkv, and its runs, to the next's */
+ uvec2 pos; /* the token's position, read at run time: npos = pos + 1 */
+} p;
+
+shared float sq[MAXQ]; /* the G query heads */
+shared float sc[MAXS]; /* scores, then weights: head g at g C */
+shared float r8[MAXS / 8u]; /* the maxima of eight scores */
+shared float r8s[MAXS / 8u]; /* and the sums of eight weights */
+shared uint sqw[MAXQ / 4u]; /* the query heads at eight bits, four a word */
+shared float sqs[16]; /* and their scales */
+
+int byte_of(uint w, uint i) { return bitfieldExtract(int(w), int(8u * i), 8); }
+
+uint comp(uvec4 v, uint i) { return i == 0u ? v.x : i == 1u ? v.y : i == 2u ? v.z : v.w; }
+
+void main()
+{
+ uint t = gl_LocalInvocationID.x, hd = p.hd;
+ uint kh = gl_WorkGroupID.x / p.nch, c = gl_WorkGroupID.x % p.nch;
+ /* token j of a block (workgroup y): positions 0 .. pos + j */
+ uint j0 = gl_WorkGroupID.y;
+ uint npos = RP(p.pos).v[0] + j0 + 1u, p0 = c * C;
+ if (p0 >= npos)
+ return; /* the whole workgroup: past the token */
+ uint n = min(C, npos - p0);
+ R Q = R(p.q), KS = R(p.ks), VS = R(p.vs);
+ RP QW = RP(p.q);
+ B4 KC = B4(p.kc), VC = B4(p.vc); /* 16 bytes a load: hd % 16 == 0 */
+ /* the G query heads at eight bits and their scales, as qk_rope.comp
+ left them */
+ uint qo = j0 * p.qs + kh * G * hd, nw = hd / 4u;
+ for (uint k = t; k < G * nw; k += 256u)
+ sqw[k] = QW.v[qo + (k / nw) * hd + k % nw];
+ if (t < G)
+ sqs[t] = Q.v[qo + t * hd + nw];
+ barrier();
+ uint base = kh * p.cap + p0; /* the run's first position */
+ /* scores: four threads a position (256 threads: C / 64 rounds), each
+ a quarter of the key for all G heads at once - the key read once -
+ the quarters added across the cluster */
+ for (uint r0 = 0; r0 < C; r0 += 64u) {
+ uint j = r0 + t / 4u, qq = t % 4u, jj = min(j, n - 1u);
+ uint w0 = (base + jj) * hd / 16u;
+ int dg[G];
+ for (uint g = 0; g < G; g++)
+ dg[g] = 0;
+ for (uint w = qq; w < hd / 16u; w += 4u) {
+ uvec4 k4 = KC.v[w0 + w];
+ for (uint g = 0; g < G; g++) {
+ uint o = g * hd / 4u + 4u * w;
+ dg[g] += dotPacked4x8EXT(int(sqw[o]), int(k4.x)) +
+ dotPacked4x8EXT(int(sqw[o + 1u]), int(k4.y)) +
+ dotPacked4x8EXT(int(sqw[o + 2u]), int(k4.z)) +
+ dotPacked4x8EXT(int(sqw[o + 3u]), int(k4.w));
+ }
+ }
+ float ksc = KS.v[base + jj] * p.scale;
+ for (uint g = 0; g < G; g++) {
+ int d = subgroupClusteredAdd(dg[g], 4u);
+ if (qq == 0u && j < n)
+ sc[g * C + j] = float(d) * sqs[g] * ksc;
+ }
+ }
+ barrier();
+ /* each head's maximum and sum: a thread a (head, position), the
+ eights by cluster, then a head's eight eights in order */
+ const uint IT = (G * C + 255u) / 256u;
+ for (uint it = 0; it < IT; it++) {
+ uint k = it * 256u + t, g = k / C, j = k % C;
+ float v = g < G && j < n ? sc[k] : -1.0 / 0.0;
+ float cm = subgroupClusteredMax(v, 8u);
+ if (t % 8u == 0u && g < G)
+ r8[k / 8u] = cm;
+ }
+ barrier();
+ /* each thread its head's maximum from the eights, in the order the
+ table of maxima took (no barrier for it); the eights of the sums
+ in a table of their own, the maxima still being read */
+ for (uint it = 0; it < IT; it++) {
+ uint k = it * 256u + t, g = min(k / C, G - 1u), j = k % C;
+ bool in_g = k / C < G, on = in_g && j < n;
+ float m = r8[g * (C / 8u)];
+ for (uint q = 1u; q < C / 8u; q++)
+ m = max(m, r8[g * (C / 8u) + q]);
+ float e = on ? exp(sc[k] - m) : 0.0;
+ if (in_g)
+ sc[k] = on ? e * VS.v[base + j] : 0.0;
+ float ce = subgroupClusteredAdd(e, 8u);
+ if (t % 8u == 0u && in_g)
+ r8s[k / 8u] = ce;
+ }
+ barrier();
+ /* the weighted values, the slices' sums through the shared memory
+ the query heads are done with, added in order. Up to four heads a
+ KV head and runs of more than 64 positions: a thread 8 dimensions
+ of every head (each value read once, 8 bytes a load) and a slice of
+ the run's positions, four slices in the four lanes of a cluster,
+ added there first. Else (shorter runs, where that is slower, or more
+ heads): a thread 16 dimensions of one head. SH: the slice sets left
+ for the shared memory. */
+ uint SH;
+ if (G <= 4u && n > 64u) {
+ uint U = hd / 8u;
+ SH = min(256u / (4u * U), MAXQ / (G * hd));
+ if (t < 4u * U * SH) {
+ uint slo = t % 4u, u = (t / 4u) % U, shi = t / (4u * U), d0 = u * 8u;
+ B2 VC2 = B2(p.vc);
+ float a[G * 8u];
+ for (uint k = 0; k < G * 8u; k++)
+ a[k] = 0.0;
+ for (uint j = slo + 4u * shi; j < n; j += 4u * SH) {
+ uvec2 v2 = VC2.v[((base + j) * hd + d0) / 8u];
+ for (uint k = 0; k < 8u; k++) {
+ float vb = float(byte_of(k < 4u ? v2.x : v2.y, k % 4u));
+ for (uint g = 0; g < G; g++)
+ a[g * 8u + k] += sc[g * C + j] * vb;
+ }
+ }
+ for (uint g = 0; g < G; g++)
+ for (uint k = 0; k < 8u; k++) {
+ float x = subgroupClusteredAdd(a[g * 8u + k], 4u);
+ if (slo == 0u)
+ sq[shi * G * hd + g * hd + d0 + k] = x;
+ }
+ }
+ } else {
+ uint U = G * hd / 16u;
+ SH = min(256u / U, MAXQ / (G * hd));
+ if (t < U * SH) {
+ uint u = t % U, sl_ = t / U, g = u / (hd / 16u), d0 = (u % (hd / 16u)) * 16u;
+ float a[16];
+ for (uint k = 0; k < 16u; k++)
+ a[k] = 0.0;
+ for (uint j = sl_; j < n; j += SH) {
+ uvec4 v4 = VC.v[((base + j) * hd + d0) / 16u];
+ float wj = sc[g * C + j];
+ for (uint k = 0; k < 16u; k++)
+ a[k] += wj * float(byte_of(comp(v4, k / 4u), k % 4u));
+ }
+ for (uint k = 0; k < 16u; k++)
+ sq[sl_ * G * hd + g * hd + d0 + k] = a[k];
+ }
+ }
+ barrier();
+ W O = W(p.part);
+ for (uint k = t; k < G * hd; k += 256u) {
+ uint g = k / hd, i = k % hd;
+ float a = sq[k];
+ for (uint q = 1u; q < SH; q++)
+ a += sq[q * G * hd + k];
+ uint h = kh * G + g;
+ O.v[j0 * p.ps + (h * p.nch + c) * (hd + 2u) + i] = a;
+ }
+ if (t < G) {
+ /* the head's maximum and sum, from the eights in their order */
+ float m = r8[t * (C / 8u)], l = 0.0;
+ for (uint q = 1u; q < C / 8u; q++)
+ m = max(m, r8[t * (C / 8u) + q]);
+ for (uint q = 0; q < C / 8u; q++)
+ l += r8s[t * (C / 8u) + q];
+ uint h = kh * G + t;
+ O.v[j0 * p.ps + (h * p.nch + c) * (hd + 2u) + hd] = m;
+ O.v[j0 * p.ps + (h * p.nch + c) * (hd + 2u) + hd + 1u] = l;
+ }
+}
diff --git a/src/llm/shaders/attn_merge.comp b/src/llm/shaders/attn_merge.comp
new file mode 100644
index 0000000..cb3d096
--- /dev/null
+++ b/src/llm/shaders/attn_merge.comp
@@ -0,0 +1,116 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Attention of one token, second step, with the quantization of its output
+// for the products that follow: one workgroup per block of 256 of the
+// n_head x hd outputs, a value a thread (element e: head e / hd, dimension
+// e % hd). The runs of attn_decode.comp joined in their order - the
+// largest maximum M, each run's sums and l scaled by e^(m - M), the sums
+// divided by the total - then quantized to Q8_K as norm_quant.comp does
+// (q256, and q32 if set): no dispatch of its own between the two.
+#extension GL_EXT_buffer_reference : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_clustered : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 256) in;
+
+const uint C = 128u; /* positions a run, as attn_decode.comp */
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer R { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer U { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer RP { uint v[]; };
+
+layout(push_constant) uniform P {
+ uvec2 part, q256, q32;
+ uint hd, nch, ps; /* ps: floats from a token's runs to the next's */
+ uint pad_;
+ uvec2 pos;
+} p;
+
+shared float m8[32]; /* the block's maxima, eight values each */
+shared int s8a[32], s8b[32]; /* and its quants' sums, eight each */
+
+bool set(uvec2 a) { return a.x != 0u || a.y != 0u; }
+
+float recip_det(float d)
+{
+ precise float y = uintBitsToFloat(0x7EF311C3u - floatBitsToUint(d));
+ for (int i = 0; i < 3; i++)
+ y = fma(y, fma(-d, y, 1.0), y);
+ return y;
+}
+
+int q8(float v, float id)
+{
+ precise float q = roundEven(v * id);
+ return int(clamp(q, -127.0, 127.0));
+}
+
+void main()
+{
+ uint t = gl_LocalInvocationID.x, b = gl_WorkGroupID.x, hd = p.hd;
+ U Q = U(p.q256), Q32 = U(p.q32);
+ /* token j of a block (workgroup y): positions 0 .. pos + j */
+ uint j0 = gl_WorkGroupID.y;
+ uint runs = (RP(p.pos).v[0] + j0 + C) / C; /* npos / C, rounded up */
+ R PR = R(p.part);
+ uint e = 256u * b + t, h = e / hd, i = e % hd;
+ uint at = j0 * p.ps + h * p.nch * (hd + 2u);
+ float M = PR.v[at + hd];
+ for (uint c = 1u; c < runs; c++)
+ M = max(M, PR.v[at + c * (hd + 2u) + hd]);
+ float L = 0.0, a = 0.0;
+ for (uint c = 0; c < runs; c++) {
+ uint o = at + c * (hd + 2u);
+ float f = exp(PR.v[o + hd] - M);
+ L += PR.v[o + hd + 1u] * f;
+ a += PR.v[o + i] * f;
+ }
+ float v = a / L;
+ /* the maxima of the groups of 32 and of the block */
+ float mc = subgroupClusteredMax(abs(v), 8u);
+ if (t % 8u == 0u)
+ m8[t / 8u] = mc;
+ barrier();
+ uint l = t / 32u;
+ float m32 = max(max(m8[4u * l], m8[4u * l + 1u]), max(m8[4u * l + 2u], m8[4u * l + 3u]));
+ float m256 = 0.0;
+ for (uint k = 0; k < 32u; k++)
+ m256 = max(m256, m8[k]);
+ precise float dd = m256 * 0.007874015718698502;
+ float id = dd > 0.0 ? recip_det(dd) : 0.0;
+ precise float d32 = m32 * 0.007874015718698502;
+ float id32 = d32 > 0.0 ? recip_det(d32) : 0.0;
+ int qa = q8(v, id), qb = q8(v, id32);
+ /* four quants a word, from four neighbouring threads */
+ uint wa = subgroupClusteredOr((uint(qa) & 0xffu) << (8u * (t % 4u)), 4u);
+ uint wb = subgroupClusteredOr((uint(qb) & 0xffu) << (8u * (t % 4u)), 4u);
+ uint base = (j0 * gl_NumWorkGroups.x + b) * 80u; /* 320 bytes a block */
+ if (t % 4u == 0u) {
+ Q.v[base + t / 4u] = wa;
+ if (set(p.q32))
+ Q32.v[base + t / 4u] = wb;
+ }
+ /* the sums of 16 quants: two of eight each */
+ int ca = subgroupClusteredAdd(qa, 8u), cb = subgroupClusteredAdd(qb, 8u);
+ if (t % 8u == 0u) {
+ s8a[t / 8u] = ca;
+ s8b[t / 8u] = cb;
+ }
+ barrier();
+ if (t < 8u) {
+ int sa0 = s8a[4u * t] + s8a[4u * t + 1u], sa1 = s8a[4u * t + 2u] + s8a[4u * t + 3u];
+ Q.v[base + 64u + t] = (uint(sa0) & 0xffffu) | (uint(sa1) << 16);
+ if (set(p.q32)) {
+ int sb0 = s8b[4u * t] + s8b[4u * t + 1u], sb1 = s8b[4u * t + 2u] + s8b[4u * t + 3u];
+ Q32.v[base + 64u + t] = (uint(sb0) & 0xffffu) | (uint(sb1) << 16);
+ precise float dt =
+ max(max(m8[4u * t], m8[4u * t + 1u]), max(m8[4u * t + 2u], m8[4u * t + 3u])) *
+ 0.007874015718698502;
+ Q32.v[base + 72u + t] = floatBitsToUint(dt);
+ }
+ }
+ if (t == 0u)
+ Q.v[base + 72u] = floatBitsToUint(dd);
+}
diff --git a/src/llm/shaders/b32_matvec.comp b/src/llm/shaders/b32_matvec.comp
new file mode 100644
index 0000000..25b1dd2
--- /dev/null
+++ b/src/llm/shaders/b32_matvec.comp
@@ -0,0 +1,148 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Weights in blocks of 32 with four- or five-bit values, KIND chosen when
+// the pipeline is made: 0 Q4_0 (q - 8), 1 IQ4_NL (a table of sixteen
+// levels), 2 Q4_1 and 3 Q5_1 (d q + m, Q5_1 with a fifth bit per weight in
+// qh). As the CPU computes them (nib_dot_ref and dm_dot_ref in quant.c):
+// each block's integer dot in one fma into the accumulator of its position
+// in the group of eight, the minimum of Q4_1/Q5_1 (m times the block's
+// activation sum) in accumulators of its own, the eight added at the end as
+// janas_hsum8 does - the same float operations, so the results agree bit
+// for bit. Q4_0's q - 8 is folded as the exact integer sum q.a - 8 sum(a).
+// The activations come in the 32-block layout (20 uvec4 a Q8_K block: qs32
+// in 16, bsums32 in 2, d32 in 2), shared across the subgroup as in
+// q4k_matvec.comp. The low nibbles of a block's 16 bytes are weights 0-15,
+// the high ones 16-31.
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_ballot : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 8;
+layout(constant_id = 1) const uint SG = 8;
+layout(constant_id = 2) const uint KIND = 0;
+const uint NX = (20u + SG - 1u) / SG;
+/* bytes of a block, and of a group of eight in words */
+const uint S = KIND == 3u ? 24u : KIND == 2u ? 20u : 18u;
+const uint GW = 2u * S;
+const bool DM = KIND >= 2u;
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+const int IQ4[16] = int[16](-127, -104, -83, -65, -49, -35, -22, -10,
+ 1, 13, 25, 38, 53, 69, 89, 113);
+
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+int dp4(uvec4 a, uvec4 b) { return dp(a.x, b.x) + dp(a.y, b.y) + dp(a.z, b.z) + dp(a.w, b.w); }
+uvec4 bc(uvec4 xr[NX], uint k) { return subgroupBroadcast(xr[k / SG], k % SG); }
+
+/* four bits (weights 4j..4j+3) spread to bit 4 of each byte */
+uint spread5(uint b)
+{
+ return ((b & 1u) << 4) | ((b & 2u) << 11) | ((b & 4u) << 18) | ((b & 8u) << 25);
+}
+
+/* each byte of w through the IQ4_NL table */
+uint iq4(uint w)
+{
+ return (uint(IQ4[w & 15u]) & 0xffu) | ((uint(IQ4[(w >> 8) & 15u]) & 0xffu) << 8) |
+ ((uint(IQ4[(w >> 16) & 15u]) & 0xffu) << 16) |
+ ((uint(IQ4[(w >> 24) & 15u]) & 0xffu) << 24);
+}
+
+float hsum8(float a[8])
+{
+ return ((a[0] + a[4]) + (a[2] + a[6])) + ((a[1] + a[5]) + (a[3] + a[7]));
+}
+
+void main()
+{
+ U1 W = U1(p.w);
+ U4 X = U4(p.x);
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID;
+ uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.y * NV;
+ uint xo[NV];
+ for (uint v = 0; v < NV; v++)
+ xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
+ float acc[NV][8], accm[NV][8];
+ for (uint v = 0; v < NV; v++)
+ for (uint k = 0; k < 8u; k++) {
+ acc[v][k] = 0.0;
+ accm[v][k] = 0.0;
+ }
+ uint gw = row * p.nb * GW;
+ for (uint b = 0; b < p.nb; b++, gw += GW) {
+ uint wg[48];
+ for (uint i = 0; i < GW; i++)
+ wg[i] = W.v[gw + i];
+ float d[8], m[8];
+ uvec4 lo[8], hi[8];
+ for (uint k = 0; k < 8u; k++) {
+ uint B = S * k; /* the block's first byte */
+ uint hw = wg[B >> 2];
+ vec2 dm = unpackHalf2x16((B & 2u) != 0u ? (hw >> 16) | (wg[(B >> 2) + 1u] << 16) : hw);
+ d[k] = dm.x;
+ m[k] = dm.y;
+ uint qb = B + S - 16u, wi = qb >> 2;
+ uint q[4];
+ for (uint i = 0; i < 4u; i++)
+ q[i] = (qb & 2u) != 0u ? (wg[wi + i] >> 16) | (wg[wi + i + 1u] << 16) : wg[wi + i];
+ uint qh = KIND == 3u ? wg[(B + 4u) >> 2] : 0u;
+ for (uint i = 0; i < 4u; i++) {
+ uint l = q[i] & 0x0f0f0f0fu, h = (q[i] >> 4) & 0x0f0f0f0fu;
+ if (KIND == 1u) {
+ l = iq4(l);
+ h = iq4(h);
+ } else if (KIND == 3u) {
+ l |= spread5((qh >> (4u * i)) & 15u);
+ h |= spread5((qh >> (16u + 4u * i)) & 15u);
+ }
+ q[i] = l;
+ if (i == 0u) { lo[k].x = l; hi[k].x = h; }
+ if (i == 1u) { lo[k].y = l; hi[k].y = h; }
+ if (i == 2u) { lo[k].z = l; hi[k].z = h; }
+ if (i == 3u) { lo[k].w = l; hi[k].w = h; }
+ }
+ }
+ for (uint v = 0; v < NV; v++) {
+ uvec4 xr[NX];
+ for (uint j = 0; j < NX; j++)
+ xr[j] = X.v[xo[v] + min(j * SG + lane, 19u)];
+ uvec4 s0 = bc(xr, 18u), s1 = bc(xr, 19u);
+ float d32[8] = float[8](uintBitsToFloat(s0.x), uintBitsToFloat(s0.y),
+ uintBitsToFloat(s0.z), uintBitsToFloat(s0.w),
+ uintBitsToFloat(s1.x), uintBitsToFloat(s1.y),
+ uintBitsToFloat(s1.z), uintBitsToFloat(s1.w));
+ uvec4 b0 = bc(xr, 16u), b1 = bc(xr, 17u);
+ uint bw[8] = uint[8](b0.x, b0.y, b0.z, b0.w, b1.x, b1.y, b1.z, b1.w);
+ for (uint k = 0; k < 8u; k++) {
+ int dot = dp4(lo[k], bc(xr, 2u * k)) + dp4(hi[k], bc(xr, 2u * k + 1u));
+ /* the block's activation sum: bsums32 of its two halves */
+ int asum = bitfieldExtract(int(bw[k]), 0, 16) + bitfieldExtract(int(bw[k]), 16, 16);
+ if (KIND == 0u)
+ dot -= 8 * asum;
+ acc[v][k] = fma(d[k] * d32[k], float(dot), acc[v][k]);
+ if (DM)
+ accm[v][k] = fma(m[k] * d32[k], float(asum), accm[v][k]);
+ }
+ xo[v] += 20u;
+ }
+ }
+ if (gl_GlobalInvocationID.x < p.rows)
+ for (uint v = 0; v < NV; v++)
+ if (v0 + v < p.nv) {
+ float r = hsum8(acc[v]);
+ if (DM)
+ r = r + hsum8(accm[v]);
+ Y.v[(v0 + v) * p.ys + row] = r;
+ }
+}
diff --git a/src/llm/shaders/expert_act.comp b/src/llm/shaders/expert_act.comp
index cdc3797..fb0d40b 100644
--- a/src/llm/shaders/expert_act.comp
+++ b/src/llm/shaders/expert_act.comp
@@ -9,6 +9,8 @@
// One workgroup per 256-value block; gate and up of block b of item i at
// g[(i * nb + b) * 256 ...], u likewise; the output block at x.
#extension GL_EXT_buffer_reference : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_arithmetic : require
#extension GL_EXT_buffer_reference_uvec2 : require
layout(local_size_x = 256) in;
@@ -18,7 +20,23 @@ layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer U
layout(push_constant) uniform P { uvec2 g, u, x; uint blocks; } p;
-shared float amax_s[256];
+/* The workgroup's maximum: each subgroup's in one operation, then the
+ subgroups' - two barriers, not one per level of a tree. */
+shared float sg_part[64];
+
+float wg_max(float s)
+{
+ float r = subgroupMax(s);
+ if (subgroupElect())
+ sg_part[gl_SubgroupID] = r;
+ barrier();
+ float m = sg_part[0];
+ for (uint i = 1u; i < gl_NumSubgroups; i++)
+ m = max(m, sg_part[i]);
+ barrier();
+ return m;
+}
+
shared int q_s[256];
float exp_det(float x)
@@ -62,14 +80,8 @@ void main()
precise float gs = gv * s;
precise float h = gs * uv;
/* the block's largest magnitude (max is exact in any order) */
- amax_s[t] = abs(h);
- barrier();
- for (uint w = 128u; w > 0u; w >>= 1) {
- if (t < w)
- amax_s[t] = max(amax_s[t], amax_s[t + w]);
- barrier();
- }
- precise float d = amax_s[0] * 0.007874015718698502;
+ float amax = wg_max(abs(h));
+ precise float d = amax * 0.007874015718698502;
precise float id = d > 0.0 ? recip_det(d) : 0.0;
precise float qf = roundEven(h * id);
q_s[t] = int(clamp(qf, -127.0, 127.0));
diff --git a/src/llm/shaders/iq3s_matvec.comp b/src/llm/shaders/iq3s_matvec.comp
new file mode 100644
index 0000000..3482ac2
--- /dev/null
+++ b/src/llm/shaders/iq3s_matvec.comp
@@ -0,0 +1,202 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri
+ The table GRID below is the IQ3_S grid of ggml (ggml/src/ggml-common.h,
+ iq3s_grid), copied as data from src/llm/iq3s_grid.h: it defines the
+ format. Copyright (c) 2023-2026 The ggml authors, under the MIT licence
+ (see the ggml repository). */
+#version 450
+// IQ3_S weights times up to NV Q8_K vectors, one row per invocation, as
+// janas_iq3s_dot_ref computes it: eight groups of 32, each weight a level
+// of the grid (a 9-bit index for four weights: qs[8 g + k], its ninth bit
+// bit k of qh[g]) with its sign (bit e of signs[4 g + e / 8]), each group's
+// integer dot times its scale 1 + 2 x a nibble, the block's exact integer
+// sum in one fma: the CPU's float operation, so the results agree bit for
+// bit. A block is 110 bytes (d 2, qs 64, qh 8, signs 32, scales 4): every
+// other one starts 2 bytes off a 4-byte boundary, and its words are
+// realigned. Activations shared across the subgroup as in q4k_matvec.comp.
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_ballot : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 8;
+layout(constant_id = 1) const uint SG = 8;
+const uint NX = (19u + SG - 1u) / SG;
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+const uint GRID[512] = uint[512](
+ 0x01010101u, 0x01010103u, 0x01010105u, 0x0101010bu, 0x0101010fu, 0x01010301u,
+ 0x01010303u, 0x01010305u, 0x01010309u, 0x0101030du, 0x01010501u, 0x01010503u,
+ 0x0101050bu, 0x01010707u, 0x01010901u, 0x01010905u, 0x0101090bu, 0x0101090fu,
+ 0x01010b03u, 0x01010b07u, 0x01010d01u, 0x01010d05u, 0x01010f03u, 0x01010f09u,
+ 0x01010f0fu, 0x01030101u, 0x01030103u, 0x01030105u, 0x01030109u, 0x01030301u,
+ 0x01030303u, 0x0103030bu, 0x01030501u, 0x01030507u, 0x0103050fu, 0x01030703u,
+ 0x0103070bu, 0x01030909u, 0x01030d03u, 0x01030d0bu, 0x01030f05u, 0x01050101u,
+ 0x01050103u, 0x0105010bu, 0x0105010fu, 0x01050301u, 0x01050307u, 0x0105030du,
+ 0x01050503u, 0x0105050bu, 0x01050701u, 0x01050709u, 0x01050905u, 0x0105090bu,
+ 0x0105090fu, 0x01050b03u, 0x01050b07u, 0x01050f01u, 0x01050f07u, 0x01070107u,
+ 0x01070303u, 0x0107030bu, 0x01070501u, 0x01070505u, 0x01070703u, 0x01070707u,
+ 0x0107070du, 0x01070909u, 0x01070b01u, 0x01070b05u, 0x01070d0fu, 0x01070f03u,
+ 0x01070f0bu, 0x01090101u, 0x01090307u, 0x0109030fu, 0x01090503u, 0x01090509u,
+ 0x01090705u, 0x01090901u, 0x01090907u, 0x01090b03u, 0x01090f01u, 0x010b0105u,
+ 0x010b0109u, 0x010b0501u, 0x010b0505u, 0x010b050du, 0x010b0707u, 0x010b0903u,
+ 0x010b090bu, 0x010b090fu, 0x010b0d0du, 0x010b0f07u, 0x010d010du, 0x010d0303u,
+ 0x010d0307u, 0x010d0703u, 0x010d0b05u, 0x010d0f03u, 0x010f0101u, 0x010f0105u,
+ 0x010f0109u, 0x010f0501u, 0x010f0505u, 0x010f050du, 0x010f0707u, 0x010f0b01u,
+ 0x010f0b09u, 0x03010101u, 0x03010103u, 0x03010105u, 0x03010109u, 0x03010301u,
+ 0x03010303u, 0x03010307u, 0x0301030bu, 0x0301030fu, 0x03010501u, 0x03010505u,
+ 0x03010703u, 0x03010709u, 0x0301070du, 0x03010b09u, 0x03010b0du, 0x03010d03u,
+ 0x03010f05u, 0x03030101u, 0x03030103u, 0x03030107u, 0x0303010du, 0x03030301u,
+ 0x03030309u, 0x03030503u, 0x03030701u, 0x03030707u, 0x03030903u, 0x03030b01u,
+ 0x03030b05u, 0x03030f01u, 0x03030f0du, 0x03050101u, 0x03050305u, 0x0305030bu,
+ 0x0305030fu, 0x03050501u, 0x03050509u, 0x03050705u, 0x03050901u, 0x03050907u,
+ 0x03050b0bu, 0x03050d01u, 0x03050f05u, 0x03070103u, 0x03070109u, 0x0307010fu,
+ 0x03070301u, 0x03070307u, 0x03070503u, 0x0307050fu, 0x03070701u, 0x03070709u,
+ 0x03070903u, 0x03070d05u, 0x03070f01u, 0x03090107u, 0x0309010bu, 0x03090305u,
+ 0x03090309u, 0x03090703u, 0x03090707u, 0x03090905u, 0x0309090du, 0x03090b01u,
+ 0x03090b09u, 0x030b0103u, 0x030b0301u, 0x030b0307u, 0x030b0503u, 0x030b0701u,
+ 0x030b0705u, 0x030b0b03u, 0x030d0501u, 0x030d0509u, 0x030d050fu, 0x030d0909u,
+ 0x030d090du, 0x030f0103u, 0x030f0107u, 0x030f0301u, 0x030f0305u, 0x030f0503u,
+ 0x030f070bu, 0x030f0903u, 0x030f0d05u, 0x030f0f01u, 0x05010101u, 0x05010103u,
+ 0x05010107u, 0x0501010bu, 0x0501010fu, 0x05010301u, 0x05010305u, 0x05010309u,
+ 0x0501030du, 0x05010503u, 0x05010507u, 0x0501050fu, 0x05010701u, 0x05010705u,
+ 0x05010903u, 0x05010907u, 0x0501090bu, 0x05010b01u, 0x05010b05u, 0x05010d0fu,
+ 0x05010f01u, 0x05010f07u, 0x05010f0bu, 0x05030101u, 0x05030105u, 0x05030301u,
+ 0x05030307u, 0x0503030fu, 0x05030505u, 0x0503050bu, 0x05030703u, 0x05030709u,
+ 0x05030905u, 0x05030b03u, 0x05050103u, 0x05050109u, 0x0505010fu, 0x05050503u,
+ 0x05050507u, 0x05050701u, 0x0505070fu, 0x05050903u, 0x05050b07u, 0x05050b0fu,
+ 0x05050f03u, 0x05050f09u, 0x05070101u, 0x05070105u, 0x0507010bu, 0x05070303u,
+ 0x05070505u, 0x05070509u, 0x05070703u, 0x05070707u, 0x05070905u, 0x05070b01u,
+ 0x05070d0du, 0x05090103u, 0x0509010fu, 0x05090501u, 0x05090507u, 0x05090705u,
+ 0x0509070bu, 0x05090903u, 0x05090f05u, 0x05090f0bu, 0x050b0109u, 0x050b0303u,
+ 0x050b0505u, 0x050b070fu, 0x050b0901u, 0x050b0b07u, 0x050b0f01u, 0x050d0101u,
+ 0x050d0105u, 0x050d010fu, 0x050d0503u, 0x050d0b0bu, 0x050d0d03u, 0x050f010bu,
+ 0x050f0303u, 0x050f050du, 0x050f0701u, 0x050f0907u, 0x050f0b01u, 0x07010105u,
+ 0x07010303u, 0x07010307u, 0x0701030bu, 0x0701030fu, 0x07010505u, 0x07010703u,
+ 0x07010707u, 0x0701070bu, 0x07010905u, 0x07010909u, 0x0701090fu, 0x07010b03u,
+ 0x07010d07u, 0x07010f03u, 0x07030103u, 0x07030107u, 0x0703010bu, 0x07030309u,
+ 0x07030503u, 0x07030507u, 0x07030901u, 0x07030d01u, 0x07030f05u, 0x07030f0du,
+ 0x07050101u, 0x07050305u, 0x07050501u, 0x07050705u, 0x07050709u, 0x07050b01u,
+ 0x07070103u, 0x07070301u, 0x07070309u, 0x07070503u, 0x07070507u, 0x0707050fu,
+ 0x07070701u, 0x07070903u, 0x07070907u, 0x0707090fu, 0x07070b0bu, 0x07070f07u,
+ 0x07090107u, 0x07090303u, 0x0709030du, 0x07090505u, 0x07090703u, 0x07090b05u,
+ 0x07090d01u, 0x07090d09u, 0x070b0103u, 0x070b0301u, 0x070b0305u, 0x070b050bu,
+ 0x070b0705u, 0x070b0909u, 0x070b0b0du, 0x070b0f07u, 0x070d030du, 0x070d0903u,
+ 0x070f0103u, 0x070f0107u, 0x070f0501u, 0x070f0505u, 0x070f070bu, 0x09010101u,
+ 0x09010109u, 0x09010305u, 0x09010501u, 0x09010509u, 0x0901050fu, 0x09010705u,
+ 0x09010903u, 0x09010b01u, 0x09010f01u, 0x09030105u, 0x0903010fu, 0x09030303u,
+ 0x09030307u, 0x09030505u, 0x09030701u, 0x0903070bu, 0x09030907u, 0x09030b03u,
+ 0x09030b0bu, 0x09050103u, 0x09050107u, 0x09050301u, 0x0905030bu, 0x09050503u,
+ 0x09050707u, 0x09050901u, 0x09050b0fu, 0x09050d05u, 0x09050f01u, 0x09070109u,
+ 0x09070303u, 0x09070307u, 0x09070501u, 0x09070505u, 0x09070703u, 0x0907070bu,
+ 0x09090101u, 0x09090105u, 0x09090509u, 0x0909070fu, 0x09090901u, 0x09090f03u,
+ 0x090b010bu, 0x090b010fu, 0x090b0503u, 0x090b0d05u, 0x090d0307u, 0x090d0709u,
+ 0x090d0d01u, 0x090f0301u, 0x090f030bu, 0x090f0701u, 0x090f0907u, 0x090f0b03u,
+ 0x0b010105u, 0x0b010301u, 0x0b010309u, 0x0b010505u, 0x0b010901u, 0x0b010909u,
+ 0x0b01090fu, 0x0b010b05u, 0x0b010d0du, 0x0b010f09u, 0x0b030103u, 0x0b030107u,
+ 0x0b03010bu, 0x0b030305u, 0x0b030503u, 0x0b030705u, 0x0b030f05u, 0x0b050101u,
+ 0x0b050303u, 0x0b050507u, 0x0b050701u, 0x0b05070du, 0x0b050b07u, 0x0b070105u,
+ 0x0b07010fu, 0x0b070301u, 0x0b07050fu, 0x0b070909u, 0x0b070b03u, 0x0b070d0bu,
+ 0x0b070f07u, 0x0b090103u, 0x0b090109u, 0x0b090501u, 0x0b090705u, 0x0b09090du,
+ 0x0b0b0305u, 0x0b0b050du, 0x0b0b0b03u, 0x0b0b0b07u, 0x0b0d0905u, 0x0b0f0105u,
+ 0x0b0f0109u, 0x0b0f0505u, 0x0d010303u, 0x0d010307u, 0x0d01030bu, 0x0d010703u,
+ 0x0d010707u, 0x0d010d01u, 0x0d030101u, 0x0d030501u, 0x0d03050fu, 0x0d030d09u,
+ 0x0d050305u, 0x0d050709u, 0x0d050905u, 0x0d050b0bu, 0x0d050d05u, 0x0d050f01u,
+ 0x0d070101u, 0x0d070309u, 0x0d070503u, 0x0d070901u, 0x0d09050bu, 0x0d090907u,
+ 0x0d090d05u, 0x0d0b0101u, 0x0d0b0107u, 0x0d0b0709u, 0x0d0b0d01u, 0x0d0d010bu,
+ 0x0d0d0901u, 0x0d0f0303u, 0x0d0f0307u, 0x0f010101u, 0x0f010109u, 0x0f01010fu,
+ 0x0f010501u, 0x0f010505u, 0x0f01070du, 0x0f010901u, 0x0f010b09u, 0x0f010d05u,
+ 0x0f030105u, 0x0f030303u, 0x0f030509u, 0x0f030907u, 0x0f03090bu, 0x0f050103u,
+ 0x0f050109u, 0x0f050301u, 0x0f05030du, 0x0f050503u, 0x0f050701u, 0x0f050b03u,
+ 0x0f070105u, 0x0f070705u, 0x0f07070bu, 0x0f070b07u, 0x0f090103u, 0x0f09010bu,
+ 0x0f090307u, 0x0f090501u, 0x0f090b01u, 0x0f0b0505u, 0x0f0b0905u, 0x0f0d0105u,
+ 0x0f0d0703u, 0x0f0f0101u);
+
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+uvec4 bc(uvec4 xr[NX], uint k) { return subgroupBroadcast(xr[k / SG], k % SG); }
+
+/* byte i of the block's realigned words */
+uint byte_at(uint wd[28], uint i) { return (wd[i >> 2] >> (8u * (i & 3u))) & 0xffu; }
+
+/* the four levels of a grid entry, each negated where its sign bit is set
+ (bits 0-3 of s), as signed bytes */
+uint signed4(uint g, uint s)
+{
+ uint r = 0u;
+ for (uint i = 0; i < 4u; i++) {
+ int v = int((g >> (8u * i)) & 0xffu);
+ if (((s >> i) & 1u) != 0u)
+ v = -v;
+ r |= (uint(v) & 0xffu) << (8u * i);
+ }
+ return r;
+}
+
+void main()
+{
+ U1 W = U1(p.w);
+ U4 X = U4(p.x);
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID;
+ uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.y * NV;
+ uint xo[NV];
+ for (uint v = 0; v < NV; v++)
+ xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
+ float acc[NV];
+ for (uint v = 0; v < NV; v++)
+ acc[v] = 0.0;
+ uint off = row * p.nb * 110u; /* bytes */
+ for (uint b = 0; b < p.nb; b++, off += 110u) {
+ uint base = off >> 2, sh = (off & 3u) * 8u;
+ uint wd[28];
+ for (uint k = 0; k < 28u; k++)
+ wd[k] = W.v[base + k];
+ if (sh != 0u) {
+ for (uint k = 0; k < 27u; k++)
+ wd[k] = (wd[k] >> 16) | (wd[k + 1u] << 16);
+ wd[27] = wd[27] >> 16;
+ }
+ float d = unpackHalf2x16(wd[0] & 0xffffu).x;
+ /* the 64 signed words: group g, word k = weights 4k..4k+3 */
+ uint q[64];
+ int sc[8];
+ for (uint g = 0; g < 8u; g++) {
+ uint qh = byte_at(wd, 66u + g);
+ for (uint k = 0; k < 8u; k++) {
+ uint idx = byte_at(wd, 2u + 8u * g + k) | (((qh >> k) & 1u) << 8);
+ uint sg = byte_at(wd, 74u + 4u * g + k / 2u) >> (4u * (k & 1u));
+ q[8u * g + k] = signed4(GRID[idx], sg & 15u);
+ }
+ sc[g] = 1 + 2 * int((byte_at(wd, 106u + g / 2u) >> (4u * (g & 1u))) & 15u);
+ }
+ for (uint v = 0; v < NV; v++) {
+ uvec4 xr[NX];
+ for (uint j = 0; j < NX; j++)
+ xr[j] = X.v[xo[v] + min(j * SG + lane, 19u)];
+ int isum = 0;
+ for (uint g = 0; g < 8u; g++) {
+ uvec4 a0 = bc(xr, 2u * g), a1 = bc(xr, 2u * g + 1u);
+ uint q0 = 8u * g;
+ int s = dp(q[q0], a0.x) + dp(q[q0 + 1u], a0.y) + dp(q[q0 + 2u], a0.z) +
+ dp(q[q0 + 3u], a0.w) + dp(q[q0 + 4u], a1.x) + dp(q[q0 + 5u], a1.y) +
+ dp(q[q0 + 6u], a1.z) + dp(q[q0 + 7u], a1.w);
+ isum += sc[g] * s;
+ }
+ float d8 = uintBitsToFloat(bc(xr, 18u).x);
+ acc[v] = fma(d * d8, float(isum), acc[v]);
+ xo[v] += 20u;
+ }
+ }
+ if (gl_GlobalInvocationID.x < p.rows)
+ for (uint v = 0; v < NV; v++)
+ if (v0 + v < p.nv)
+ Y.v[(v0 + v) * p.ys + row] = acc[v];
+}
diff --git a/src/llm/shaders/iq4xs_matvec.comp b/src/llm/shaders/iq4xs_matvec.comp
new file mode 100644
index 0000000..c712fb1
--- /dev/null
+++ b/src/llm/shaders/iq4xs_matvec.comp
@@ -0,0 +1,92 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// IQ4_XS weights times up to NV Q8_K vectors, one row per invocation, as
+// janas_iq4xs_dot_ref computes it: eight groups of 32 weights through the
+// sixteen levels of IQ4_NL, each group's integer dot times its 6-bit scale
+// (ls - 32), the block's exact integer sum in one fma: the same float
+// operation as the CPU, so the results agree bit for bit. A block is 136
+// bytes, 34 words: d and scales_h, scales_l, then the nibbles, group g's 16
+// bytes holding its weights 0-15 (low nibbles) and 16-31 (high).
+// Activations shared across the subgroup as in q4k_matvec.comp.
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_ballot : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 8;
+layout(constant_id = 1) const uint SG = 8;
+const uint NX = (19u + SG - 1u) / SG;
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+const int IQ4[16] = int[16](-127, -104, -83, -65, -49, -35, -22, -10,
+ 1, 13, 25, 38, 53, 69, 89, 113);
+
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+int dp4(uvec4 a, uvec4 b) { return dp(a.x, b.x) + dp(a.y, b.y) + dp(a.z, b.z) + dp(a.w, b.w); }
+uvec4 bc(uvec4 xr[NX], uint k) { return subgroupBroadcast(xr[k / SG], k % SG); }
+
+/* each byte of w (a nibble) through the IQ4_NL table */
+uint iq4(uint w)
+{
+ return (uint(IQ4[w & 15u]) & 0xffu) | ((uint(IQ4[(w >> 8) & 15u]) & 0xffu) << 8) |
+ ((uint(IQ4[(w >> 16) & 15u]) & 0xffu) << 16) |
+ ((uint(IQ4[(w >> 24) & 15u]) & 0xffu) << 24);
+}
+
+void main()
+{
+ U1 W = U1(p.w);
+ U4 X = U4(p.x);
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID;
+ uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.y * NV;
+ uint xo[NV];
+ for (uint v = 0; v < NV; v++)
+ xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
+ float acc[NV];
+ for (uint v = 0; v < NV; v++)
+ acc[v] = 0.0;
+ uint wo = row * p.nb * 34u;
+ for (uint b = 0; b < p.nb; b++, wo += 34u) {
+ uint w0 = W.v[wo], sl = W.v[wo + 1u];
+ float d = unpackHalf2x16(w0).x;
+ uint sh = w0 >> 16;
+ int sc[8];
+ uvec4 lo[8], hi[8];
+ for (uint g = 0; g < 8u; g++) {
+ uint ls = ((sl >> (8u * (g / 2u) + 4u * (g & 1u))) & 15u) |
+ (((sh >> (2u * g)) & 3u) << 4);
+ sc[g] = int(ls) - 32;
+ uvec4 q = uvec4(W.v[wo + 2u + 4u * g], W.v[wo + 3u + 4u * g],
+ W.v[wo + 4u + 4u * g], W.v[wo + 5u + 4u * g]);
+ lo[g] = uvec4(iq4(q.x & 0x0f0f0f0fu), iq4(q.y & 0x0f0f0f0fu),
+ iq4(q.z & 0x0f0f0f0fu), iq4(q.w & 0x0f0f0f0fu));
+ hi[g] = uvec4(iq4((q.x >> 4) & 0x0f0f0f0fu), iq4((q.y >> 4) & 0x0f0f0f0fu),
+ iq4((q.z >> 4) & 0x0f0f0f0fu), iq4((q.w >> 4) & 0x0f0f0f0fu));
+ }
+ for (uint v = 0; v < NV; v++) {
+ uvec4 xr[NX];
+ for (uint j = 0; j < NX; j++)
+ xr[j] = X.v[xo[v] + min(j * SG + lane, 19u)];
+ int isum = 0;
+ for (uint g = 0; g < 8u; g++)
+ isum += sc[g] * (dp4(lo[g], bc(xr, 2u * g)) + dp4(hi[g], bc(xr, 2u * g + 1u)));
+ float d8 = uintBitsToFloat(bc(xr, 18u).x);
+ acc[v] = fma(d * d8, float(isum), acc[v]);
+ xo[v] += 20u;
+ }
+ }
+ if (gl_GlobalInvocationID.x < p.rows)
+ for (uint v = 0; v < NV; v++)
+ if (v0 + v < p.nv)
+ Y.v[(v0 + v) * p.ys + row] = acc[v];
+}
diff --git a/src/llm/shaders/norm_quant.comp b/src/llm/shaders/norm_quant.comp
new file mode 100644
index 0000000..49ff604
--- /dev/null
+++ b/src/llm/shaders/norm_quant.comp
@@ -0,0 +1,144 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// A vector of d floats on its way into the products: x + add (the
+// residual, if add is set) stored at xo (if set), then v = rms_norm(x) * w
+// (if w is set; else v = x), quantized to Q8_K in the product shaders'
+// layouts - q256 (qs, bsums, d: janas_q8k_quantize_det) and q32 (the eight
+// blocks of 32 with a scale each, if q32 is set). One workgroup per block
+// of 256 values: each one makes the whole vector's sum of squares, the
+// same operations in the same order, so the same bits, then normalizes and
+// quantizes its own block, a value a thread. x is only read: the residual
+// goes to xo, another buffer, as the other workgroups may still be reading
+// x. The sum of squares is the GPU's own (float: each subgroup's, then
+// theirs in order); the quantization is the deterministic one, with the
+// CPU's operations (amax x 1/127 as a product, the reciprocal by Newton
+// steps, rounding to even) - maxima and integer sums, exact in any order.
+#extension GL_EXT_buffer_reference : require
+#extension GL_KHR_shader_subgroup_arithmetic : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_clustered : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 256) in;
+
+layout(buffer_reference, std430, buffer_reference_align = 4) buffer F { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer U { uint v[]; };
+
+layout(push_constant) uniform P { uvec2 x, add, w, xo, q256, q32; uint d; float eps; } p;
+
+/* The workgroup's sum: each subgroup's in one operation, then the
+ subgroups' in a fixed order. */
+shared float sg_part[64];
+
+float wg_sum(float s)
+{
+ float r = subgroupAdd(s);
+ if (subgroupElect())
+ sg_part[gl_SubgroupID] = r;
+ barrier();
+ float tot = sg_part[0];
+ for (uint i = 1u; i < gl_NumSubgroups; i++)
+ tot += sg_part[i];
+ barrier();
+ return tot;
+}
+
+shared float m8[32]; /* the block's maxima, eight values each */
+shared int s8a[32], s8b[32]; /* and its quants' sums, eight each */
+
+bool set(uvec2 a) { return a.x != 0u || a.y != 0u; }
+
+float recip_det(float d)
+{
+ precise float y = uintBitsToFloat(0x7EF311C3u - floatBitsToUint(d));
+ for (int i = 0; i < 3; i++)
+ y = fma(y, fma(-d, y, 1.0), y);
+ return y;
+}
+
+int q8(float v, float id)
+{
+ precise float q = roundEven(v * id);
+ return int(clamp(q, -127.0, 127.0));
+}
+
+void main()
+{
+ /* vector j of a block (workgroup y): d floats a vector, d / 256
+ quantized blocks */
+ uint t = gl_LocalInvocationID.x, b = gl_WorkGroupID.x, d = p.d;
+ uint j = gl_WorkGroupID.y, xo0 = j * d;
+ F X = F(p.x), A = F(p.add), Wt = F(p.w), XO = F(p.xo);
+ U Q = U(p.q256), Q32 = U(p.q32);
+ float scale = 1.0;
+ if (set(p.w)) {
+ float ss = 0.0;
+ for (uint i = t; i < d; i += 256u) {
+ precise float xv = X.v[xo0 + i];
+ if (set(p.add))
+ xv = xv + A.v[xo0 + i];
+ ss += xv * xv;
+ }
+ ss = wg_sum(ss);
+ precise float sc = 1.0 / sqrt(ss / float(d) + p.eps);
+ scale = sc;
+ }
+ /* this thread's value: element 256 b + t */
+ uint e = 256u * b + t;
+ precise float xv = X.v[xo0 + e];
+ if (set(p.add))
+ xv = xv + A.v[xo0 + e];
+ if (set(p.xo))
+ XO.v[xo0 + e] = xv;
+ float v = xv;
+ if (set(p.w)) {
+ precise float vs = xv * scale;
+ v = vs * Wt.v[e];
+ }
+ /* the maxima of the groups of 32 and of the block */
+ float mc = subgroupClusteredMax(abs(v), 8u);
+ if (t % 8u == 0u)
+ m8[t / 8u] = mc;
+ barrier();
+ uint l = t / 32u;
+ float m32 = max(max(m8[4u * l], m8[4u * l + 1u]), max(m8[4u * l + 2u], m8[4u * l + 3u]));
+ float m256 = 0.0;
+ for (uint k = 0; k < 32u; k++)
+ m256 = max(m256, m8[k]);
+ precise float dd = m256 * 0.007874015718698502;
+ float id = dd > 0.0 ? recip_det(dd) : 0.0;
+ precise float d32 = m32 * 0.007874015718698502;
+ float id32 = d32 > 0.0 ? recip_det(d32) : 0.0;
+ int qa = q8(v, id), qb = q8(v, id32);
+ /* four quants a word, from four neighbouring threads */
+ uint wa = subgroupClusteredOr((uint(qa) & 0xffu) << (8u * (t % 4u)), 4u);
+ uint wb = subgroupClusteredOr((uint(qb) & 0xffu) << (8u * (t % 4u)), 4u);
+ uint base = (j * gl_NumWorkGroups.x + b) * 80u; /* 320 bytes a block */
+ if (t % 4u == 0u) {
+ Q.v[base + t / 4u] = wa;
+ if (set(p.q32))
+ Q32.v[base + t / 4u] = wb;
+ }
+ /* the sums of 16 quants: two of eight each */
+ int ca = subgroupClusteredAdd(qa, 8u), cb = subgroupClusteredAdd(qb, 8u);
+ if (t % 8u == 0u) {
+ s8a[t / 8u] = ca;
+ s8b[t / 8u] = cb;
+ }
+ barrier();
+ if (t < 8u) {
+ int sa0 = s8a[4u * t] + s8a[4u * t + 1u], sa1 = s8a[4u * t + 2u] + s8a[4u * t + 3u];
+ Q.v[base + 64u + t] = (uint(sa0) & 0xffffu) | (uint(sa1) << 16);
+ if (set(p.q32)) {
+ int sb0 = s8b[4u * t] + s8b[4u * t + 1u], sb1 = s8b[4u * t + 2u] + s8b[4u * t + 3u];
+ Q32.v[base + 64u + t] = (uint(sb0) & 0xffffu) | (uint(sb1) << 16);
+ precise float dt =
+ max(max(m8[4u * t], m8[4u * t + 1u]), max(m8[4u * t + 2u], m8[4u * t + 3u])) *
+ 0.007874015718698502;
+ Q32.v[base + 72u + t] = floatBitsToUint(dt);
+ }
+ }
+ if (t == 0u)
+ Q.v[base + 72u] = floatBitsToUint(dd);
+}
diff --git a/src/llm/shaders/q3k_matvec.comp b/src/llm/shaders/q3k_matvec.comp
new file mode 100644
index 0000000..5218aea
--- /dev/null
+++ b/src/llm/shaders/q3k_matvec.comp
@@ -0,0 +1,105 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Q3_K weights times up to NV Q8_K vectors, one row per invocation, as
+// janas_q3k_dot_ref computes it: sixteen groups of 16 three-bit values
+// (-4 to 3), each group's integer dot times its 6-bit scale (sc - 32), the
+// block's exact integer sum in one fma, the same float operation as the
+// CPU: the results agree bit for bit. A value is taken as u - 4, u = its
+// two low bits and its third (0 to 7), and the -4 folded in exactly with
+// the activations' sums of 16 (bsums). A block is 110 bytes (hmask 32, qs
+// 64, scales 12, d 2), so every other one starts 2 bytes off a 4-byte
+// boundary: words are read from the boundary below and realigned, as in
+// q6k_matvec.comp. Weight e = 128 n + 32 j + 16 h + l, group 8 n + 2 j + h:
+// its low bits are bits 2j of qs[32 n + 16 h + l], its third bit j + 4 n of
+// hmask[16 h + l].
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_ballot : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 8;
+layout(constant_id = 1) const uint SG = 8;
+const uint NX = (19u + SG - 1u) / SG;
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+int dp4(uvec4 a, uvec4 b) { return dp(a.x, b.x) + dp(a.y, b.y) + dp(a.z, b.z) + dp(a.w, b.w); }
+uvec4 bc(uvec4 xr[NX], uint k) { return subgroupBroadcast(xr[k / SG], k % SG); }
+
+void main()
+{
+ U1 W = U1(p.w);
+ U4 X = U4(p.x);
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID;
+ uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.y * NV;
+ uint xo[NV];
+ for (uint v = 0; v < NV; v++)
+ xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
+ float acc[NV];
+ for (uint v = 0; v < NV; v++)
+ acc[v] = 0.0;
+ uint off = row * p.nb * 110u; /* bytes */
+ for (uint b = 0; b < p.nb; b++, off += 110u) {
+ /* the block's 28 words, realigned: hmask 0-7, qs 8-23, scales
+ 24-26, d in the low half of 27 */
+ uint base = off >> 2, sh = (off & 3u) * 8u;
+ uint wd[28];
+ for (uint k = 0; k < 28u; k++)
+ wd[k] = W.v[base + k];
+ if (sh != 0u) {
+ for (uint k = 0; k < 27u; k++)
+ wd[k] = (wd[k] >> 16) | (wd[k + 1u] << 16);
+ wd[27] = wd[27] >> 16;
+ }
+ float d = unpackHalf2x16(wd[27] & 0xffffu).x;
+ uint a0 = wd[24], a1 = wd[25], a2 = wd[26];
+ uint o[4] = uint[4]((a0 & 0x0f0f0f0fu) | ((a2 & 0x03030303u) << 4),
+ (a1 & 0x0f0f0f0fu) | (((a2 >> 2) & 0x03030303u) << 4),
+ ((a0 >> 4) & 0x0f0f0f0fu) | (((a2 >> 4) & 0x03030303u) << 4),
+ ((a1 >> 4) & 0x0f0f0f0fu) | (((a2 >> 6) & 0x03030303u) << 4));
+ int sc[16];
+ for (uint i = 0; i < 16u; i++)
+ sc[i] = int((o[i / 4u] >> (8u * (i % 4u))) & 0xffu) - 32;
+ uvec4 u[16];
+ for (uint n = 0; n < 2u; n++)
+ for (uint j = 0; j < 4u; j++)
+ for (uint h = 0; h < 2u; h++) {
+ uint gq = 8u + 8u * n + 4u * h, gh = 4u * h;
+ uint lsh = 2u * j, hsh = j + 4u * n;
+ uint q[4];
+ for (uint i = 0; i < 4u; i++)
+ q[i] = ((wd[gq + i] >> lsh) & 0x03030303u) |
+ (((wd[gh + i] >> hsh) & 0x01010101u) << 2);
+ u[8u * n + 2u * j + h] = uvec4(q[0], q[1], q[2], q[3]);
+ }
+ for (uint v = 0; v < NV; v++) {
+ uvec4 xr[NX];
+ for (uint j = 0; j < NX; j++)
+ xr[j] = X.v[xo[v] + min(j * SG + lane, 19u)];
+ uvec4 bs0 = bc(xr, 16u), bs1 = bc(xr, 17u);
+ uint bw[8] = uint[8](bs0.x, bs0.y, bs0.z, bs0.w, bs1.x, bs1.y, bs1.z, bs1.w);
+ int isum = 0;
+ for (uint g = 0; g < 16u; g++) {
+ int bsum = bitfieldExtract(int(bw[g / 2u]), int(16u * (g % 2u)), 16);
+ isum += sc[g] * (dp4(u[g], bc(xr, g)) - 4 * bsum);
+ }
+ float d8 = uintBitsToFloat(bc(xr, 18u).x);
+ acc[v] = fma(d * d8, float(isum), acc[v]);
+ xo[v] += 20u;
+ }
+ }
+ if (gl_GlobalInvocationID.x < p.rows)
+ for (uint v = 0; v < NV; v++)
+ if (v0 + v < p.nv)
+ Y.v[(v0 + v) * p.ys + row] = acc[v];
+}
diff --git a/src/llm/shaders/q4k_row.comp b/src/llm/shaders/q4k_row.comp
new file mode 100644
index 0000000..4a86f9e
--- /dev/null
+++ b/src/llm/shaders/q4k_row.comp
@@ -0,0 +1,114 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Q4_K weights times one Q8_K vector, a subgroup per row, eight lanes per
+// block: lane j of a cluster of eight reads the block's j-th 16 bytes of
+// nibbles, so that one load of the cluster is 128 contiguous bytes, and
+// works out their part of the block's integer sums (sub-block j/2's two
+// halves, and one of the eight minimum terms); the parts are added exactly
+// (integers, a clustered add), and one lane chains the block's fmas in the
+// CPU's order (janas_q4k_dot_ref): the result is the CPU's bit for bit. A
+// subgroup of SG lanes takes SG / 8 blocks at a time. Up to NV vectors
+// (the block's, or a speculative pass's drafts): the weights loaded once. For single vectors,
+// where the products are bound by memory: q4k_matvec.comp reads a whole
+// row per invocation, rows far apart at once, and draws a fraction of the
+// bandwidth.
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_clustered : require
+#extension GL_KHR_shader_subgroup_shuffle : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 1;
+layout(constant_id = 1) const uint SG = 8;
+layout(constant_id = 2) const uint TILE = 0; /* gpu.h JANAS_TILE, or 0 */
+const uint RPW = 64u / SG; /* rows a workgroup: a subgroup each */
+const uint G = SG / 8u; /* blocks a subgroup takes a step */
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+int dp4(uvec4 a, uvec4 b) { return dp(a.x, b.x) + dp(a.y, b.y) + dp(a.z, b.z) + dp(a.w, b.w); }
+
+/* This lane's part of the exact integer sums of a block (header hd, its
+ 16 bytes q of nibbles) against the vector whose block starts at xo:
+ added across its cluster of eight, with its two scale products. */
+void blk(U4 X, uvec4 hd, uvec4 q, uint xo, uint j, out float sa, out float sb,
+ out int isum, out int imin)
+{
+ /* the scale and minimum of sub-blocks 2c and 2c + 1, c = j / 2 */
+ uint c = j / 2u, s0 = 2u * c, s1 = s0 + 1u;
+ int sc0 = s0 < 4u ? int(bitfieldExtract(hd.y, int(8u * s0), 6))
+ : int(bitfieldExtract(hd.w, int(8u * (s0 - 4u)), 4) |
+ (bitfieldExtract(hd.y, int(8u * (s0 - 4u) + 6u), 2) << 4));
+ int sc1 = s1 < 4u ? int(bitfieldExtract(hd.y, int(8u * s1), 6))
+ : int(bitfieldExtract(hd.w, int(8u * (s1 - 4u)), 4) |
+ (bitfieldExtract(hd.y, int(8u * (s1 - 4u) + 6u), 2) << 4));
+ uint half_ = j & 1u;
+ isum = dp4(q & 0x0f0f0f0fu, X.v[xo + 4u * c + half_]) * sc0 +
+ dp4((q >> 4) & 0x0f0f0f0fu, X.v[xo + 4u * c + 2u + half_]) * sc1;
+ /* minimum term j: mn[j] times the activations' sum of sub-block j */
+ int mnj = j < 4u ? int(bitfieldExtract(hd.z, int(8u * j), 6))
+ : int(bitfieldExtract(hd.w, int(8u * (j - 4u) + 4u), 4) |
+ (bitfieldExtract(hd.z, int(8u * (j - 4u) + 6u), 2) << 4));
+ uvec4 bs = X.v[xo + 16u + j / 4u];
+ uint bw = j % 4u == 0u ? bs.x : j % 4u == 1u ? bs.y : j % 4u == 2u ? bs.z : bs.w;
+ imin = mnj * (bitfieldExtract(int(bw), 0, 16) + bitfieldExtract(int(bw), 16, 16));
+ isum = subgroupClusteredAdd(isum, 8u);
+ imin = subgroupClusteredAdd(imin, 8u);
+ float d8 = uintBitsToFloat(X.v[xo + 18u].x);
+ vec2 dd = unpackHalf2x16(hd.x);
+ sa = dd.x * d8;
+ sb = dd.y * d8;
+}
+
+void main()
+{
+ U4 W = U4(p.w), X = U4(p.x);
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID, sg = gl_SubgroupID;
+ uint j = lane % 8u, g = lane / 8u;
+ uint row = gl_WorkGroupID.x * RPW + sg;
+ bool live = row < p.rows;
+ uint r = min(row, p.rows - 1u);
+ /* NV vectors from v0 (workgroup y) on, of p.nv, xs blocks apart: the
+ weights read once for all */
+ uint v0 = gl_WorkGroupID.y * NV;
+ float acc[NV], accm[NV];
+ for (uint v = 0; v < NV; v++) {
+ acc[v] = 0.0;
+ accm[v] = 0.0;
+ }
+ /* blocks b0 .. b0 + G - 1 a step, a cluster each, chained in that order */
+ for (uint b0 = 0; b0 < p.nb; b0 += G) {
+ uint bb = min(b0 + g, p.nb - 1u);
+ uint wo = (TILE == 0u ? r * p.nb + bb : ((r / TILE) * p.nb + bb) * TILE + r % TILE) * 9u;
+ uvec4 hd = W.v[wo], q = W.v[wo + 1u + j];
+ for (uint v = 0; v < NV; v++) {
+ uint xo = (min(v0 + v, p.nv - 1u) * p.xs + bb) * 20u;
+ float sa, sb;
+ int si, sj;
+ blk(X, hd, q, xo, j, sa, sb, si, sj);
+ for (uint k = 0; k < G; k++) {
+ float ak = G == 1u ? sa : subgroupShuffle(sa, 8u * k);
+ float bk = G == 1u ? sb : subgroupShuffle(sb, 8u * k);
+ int ik = G == 1u ? si : subgroupShuffle(si, 8u * k);
+ int jk = G == 1u ? sj : subgroupShuffle(sj, 8u * k);
+ if (lane == 0u && b0 + k < p.nb) {
+ acc[v] = fma(ak, float(ik), acc[v]);
+ accm[v] = fma(bk, float(jk), accm[v]);
+ }
+ }
+ }
+ }
+ if (lane == 0u && live)
+ for (uint v = 0; v < NV; v++)
+ if (v0 + v < p.nv)
+ Y.v[(v0 + v) * p.ys + row] = acc[v] - accm[v];
+}
diff --git a/src/llm/shaders/q6k_row.comp b/src/llm/shaders/q6k_row.comp
new file mode 100644
index 0000000..eeeb0c8
--- /dev/null
+++ b/src/llm/shaders/q6k_row.comp
@@ -0,0 +1,117 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Q6_K weights times one Q8_K vector, a subgroup per row, eight lanes per
+// block, as q4k_row.comp: lane j = 4 n + part takes the 32 values of half
+// n, quarter part (their low bits in ql, high bits in qh, the scales of its
+// two groups of 16) and the j-th term of the -32 offset (scale pair j times
+// its activations' sums); the parts are added exactly (integers, a
+// clustered add) and one lane chains the blocks' fmas in the CPU's order
+// (janas_q6k_dot_ref): the CPU's result bit for bit. A block is 210 bytes,
+// so every other one starts 2 bytes off a 4-byte boundary: each lane reads
+// its words from the boundary below and realigns them.
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_clustered : require
+#extension GL_KHR_shader_subgroup_shuffle : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 1;
+layout(constant_id = 1) const uint SG = 8;
+const uint RPW = 64u / SG; /* rows a workgroup: a subgroup each */
+const uint G = SG / 8u; /* blocks a subgroup takes a step */
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+
+/* word i of the block whose first byte is off, realigned */
+uint wat(U1 W, uint off, uint i)
+{
+ uint base = off >> 2;
+ return (off & 3u) != 0u ? (W.v[base + i] >> 16) | (W.v[base + i + 1u] << 16) : W.v[base + i];
+}
+
+void main()
+{
+ U1 W = U1(p.w);
+ U4 X = U4(p.x);
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID, sg = gl_SubgroupID;
+ uint j = lane % 8u, g = lane / 8u;
+ uint row = gl_WorkGroupID.x * RPW + sg;
+ bool live = row < p.rows;
+ uint r = min(row, p.rows - 1u);
+ uint n = j / 4u, part = j % 4u;
+ uint qlw = 16u * n + (part & 1u) * 8u, qhw = 32u + 8u * n;
+ uint lsh = (part >> 1) * 4u, hsh = part * 2u;
+ uint gi = 8u * n + 2u * part; /* its first group of 16 */
+ /* NV vectors from v0 (workgroup y) on, of p.nv, xs blocks apart: the
+ weights read once for all */
+ uint v0 = gl_WorkGroupID.y * NV;
+ float acc[NV];
+ for (uint v = 0; v < NV; v++)
+ acc[v] = 0.0;
+ for (uint b0 = 0; b0 < p.nb; b0 += G) {
+ uint b = b0 + g;
+ uint bb = min(b, p.nb - 1u);
+ uint off = (r * p.nb + bb) * 210u;
+ uint scw0 = wat(W, off, 48u + gi / 4u);
+ int sca = bitfieldExtract(int(scw0), int(8u * (gi % 4u)), 8);
+ int scb = bitfieldExtract(int(scw0), int(8u * (gi % 4u + 1u)), 8);
+ /* its 8 words of ql and of qh, each from 9 raw words */
+ uint rl[9], rh[9];
+ uint base = off >> 2;
+ for (uint k = 0; k < 9u; k++) {
+ rl[k] = W.v[base + qlw + k];
+ rh[k] = W.v[base + qhw + k];
+ }
+ bool odd = (off & 3u) != 0u;
+ uint qv[8];
+ for (uint k = 0; k < 8u; k++) {
+ uint l = odd ? (rl[k] >> 16) | (rl[k + 1u] << 16) : rl[k];
+ uint h = odd ? (rh[k] >> 16) | (rh[k + 1u] << 16) : rh[k];
+ qv[k] = ((l >> lsh) & 0x0f0f0f0fu) | (((h >> hsh) & 0x03030303u) << 4);
+ }
+ /* offset term j: scales 2j and 2j + 1 times their activation sums */
+ uint scw = wat(W, off, 48u + j / 2u);
+ int s0 = bitfieldExtract(int(scw), int(16u * (j % 2u)), 8);
+ int s1 = bitfieldExtract(int(scw), int(16u * (j % 2u) + 8u), 8);
+ float d = unpackHalf2x16(wat(W, off, 52u) & 0xffffu).x;
+ for (uint v = 0; v < NV; v++) {
+ uint xo = (min(v0 + v, p.nv - 1u) * p.xs + bb) * 20u;
+ uvec4 a0 = X.v[xo + gi], a1 = X.v[xo + gi + 1u];
+ uint a[8] = uint[8](a0.x, a0.y, a0.z, a0.w, a1.x, a1.y, a1.z, a1.w);
+ int dot0 = 0, dot1 = 0;
+ for (uint k = 0; k < 8u; k++) {
+ if (k < 4u)
+ dot0 += dp(qv[k], a[k]);
+ else
+ dot1 += dp(qv[k], a[k]);
+ }
+ int isum = sca * dot0 + scb * dot1;
+ uvec4 bs = X.v[xo + 16u + j / 4u];
+ uint bw = j % 4u == 0u ? bs.x : j % 4u == 1u ? bs.y : j % 4u == 2u ? bs.z : bs.w;
+ isum -= 32 * (s0 * bitfieldExtract(int(bw), 0, 16) + s1 * bitfieldExtract(int(bw), 16, 16));
+ isum = subgroupClusteredAdd(isum, 8u);
+ float sa = d * uintBitsToFloat(X.v[xo + 18u].x);
+ for (uint k = 0; k < G; k++) {
+ float ak = G == 1u ? sa : subgroupShuffle(sa, 8u * k);
+ int ik = G == 1u ? isum : subgroupShuffle(isum, 8u * k);
+ if (lane == 0u && b0 + k < p.nb)
+ acc[v] = fma(ak, float(ik), acc[v]);
+ }
+ }
+ }
+ if (lane == 0u && live)
+ for (uint v = 0; v < NV; v++)
+ if (v0 + v < p.nv)
+ Y.v[(v0 + v) * p.ys + row] = acc[v];
+}
diff --git a/src/llm/shaders/q6ka_row.comp b/src/llm/shaders/q6ka_row.comp
new file mode 100644
index 0000000..8d653f6
--- /dev/null
+++ b/src/llm/shaders/q6ka_row.comp
@@ -0,0 +1,104 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Q6_K in the GPU's aligned copy (JANAS_Q6_K_A, gpu.h: each block padded
+// from 210 to 224 bytes - ql 128, qh 64, scales 16, d and padding 16 - so
+// that every part starts on 16 bytes) times one Q8_K vector: as
+// q6k_row.comp, a subgroup per row and eight lanes per block, lane j = 4n +
+// 2h + kk taking positions 16kk .. 16kk + 15 of half n in quarters h and h
+// + 2, so that it reads one uvec4 of ql and one of qh, whole, with nothing
+// to realign. The same integers and the same fmas in the CPU's order: the
+// CPU's result for the Q6_K block it was copied from, bit for bit (and for
+// a Q6_K_P block with its three planes, which is the Q6_K one).
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_clustered : require
+#extension GL_KHR_shader_subgroup_shuffle : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 1;
+layout(constant_id = 1) const uint SG = 8;
+layout(constant_id = 2) const uint TILE = 0; /* gpu.h JANAS_TILE, or 0 */
+const uint RPW = 64u / SG; /* rows a workgroup: a subgroup each */
+const uint G = SG / 8u; /* blocks a subgroup takes a step */
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+
+uint comp(uvec4 v, uint i) { return i == 0u ? v.x : i == 1u ? v.y : i == 2u ? v.z : v.w; }
+
+void main()
+{
+ U4 W = U4(p.w), X = U4(p.x);
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID, sg = gl_SubgroupID;
+ uint j = lane % 8u, g = lane / 8u;
+ uint row = gl_WorkGroupID.x * RPW + sg;
+ bool live = row < p.rows;
+ uint r = min(row, p.rows - 1u);
+ /* lane j = 4n + 2h + kk: half n, positions 16kk .. 16kk + 15 of quarters
+ h (low nibbles) and h + 2 (high): one uvec4 of ql and one of qh */
+ uint n = j / 4u, h = (j / 2u) % 2u, kk = j % 2u;
+ uint qlv = 4u * n + 2u * h + kk, qhv = 8u + 2u * n + kk;
+ /* NV vectors from v0 (workgroup y) on, of p.nv, xs blocks apart: the
+ weights read once for all */
+ uint v0 = gl_WorkGroupID.y * NV;
+ float acc[NV];
+ for (uint v = 0; v < NV; v++)
+ acc[v] = 0.0;
+ for (uint b0 = 0; b0 < p.nb; b0 += G) {
+ uint bb = min(b0 + g, p.nb - 1u);
+ uint wo = (TILE == 0u ? r * p.nb + bb : ((r / TILE) * p.nb + bb) * TILE + r % TILE) * 14u;
+ uvec4 l4 = W.v[wo + qlv], h4 = W.v[wo + qhv], sc4 = W.v[wo + 12u];
+ uint q[2][4];
+ int scg[2];
+ for (uint e = 0; e < 2u; e++) {
+ uint part = h + 2u * e, lsh = e * 4u, hsh = part * 2u;
+ for (uint k = 0; k < 4u; k++)
+ q[e][k] = ((comp(l4, k) >> lsh) & 0x0f0f0f0fu) |
+ (((comp(h4, k) >> hsh) & 0x03030303u) << 4);
+ uint gi = 8u * n + 2u * part + kk; /* its group of 16 */
+ scg[e] = bitfieldExtract(int(comp(sc4, gi / 4u)), int(8u * (gi % 4u)), 8);
+ }
+ /* offset term j: scales 2j and 2j + 1 times their activation sums */
+ uint scw = comp(sc4, j / 2u);
+ int s0 = bitfieldExtract(int(scw), int(16u * (j % 2u)), 8);
+ int s1 = bitfieldExtract(int(scw), int(16u * (j % 2u) + 8u), 8);
+ float d = unpackHalf2x16(W.v[wo + 13u].x & 0xffffu).x;
+ for (uint v = 0; v < NV; v++) {
+ uint xo = (min(v0 + v, p.nv - 1u) * p.xs + bb) * 20u;
+ int isum = 0;
+ for (uint e = 0; e < 2u; e++) {
+ uint part = h + 2u * e;
+ uvec4 a4 = X.v[xo + 8u * n + 2u * part + kk];
+ int dot = 0;
+ for (uint k = 0; k < 4u; k++)
+ dot += dp(q[e][k], comp(a4, k));
+ isum += scg[e] * dot;
+ }
+ uint bw = comp(X.v[xo + 16u + j / 4u], j % 4u);
+ isum -= 32 * (s0 * bitfieldExtract(int(bw), 0, 16) + s1 * bitfieldExtract(int(bw), 16, 16));
+ isum = subgroupClusteredAdd(isum, 8u);
+ /* d and the activations' scale: lane 0 alone needs them */
+ float sa = 0.0;
+ if (j == 0u)
+ sa = d * uintBitsToFloat(X.v[xo + 18u].x);
+ for (uint k = 0; k < G; k++) {
+ float ak = G == 1u ? sa : subgroupShuffle(sa, 8u * k);
+ int ik = G == 1u ? isum : subgroupShuffle(isum, 8u * k);
+ if (lane == 0u && b0 + k < p.nb)
+ acc[v] = fma(ak, float(ik), acc[v]);
+ }
+ }
+ }
+ if (lane == 0u && live)
+ for (uint v = 0; v < NV; v++)
+ if (v0 + v < p.nv)
+ Y.v[(v0 + v) * p.ys + row] = acc[v];
+}
diff --git a/src/llm/shaders/q6kp_row.comp b/src/llm/shaders/q6kp_row.comp
new file mode 100644
index 0000000..f2b730f
--- /dev/null
+++ b/src/llm/shaders/q6kp_row.comp
@@ -0,0 +1,134 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Q6_K in bit planes (JANAS_Q6_K_P) times one Q8_K vector, a subgroup per
+// row, eight lanes per block, as q6k_row.comp: lane j = 4 n + part takes
+// the 32 values of half n, quarter part - two bits from each plane present
+// (the high plane in the row's 82-byte blocks, the bare planes p1 and p0
+// in arrays of their own, 64 bytes a block) - and the j-th pair of the
+// block's scaled activation sums; both integer sums are added exactly
+// across the eight lanes, and one lane forms sumi x 2^shk - c x off and
+// chains the fmas in the CPU's order (janas_q6kp_dot_ref): the CPU's result
+// bit for bit, at the three levels. The 82-byte blocks start 2 bytes off a
+// 4-byte boundary every other time: words are realigned.
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_clustered : require
+#extension GL_KHR_shader_subgroup_shuffle : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 1;
+layout(constant_id = 1) const uint SG = 8;
+const uint RPW = 64u / SG; /* rows a workgroup: a subgroup each */
+const uint G = SG / 8u; /* blocks a subgroup takes a step */
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys, level; uvec2 p1, p0; } p;
+
+
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+
+uint wat(U1 W, uint off, uint i)
+{
+ uint base = off >> 2;
+ return (off & 3u) != 0u ? (W.v[base + i] >> 16) | (W.v[base + i + 1u] << 16) : W.v[base + i];
+}
+
+void main()
+{
+ U1 W = U1(p.w);
+ U4 P1Q = U4(p.p1), P0Q = U4(p.p0);
+ U4 X = U4(p.x);
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID, sg = gl_SubgroupID;
+ uint j = lane % 8u, g = lane / 8u;
+ uint row = gl_WorkGroupID.x * RPW + sg;
+ bool live = row < p.rows;
+ uint r = min(row, p.rows - 1u);
+ uint shk = p.level == 3u ? 1u : p.level == 2u ? 3u : 5u;
+ int c = p.level == 3u ? 64 : p.level == 2u ? 61 : 49;
+ uint n = j / 4u, part = j % 4u, hsh = part * 2u;
+ uint gi = 8u * n + 2u * part;
+ /* NV vectors from v0 (workgroup y) on, of p.nv, xs blocks apart: the
+ weights read once for all */
+ uint v0 = gl_WorkGroupID.y * NV;
+ float acc[NV];
+ for (uint v = 0; v < NV; v++)
+ acc[v] = 0.0;
+ for (uint b0 = 0; b0 < p.nb; b0 += G) {
+ uint b = b0 + g;
+ uint bb = min(b, p.nb - 1u);
+ uint blk = r * p.nb + bb;
+ uint off = blk * 82u, pw = blk * 16u;
+ uint scw0 = wat(W, off, 16u + gi / 4u);
+ int sca = bitfieldExtract(int(scw0), int(8u * (gi % 4u)), 8);
+ int scb = bitfieldExtract(int(scw0), int(8u * (gi % 4u + 1u)), 8);
+ /* the high plane's 8 words of this half, from 9 raw words */
+ uint raw[9], hw[8];
+ uint base = (off >> 2) + 8u * n;
+ for (uint k = 0; k < 9u; k++)
+ raw[k] = W.v[base + k];
+ for (uint k = 0; k < 8u; k++)
+ hw[k] = (off & 3u) != 0u ? (raw[k] >> 16) | (raw[k + 1u] << 16) : raw[k];
+ /* the bare planes' words, two uvec4 each (64-byte aligned) */
+ uvec4 p1a = uvec4(0), p1b = uvec4(0), p0a = uvec4(0), p0b = uvec4(0);
+ if (p.level >= 2u) {
+ p1a = P1Q.v[pw / 4u + 2u * n];
+ p1b = P1Q.v[pw / 4u + 2u * n + 1u];
+ }
+ if (p.level >= 3u) {
+ p0a = P0Q.v[pw / 4u + 2u * n];
+ p0b = P0Q.v[pw / 4u + 2u * n + 1u];
+ }
+ uint w1[8] = uint[8](p1a.x, p1a.y, p1a.z, p1a.w, p1b.x, p1b.y, p1b.z, p1b.w);
+ uint w0[8] = uint[8](p0a.x, p0a.y, p0a.z, p0a.w, p0b.x, p0b.y, p0b.z, p0b.w);
+ uint qv[8];
+ for (uint k = 0; k < 8u; k++) {
+ uint q = (hw[k] >> hsh) & 0x03030303u;
+ if (p.level >= 2u)
+ q = (q << 2) | ((w1[k] >> hsh) & 0x03030303u);
+ if (p.level >= 3u)
+ q = (q << 2) | ((w0[k] >> hsh) & 0x03030303u);
+ qv[k] = q;
+ }
+ uint scw = wat(W, off, 16u + j / 2u);
+ int s0 = bitfieldExtract(int(scw), int(16u * (j % 2u)), 8);
+ int s1 = bitfieldExtract(int(scw), int(16u * (j % 2u) + 8u), 8);
+ float d = unpackHalf2x16(wat(W, off, 20u) & 0xffffu).x;
+ for (uint v = 0; v < NV; v++) {
+ uint xo = (min(v0 + v, p.nv - 1u) * p.xs + bb) * 20u;
+ uvec4 a0 = X.v[xo + gi], a1 = X.v[xo + gi + 1u];
+ uint a[8] = uint[8](a0.x, a0.y, a0.z, a0.w, a1.x, a1.y, a1.z, a1.w);
+ int dot0 = 0, dot1 = 0;
+ for (uint k = 0; k < 8u; k++) {
+ if (k < 4u)
+ dot0 += dp(qv[k], a[k]);
+ else
+ dot1 += dp(qv[k], a[k]);
+ }
+ int isum = sca * dot0 + scb * dot1;
+ uvec4 bs = X.v[xo + 16u + j / 4u];
+ uint bw = j % 4u == 0u ? bs.x : j % 4u == 1u ? bs.y : j % 4u == 2u ? bs.z : bs.w;
+ int boff = s0 * bitfieldExtract(int(bw), 0, 16) + s1 * bitfieldExtract(int(bw), 16, 16);
+ isum = subgroupClusteredAdd(isum, 8u);
+ boff = subgroupClusteredAdd(boff, 8u);
+ float sa = d * 0.5 * uintBitsToFloat(X.v[xo + 18u].x);
+ for (uint k = 0; k < G; k++) {
+ float ak = G == 1u ? sa : subgroupShuffle(sa, 8u * k);
+ int ik = G == 1u ? isum : subgroupShuffle(isum, 8u * k);
+ int ok = G == 1u ? boff : subgroupShuffle(boff, 8u * k);
+ if (lane == 0u && b0 + k < p.nb)
+ acc[v] = fma(ak, float(ik * (1 << shk) - c * ok), acc[v]);
+ }
+ }
+ }
+ if (lane == 0u && live)
+ for (uint v = 0; v < NV; v++)
+ if (v0 + v < p.nv)
+ Y.v[(v0 + v) * p.ys + row] = acc[v];
+}
diff --git a/src/llm/shaders/q8_0_matvec.comp b/src/llm/shaders/q8_0_matvec.comp
new file mode 100644
index 0000000..78f8b31
--- /dev/null
+++ b/src/llm/shaders/q8_0_matvec.comp
@@ -0,0 +1,92 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Q8_0 weights (blocks of 32: an fp16 scale and 32 int8) times up to NV
+// vectors, one row per invocation, as janas_q8_0_dot_ref computes it: the
+// activations in blocks of 32 with a scale each (qs32/d32 of the Q8_K
+// block), each weight block's integer dot in one fma into the accumulator
+// of its position in the group of eight, the eight added at the end as
+// janas_hsum8 does, ((a0+a4)+(a2+a6)) + ((a1+a5)+(a3+a7)): the same float
+// operations as the CPU, so the results agree bit for bit. The activations
+// come in the 32-block layout of convert_x (20 uvec4 a Q8_K block: qs32 in
+// 16, bsums32 in 2, d32 in 2), shared across the subgroup as in
+// q4k_matvec.comp. A weight block is 34 bytes, so every other one starts 2
+// bytes off a 4-byte boundary: its words are realigned.
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_ballot : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 8;
+layout(constant_id = 1) const uint SG = 8;
+const uint NX = (20u + SG - 1u) / SG;
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+int dp4(uvec4 a, uvec4 b) { return dp(a.x, b.x) + dp(a.y, b.y) + dp(a.z, b.z) + dp(a.w, b.w); }
+uvec4 bc(uvec4 xr[NX], uint k) { return subgroupBroadcast(xr[k / SG], k % SG); }
+
+void main()
+{
+ U1 W = U1(p.w);
+ U4 X = U4(p.x);
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID;
+ uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.y * NV;
+ uint xo[NV];
+ for (uint v = 0; v < NV; v++)
+ xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
+ float acc[NV][8];
+ for (uint v = 0; v < NV; v++)
+ for (uint k = 0; k < 8u; k++)
+ acc[v][k] = 0.0;
+ uint gw = row * p.nb * 68u; /* words: a group of eight blocks is 272 bytes */
+ for (uint b = 0; b < p.nb; b++, gw += 68u) {
+ uint wg[68];
+ for (uint i = 0; i < 68u; i++)
+ wg[i] = W.v[gw + i];
+ float d[8];
+ uvec4 q[8][2];
+ for (uint k = 0; k < 8u; k++) {
+ uint B = 34u * k; /* the block's first byte */
+ uint dw = wg[B >> 2];
+ d[k] = unpackHalf2x16((B & 2u) != 0u ? dw >> 16 : dw & 0xffffu).x;
+ uint qb = B + 2u, wi = qb >> 2;
+ uint qw[8];
+ for (uint i = 0; i < 8u; i++)
+ qw[i] = (qb & 2u) != 0u ? (wg[wi + i] >> 16) | (wg[wi + i + 1u] << 16)
+ : wg[wi + i];
+ q[k][0] = uvec4(qw[0], qw[1], qw[2], qw[3]);
+ q[k][1] = uvec4(qw[4], qw[5], qw[6], qw[7]);
+ }
+ for (uint v = 0; v < NV; v++) {
+ uvec4 xr[NX];
+ for (uint j = 0; j < NX; j++)
+ xr[j] = X.v[xo[v] + min(j * SG + lane, 19u)];
+ uvec4 s0 = bc(xr, 18u), s1 = bc(xr, 19u);
+ float d32[8] = float[8](uintBitsToFloat(s0.x), uintBitsToFloat(s0.y),
+ uintBitsToFloat(s0.z), uintBitsToFloat(s0.w),
+ uintBitsToFloat(s1.x), uintBitsToFloat(s1.y),
+ uintBitsToFloat(s1.z), uintBitsToFloat(s1.w));
+ for (uint k = 0; k < 8u; k++) {
+ int dot = dp4(q[k][0], bc(xr, 2u * k)) + dp4(q[k][1], bc(xr, 2u * k + 1u));
+ acc[v][k] = fma(d[k] * d32[k], float(dot), acc[v][k]);
+ }
+ xo[v] += 20u;
+ }
+ }
+ if (gl_GlobalInvocationID.x < p.rows)
+ for (uint v = 0; v < NV; v++)
+ if (v0 + v < p.nv)
+ Y.v[(v0 + v) * p.ys + row] =
+ ((acc[v][0] + acc[v][4]) + (acc[v][2] + acc[v][6])) +
+ ((acc[v][1] + acc[v][5]) + (acc[v][3] + acc[v][7]));
+}
diff --git a/src/llm/shaders/qk_rope.comp b/src/llm/shaders/qk_rope.comp
new file mode 100644
index 0000000..7b2a295
--- /dev/null
+++ b/src/llm/shaders/qk_rope.comp
@@ -0,0 +1,163 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// After the q, k, v products of one token (qkv: q, then k at qd, then v at
+// qd + kvd floats): each head of q normalized (q_norm) and turned (NeoX
+// RoPE over its first n_rot dimensions, pairs i and i + n_rot/2, the
+// token's tables cs and sn), in place; each head of k normalized (k_norm)
+// and turned, then k and v put in the layer's KV cache at eight bits with
+// a scale each (the largest of the head's numbers becomes 127), row `row`
+// of the head's positions, as model_attn.c's qkv_item does. Each head of q
+// is left at eight bits too, for attn_decode.comp: its hd / 4 words of four
+// bytes, then its scale (the largest magnitude over 127), at the start of
+// its own hd floats. One workgroup per head: the n_head of q, then the
+// n_kv of k (with v).
+#extension GL_EXT_buffer_reference : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_arithmetic : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 128) in;
+
+layout(buffer_reference, std430, buffer_reference_align = 4) buffer F { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer U { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer R0 { uint v[]; };
+
+// qkv; q_norm and k_norm weights (hd each); rope: cos then sin, n_rot/2
+// each; kc, vc: the layer's caches (n_kv x cap x hd bytes); ks, vs: their
+// scales (n_kv x cap floats)
+layout(push_constant) uniform P {
+ uvec2 qkv, qn, kn, rope, kc, vc, ks, vs;
+ uint n_head, n_kv, hd, n_rot, cap, qs; /* qs: floats from a token's qkv to the next's */
+ float eps;
+ uvec2 pos; /* the token's position, read at run time: row pos */
+} p;
+
+shared float sv[512], sw[512];
+shared int qk[512], qv[512];
+
+/* A workgroup's sum and maximum: each subgroup's in one operation, then
+ the subgroups' results in a fixed order - two barriers, not one per
+ level of a tree. */
+shared float sg_part[64];
+
+float wg_sum(float s)
+{
+ float r = subgroupAdd(s);
+ if (subgroupElect())
+ sg_part[gl_SubgroupID] = r;
+ barrier();
+ float tot = sg_part[0];
+ for (uint i = 1u; i < gl_NumSubgroups; i++)
+ tot += sg_part[i];
+ barrier();
+ return tot;
+}
+
+float wg_max(float s)
+{
+ float r = subgroupMax(s);
+ if (subgroupElect())
+ sg_part[gl_SubgroupID] = r;
+ barrier();
+ float m = sg_part[0];
+ for (uint i = 1u; i < gl_NumSubgroups; i++)
+ m = max(m, sg_part[i]);
+ barrier();
+ return m;
+}
+
+float head_sum(float s) { return wg_sum(s); }
+float head_max(float s) { return wg_max(s); }
+
+void main()
+{
+ uint t = gl_LocalInvocationID.x, h = gl_WorkGroupID.x, hd = p.hd;
+ F QKV = F(p.qkv), QN = F(p.qn), KN = F(p.kn), R = F(p.rope);
+ bool isq = h < p.n_head;
+ uint kh = isq ? 0u : h - p.n_head;
+ uint qd = p.n_head * hd, kvd = p.n_kv * hd;
+ /* token j of a block (workgroup y): its qkv, its RoPE tables (cos then
+ sin, n_rot / 2 each, n_rot floats a token), its row pos + j */
+ uint j = gl_WorkGroupID.y, qo = j * p.qs, ro = j * p.n_rot;
+ uint o = qo + (isq ? h * hd : qd + kh * hd);
+ float ss = 0.0;
+ for (uint i = t; i < hd; i += 128u) {
+ float v = QKV.v[o + i];
+ sv[i] = v;
+ ss += v * v;
+ }
+ ss = head_sum(ss);
+ precise float scale = 1.0 / sqrt(ss / float(hd) + p.eps);
+ for (uint i = t; i < hd; i += 128u) {
+ precise float v = sv[i] * scale;
+ sv[i] = v * (isq ? QN.v[i] : KN.v[i]);
+ }
+ barrier();
+ uint half_ = p.n_rot / 2u;
+ for (uint i = t; i < hd; i += 128u) {
+ float r = sv[i];
+ if (i < half_) {
+ float a = sv[i], b = sv[i + half_];
+ r = a * R.v[ro + i] - b * R.v[ro + half_ + i];
+ } else if (i < p.n_rot) {
+ float a = sv[i - half_], b = sv[i];
+ r = a * R.v[ro + half_ + i - half_] + b * R.v[ro + i - half_];
+ }
+ sw[i] = r;
+ }
+ barrier();
+ if (isq) {
+ /* the scores' integer dot products take q at eight bits: the
+ largest magnitude becomes 127, q / (m / 127) rounded to even */
+ float mq = 0.0;
+ for (uint i = t; i < hd; i += 128u)
+ mq = max(mq, abs(sw[i]));
+ mq = head_max(mq);
+ float d = mq / 127.0, id = d > 0.0 ? 1.0 / d : 0.0;
+ U QW = U(p.qkv);
+ for (uint w = t; w < hd / 4u; w += 128u) {
+ uint wq = 0u;
+ for (uint e = 0; e < 4u; e++) {
+ int q = int(clamp(roundEven(sw[4u * w + e] * id), -127.0, 127.0));
+ wq |= (uint(q) & 0xffu) << (8u * e);
+ }
+ QW.v[o + w] = wq;
+ }
+ if (t == 0u)
+ QKV.v[o + hd / 4u] = d;
+ return;
+ }
+ /* k and v of this KV head at eight bits, each with its scale */
+ uint ov = qo + qd + kvd + kh * hd;
+ float mk = 0.0, mv = 0.0;
+ for (uint i = t; i < hd; i += 128u) {
+ sv[i] = QKV.v[ov + i];
+ mk = max(mk, abs(sw[i]));
+ mv = max(mv, abs(sv[i]));
+ }
+ mk = head_max(mk);
+ mv = head_max(mv);
+ float ik = mk > 0.0 ? 127.0 / mk : 0.0, iv = mv > 0.0 ? 127.0 / mv : 0.0;
+ for (uint i = t; i < hd; i += 128u) {
+ qk[i] = int(roundEven(sw[i] * ik));
+ qv[i] = int(roundEven(sv[i] * iv));
+ }
+ barrier();
+ uint row = R0(p.pos).v[0] + j;
+ uint at = (kh * p.cap + row) * hd; /* bytes; hd is a multiple of 4 */
+ U KC = U(p.kc), VC = U(p.vc);
+ for (uint w = t; w < hd / 4u; w += 128u) {
+ KC.v[at / 4u + w] = (uint(qk[4u * w]) & 0xffu) | ((uint(qk[4u * w + 1u]) & 0xffu) << 8) |
+ ((uint(qk[4u * w + 2u]) & 0xffu) << 16) |
+ ((uint(qk[4u * w + 3u]) & 0xffu) << 24);
+ VC.v[at / 4u + w] = (uint(qv[4u * w]) & 0xffu) | ((uint(qv[4u * w + 1u]) & 0xffu) << 8) |
+ ((uint(qv[4u * w + 2u]) & 0xffu) << 16) |
+ ((uint(qv[4u * w + 3u]) & 0xffu) << 24);
+ }
+ if (t == 0u) {
+ F KS = F(p.ks), VS = F(p.vs);
+ KS.v[kh * p.cap + row] = mk / 127.0;
+ VS.v[kh * p.cap + row] = mv / 127.0;
+ }
+}
diff --git a/tests/bench_long.c b/tests/bench_long.c
index e918984..71565c4 100644
--- a/tests/bench_long.c
+++ b/tests/bench_long.c
@@ -14,12 +14,24 @@
* this file has used so far. With it, the first threads CPUs of the layout
* the engine itself picks (P cores first, then E), which is what janas-chat
* runs on.
+ *
+ * The disk the model is on: its time busy (io_ticks of /proc/diskstats)
+ * during the prefill and the decoding, beside the time waited. With
+ * JANAS_WARM=1 the machine's profile is preloaded, as janas-chat does; with
+ * BENCH_READY=1 as well, the prompt waits until that preload is done.
+ * BENCH_SAVE=file writes the prompt and the generated tokens (int32), for
+ * tracing the same sequence again. The experts' bits and count in use are
+ * printed: with little memory the engine lowers them itself (a different
+ * model); BENCH_EXACT=1 keeps all the bits and the model's own count.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
+#include <sys/stat.h>
+#include <sys/sysmacros.h>
#include <time.h>
+#include <unistd.h>
#include "common/pool.h"
#include "common/sysinfo.h"
@@ -32,6 +44,36 @@ static double now(void)
return ts.tv_sec + ts.tv_nsec * 1e-9;
}
+/* Milliseconds the block device (partition) of path has been busy, from
+ /proc/diskstats (io_ticks), or -1. */
+static long long disk_busy_ms(const char *path)
+{
+ struct stat st;
+ if (stat(path, &st) != 0)
+ return -1;
+ FILE *f = fopen("/proc/diskstats", "r");
+ if (!f)
+ return -1;
+ char line[512];
+ long long busy = -1;
+ while (fgets(line, sizeof(line), f)) {
+ unsigned ma, mi;
+ char name[64];
+ unsigned long long v[10];
+ if (sscanf(line,
+ "%u %u %63s %llu %llu %llu %llu %llu %llu %llu %llu "
+ "%llu %llu",
+ &ma, &mi, name, &v[0], &v[1], &v[2], &v[3], &v[4], &v[5],
+ &v[6], &v[7], &v[8], &v[9]) == 13 &&
+ ma == major(st.st_dev) && mi == minor(st.st_dev)) {
+ busy = (long long)v[9]; /* the tenth field after the name */
+ break;
+ }
+ }
+ fclose(f);
+ return busy;
+}
+
static int32_t argmax(const float *v, uint32_t n)
{
uint32_t b = 0;
@@ -90,18 +132,37 @@ int main(int argc, char **argv)
.n_compute = n_compute,
.io_cpus = icpus,
.n_io = 8};
+ if (getenv("BENCH_EXACT") && atoi(getenv("BENCH_EXACT")) > 0)
+ mo.expert_bits = 6;
char err[256];
+ double tl = now();
struct janas_llm_model *m =
janas_llm_model_load(argv[1], &mo, err, sizeof(err));
if (!m) {
fprintf(stderr, "%s: %s\n", argv[1], err);
return 1;
}
+ printf("load: %.2f s\n", now() - tl);
+ if (getenv("BENCH_EXACT") && atoi(getenv("BENCH_EXACT")) > 0)
+ janas_llm_model_set_experts(m, 0);
+ uint32_t most_k = 0, k_use = janas_llm_model_experts(m, &most_k);
+ printf("experts: %u of the model's %u a token, down at %d bits%s\n", k_use,
+ most_k, janas_llm_model_expert_bits(m),
+ janas_llm_model_expert_bits_auto(m) ? " (chosen from the memory)"
+ : "");
+ /* BENCH_READY=1: the prompt after the preload of the profile */
+ if (getenv("BENCH_READY") && atoi(getenv("BENCH_READY")) > 0) {
+ double w0 = now();
+ while (janas_llm_model_settling(m))
+ usleep(20000);
+ printf("profile preload waited for: %.1f s\n", now() - w0);
+ }
uint32_t nv = janas_llm_model_n_vocab(m);
float *logits = malloc((size_t)nv * sizeof(float));
struct janas_expert_cache *c = janas_llm_model_cache(m);
struct janas_expert_cache_stats cs;
double ph[3][JANAS_PH_COUNT], t0 = now();
+ long long d0 = disk_busy_ms(argv[1]);
if (!logits)
return 1;
janas_llm_model_phases(m, ph[0]);
@@ -114,12 +175,16 @@ int main(int argc, char **argv)
}
}
double t1 = now();
+ long long d1 = disk_busy_ms(argv[1]);
janas_llm_model_phases(m, ph[1]);
janas_expert_cache_stats(c, &cs);
printf("prefill %u tokens: %.1f s (%.1f token/s); experts %.1f%% from "
"RAM, %.2f GB read, %.1f s waited\n",
np, t1 - t0, np / (t1 - t0), 100.0 * cs.hits / cs.requests,
cs.bytes_read / 1e9, cs.wait_seconds);
+ if (d0 >= 0 && d1 >= 0)
+ printf("prefill, disk busy: %.2f s (%.0f%%)\n", (d1 - d0) / 1e3,
+ 100.0 * (d1 - d0) / 1e3 / (t1 - t0));
report_phases("prefill", ph[0], ph[1], np);
janas_pool_trace_report("prefill", t1 - t0);
janas_pool_trace_reset();
@@ -132,12 +197,30 @@ int main(int argc, char **argv)
}
}
double t2 = now();
+ long long d2 = disk_busy_ms(argv[1]);
+ const char *save = getenv("BENCH_SAVE");
+ if (save) {
+ FILE *o = fopen(save, "wb");
+ if (!o || fwrite(prompt, sizeof(int32_t), np, o) != np ||
+ fwrite(out, sizeof(int32_t), nn, o) != nn || fclose(o) != 0)
+ fprintf(stderr, "cannot write %s\n", save);
+ }
janas_llm_model_phases(m, ph[2]);
janas_expert_cache_stats(c, &cs);
printf("decode %u tokens after %u: %.2f s (%.2f token/s); experts "
"%.1f%% from RAM, %.2f GB read (%.1f MB/token), %.2f s waited\n",
nn, np, t2 - t1, nn / (t2 - t1), 100.0 * cs.hits / cs.requests,
cs.bytes_read / 1e9, cs.bytes_read / 1e6 / nn, cs.wait_seconds);
+ if (d1 >= 0 && d2 >= 0)
+ printf("decode, disk busy: %.2f s (%.0f%%)\n", (d2 - d1) / 1e3,
+ 100.0 * (d2 - d1) / 1e3 / (t2 - t1));
+ if (cs.prefetch_reads)
+ printf("decode, read ahead: %llu experts (%.1f MB/token), %llu of "
+ "them asked for (%.0f%%)\n",
+ (unsigned long long)cs.prefetch_reads,
+ cs.prefetch_bytes / 1e6 / nn,
+ (unsigned long long)cs.prefetch_used,
+ 100.0 * cs.prefetch_used / cs.prefetch_reads);
report_phases("decode", ph[1], ph[2], nn);
janas_pool_trace_report("decode", t2 - t1);
struct rusage ru;
diff --git a/tests/gpu_check.c b/tests/gpu_check.c
index c300c32..7f69c89 100644
--- a/tests/gpu_check.c
+++ b/tests/gpu_check.c
@@ -2,9 +2,11 @@
Copyright (C) 2026 Maurizio Cammalleri */
/*
* gpu_check.c - products split between the GPU and the CPU must equal the
- * CPU's bit for bit: random Q4_K, Q5_K, Q6_K and Q6_K_P (bit planes, at its
- * three levels) matrices in shared memory, several shapes, vector counts and
- * strides. Skips (exit 0) when no GPU is usable.
+ * CPU's bit for bit: random Q4_K, Q5_K, Q6_K, Q6_K_P (bit planes, at its
+ * three levels), Q8_0 and the blocks of 32 (Q4_0, IQ4_NL, Q4_1, Q5_1)
+ * matrices in shared memory, and the GPU's aligned copy of Q6_K (on the GPU
+ * alone, against the CPU's Q6_K), several shapes, vector
+ * counts and strides. Skips (exit 0) when no GPU is usable.
*
* Usage: gpu_check
*/
@@ -64,6 +66,19 @@ int main(void)
struct janas_block_q6k *w6b = (struct janas_block_q6k *)w6;
for (size_t b = 0; b < (w6bytes - 4096) / 210; b++)
w6b[b].d = janas_fp32_to_fp16(0.0001f + (rnd() % 1000) * 1e-6f);
+ /* the same Q6_K in the GPU's aligned copy (gpu.h JANAS_Q6KA_BLOCK):
+ ql, qh, scales, d at byte 208 */
+ size_t nb6 = (w6bytes - 4096) / 210;
+ size_t wabytes = (nb6 * JANAS_Q6KA_BLOCK + 4095) / 4096 * 4096;
+ uint8_t *wa = aligned_alloc(4096, wabytes);
+ memset(wa, 0, wabytes);
+ for (size_t b = 0; b < nb6; b++) {
+ uint8_t *d = wa + b * JANAS_Q6KA_BLOCK;
+ memcpy(d, w6b[b].ql, sizeof(w6b[b].ql));
+ memcpy(d + 128, w6b[b].qh, sizeof(w6b[b].qh));
+ memcpy(d + 192, w6b[b].scales, sizeof(w6b[b].scales));
+ memcpy(d + 208, &w6b[b].d, sizeof(w6b[b].d));
+ }
/* Q6_K_P: the high planes (82-byte blocks), then the two bare planes
(64 bytes a block), row after row as in an expert slot */
size_t pbase = (size_t)MAXR * (MAXC / JANAS_QK) * 82 + 4096;
@@ -88,10 +103,75 @@ int main(void)
w5b[b].d = janas_fp32_to_fp16(0.001f + (rnd() % 1000) * 1e-5f);
w5b[b].dmin = janas_fp32_to_fp16(0.001f + (rnd() % 1000) * 1e-5f);
}
+ /* Q8_0: blocks of 32, eight to 256 weights */
+ size_t w8bytes = (size_t)MAXR * (MAXC / JANAS_QK) * 272;
+ w8bytes = (w8bytes + 4095) / 4096 * 4096;
+ uint8_t *w8 = aligned_alloc(4096, w8bytes);
+ for (size_t i = 0; i < w8bytes; i++)
+ w8[i] = (uint8_t)rnd();
+ struct janas_block_q8_0 *w8b = (struct janas_block_q8_0 *)w8;
+ for (size_t b = 0; b < w8bytes / 34; b++)
+ w8b[b].d = janas_fp32_to_fp16(0.0001f + (rnd() % 1000) * 1e-6f);
+ /* blocks of 32 with four or five bits: Q4_0 and IQ4_NL (18 bytes: d,
+ 16 of nibbles), Q4_1 (20: d, m, ...), Q5_1 (24: d, m, qh, ...);
+ random bytes with d (and m) set to small scales */
+ static const int t32[4] = {JANAS_Q4_0, JANAS_IQ4_NL, JANAS_Q4_1,
+ JANAS_Q5_1};
+ /* Q3_K (d at byte 108) and IQ3_S (d at 0): 110-byte blocks */
+ uint8_t *w3[2];
+ size_t w3bytes = (size_t)MAXR * (MAXC / JANAS_QK) * 110 + 4096;
+ w3bytes = (w3bytes + 4095) / 4096 * 4096;
+ for (int k = 0; k < 2; k++) {
+ w3[k] = aligned_alloc(4096, w3bytes);
+ for (size_t i = 0; i < w3bytes; i++)
+ w3[k][i] = (uint8_t)rnd();
+ for (size_t b = 0; b + 110 <= w3bytes; b += 110) {
+ uint16_t d = janas_fp32_to_fp16(0.0001f + (rnd() % 1000) * 1e-6f);
+ memcpy(w3[k] + b + (k == 0 ? 108 : 0), &d, 2);
+ }
+ }
+ /* IQ4_XS: 136-byte blocks, d, scales_h, scales_l, nibbles */
+ size_t wxbytes = (size_t)MAXR * (MAXC / JANAS_QK) * 136;
+ wxbytes = (wxbytes + 4095) / 4096 * 4096;
+ uint8_t *wx = aligned_alloc(4096, wxbytes);
+ for (size_t i = 0; i < wxbytes; i++)
+ wx[i] = (uint8_t)rnd();
+ for (size_t b = 0; b + 136 <= wxbytes; b += 136) {
+ uint16_t d = janas_fp32_to_fp16(0.00005f + (rnd() % 1000) * 1e-7f);
+ memcpy(wx + b, &d, 2);
+ }
+ static const size_t s32[4] = {18, 18, 20, 24};
+ uint8_t *w32[4];
+ size_t w32bytes[4];
+ for (int k = 0; k < 4; k++) {
+ w32bytes[k] = (size_t)MAXR * (MAXC / JANAS_QK) * 8 * s32[k];
+ w32bytes[k] = (w32bytes[k] + 4095) / 4096 * 4096;
+ w32[k] = aligned_alloc(4096, w32bytes[k]);
+ for (size_t i = 0; i < w32bytes[k]; i++)
+ w32[k][i] = (uint8_t)rnd();
+ for (size_t b = 0; b + s32[k] <= w32bytes[k]; b += s32[k]) {
+ uint16_t d = janas_fp32_to_fp16(0.0005f + (rnd() % 1000) * 1e-6f);
+ memcpy(w32[k] + b, &d, 2);
+ if (s32[k] > 18) {
+ uint16_t m =
+ janas_fp32_to_fp16(-0.01f + (rnd() % 1000) * 2e-5f);
+ memcpy(w32[k] + b + 2, &m, 2);
+ }
+ }
+ }
if (janas_gpu_import(g, w, wbytes) != 0 ||
janas_gpu_import(g, w6, w6bytes) != 0 ||
+ janas_gpu_import(g, wa, wabytes) != 0 ||
janas_gpu_import(g, wp, wpbytes) != 0 ||
- janas_gpu_import(g, w5, w5bytes) != 0) {
+ janas_gpu_import(g, w5, w5bytes) != 0 ||
+ janas_gpu_import(g, w8, w8bytes) != 0 ||
+ janas_gpu_import(g, w32[0], w32bytes[0]) != 0 ||
+ janas_gpu_import(g, w32[1], w32bytes[1]) != 0 ||
+ janas_gpu_import(g, w32[2], w32bytes[2]) != 0 ||
+ janas_gpu_import(g, w32[3], w32bytes[3]) != 0 ||
+ janas_gpu_import(g, wx, wxbytes) != 0 ||
+ janas_gpu_import(g, w3[0], w3bytes) != 0 ||
+ janas_gpu_import(g, w3[1], w3bytes) != 0) {
printf("gpu_check: import failed\n");
return 1;
}
@@ -116,12 +196,16 @@ int main(void)
const size_t shapes[][2] = {{4096, 2048}, {1000, 256}, {128, 4096},
{2048, 512}, {4096, 4096}, {777, 1024},
{1500, 768}}; /* odd blocks per row */
- const size_t nvs[] = {2, 3, 5, 8, 9, 16, 17};
+ const size_t nvs[] = {1, 2, 3, 5, 8, 9, 16, 17};
int bad = 0, runs = 0;
- /* 0 Q4_K, 1 Q6_K, 2-4 Q6_K_P with three, two and one planes, 5 Q5_K */
- static const char *names[] = {"Q4_K", "Q6_K", "Q6_K_P/3",
- "Q6_K_P/2", "Q6_K_P/1", "Q5_K"};
- for (int q6 = 0; q6 < 6; q6++)
+ /* 0 Q4_K, 1 Q6_K, 2-4 Q6_K_P with three, two and one planes, 5 Q5_K,
+ 6 Q8_0, 7-10 Q4_0, IQ4_NL, Q4_1, Q5_1, 11 IQ4_XS,
+ 12 Q3_K, 13 IQ3_S, 14 the aligned Q6_K */
+ static const char *names[] = {"Q4_K", "Q6_K", "Q6_K_P/3", "Q6_K_P/2",
+ "Q6_K_P/1", "Q5_K", "Q8_0", "Q4_0",
+ "IQ4_NL", "Q4_1", "Q5_1", "IQ4_XS",
+ "Q3_K", "IQ3_S", "Q6_K_A"};
+ for (int q6 = 0; q6 < 15; q6++)
for (size_t s = 0; s < sizeof(shapes) / sizeof(shapes[0]); s++)
for (size_t k = 0; k < sizeof(nvs) / sizeof(nvs[0]); k++)
for (int strided = 0; strided < 2; strided++) {
@@ -130,11 +214,23 @@ int main(void)
size_t skip = s % 2; /* a row further in, every other
shape */
struct janas_matvec_task t = {
- .type = q6 == 5 ? JANAS_Q5_K
- : q6 >= 2 ? JANAS_Q6_K_P
- : q6 == 1 ? JANAS_Q6_K
- : JANAS_Q4_K,
- .w = q6 == 5 ? w5 + skip * 176 * nb
+ .type = q6 == 14 ? JANAS_Q6_K
+ : q6 == 13 ? JANAS_IQ3_S
+ : q6 == 12 ? JANAS_Q3_K
+ : q6 == 11 ? JANAS_IQ4_XS
+ : q6 >= 7 ? t32[q6 - 7]
+ : q6 == 6 ? JANAS_Q8_0
+ : q6 == 5 ? JANAS_Q5_K
+ : q6 >= 2 ? JANAS_Q6_K_P
+ : q6 == 1 ? JANAS_Q6_K
+ : JANAS_Q4_K,
+ .w = q6 == 14 ? w6 + skip * 210 * nb
+ : q6 >= 12 ? w3[q6 - 12] + skip * 110 * nb
+ : q6 == 11 ? wx + skip * 136 * nb
+ : q6 >= 7
+ ? w32[q6 - 7] + skip * 8 * s32[q6 - 7] * nb
+ : q6 == 6 ? w8 + skip * 272 * nb
+ : q6 == 5 ? w5 + skip * 176 * nb
: q6 >= 2 ? wp + skip * 82 * nb
: q6 == 1 ? w6 + skip * 210 * nb
: w + skip * 144 * nb,
@@ -155,7 +251,12 @@ int main(void)
t.y = ya;
janas_matvec_q4k_group(pool, &t, 1);
t.y = yb;
- if (getenv("GPU_ONLY")) {
+ if (q6 == 14) {
+ /* the CPU has no aligned copy: all on the GPU */
+ t.type = JANAS_Q6_K_A;
+ t.w = wa + skip * JANAS_Q6KA_BLOCK * nb;
+ }
+ if (getenv("GPU_ONLY") || q6 == 14) {
/* every row on the GPU, nothing on the CPU */
int waited;
if (janas_gpu_begin(g, &t, &rows, 1) != 0 ||
@@ -214,8 +315,15 @@ int main(void)
janas_pool_destroy(pool);
free(w);
free(w6);
+ free(wa);
free(wp);
free(w5);
+ free(w8);
+ for (int k = 0; k < 4; k++)
+ free(w32[k]);
+ free(wx);
+ free(w3[0]);
+ free(w3[1]);
free(x);
free(xf);
free(ya);
diff --git a/tests/llm_gen.c b/tests/llm_gen.c
index b4e47ea..44c5cb0 100644
--- a/tests/llm_gen.c
+++ b/tests/llm_gen.c
@@ -10,6 +10,8 @@
* Usage: llm_gen <model.jns> <prompt.int32> <n_prompt> <n_new> <k> [auto]
* [mtp=<mtp.jns>] [conf=<min probability of an MTP draft>]
* With mtp= the drafts come from the model's MTP block instead of lookup.
+ * With cpus=<list> (e.g. 0-11 or 18,19) the compute threads run on those
+ * CPUs, one each (to run it beside another process on other cores).
*/
#include <stdio.h>
#include <stdlib.h>
@@ -95,6 +97,7 @@ int main(int argc, char **argv)
const char *draft_path = NULL;
uint64_t seed = 20260922;
float top_p = 0.8f;
+ int cpu_list[64], n_list = 0;
for (int i = 6; i < argc; i++) {
if (strcmp(argv[i], "auto") == 0)
use_auto = 1;
@@ -114,7 +117,20 @@ int main(int argc, char **argv)
draft_path = argv[i] + 6;
else if (strncmp(argv[i], "seed=", 5) == 0)
seed = strtoull(argv[i] + 5, NULL, 10);
- else if (strncmp(argv[i], "top_p=", 6) == 0)
+ else if (strncmp(argv[i], "cpus=", 5) == 0) {
+ /* a, a-b, comma separated */
+ for (const char *c = argv[i] + 5; *c && n_list < 64;) {
+ char *e;
+ long a = strtol(c, &e, 10), b = a;
+ if (e == c)
+ break;
+ if (*e == '-')
+ b = strtol(e + 1, &e, 10);
+ for (long k = a; k <= b && n_list < 64; k++)
+ cpu_list[n_list++] = (int)k;
+ c = *e == ',' ? e + 1 : e;
+ }
+ } else if (strncmp(argv[i], "top_p=", 6) == 0)
top_p = (float)atof(argv[i] + 6);
else if (strncmp(argv[i], "seed=", 5) == 0)
seed = (uint64_t)strtoull(argv[i] + 5, NULL, 10);
@@ -123,7 +139,10 @@ int main(int argc, char **argv)
struct janas_cpu_layout lay;
int ccpus[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
const int *compute = ccpus;
- if (n_compute != 12 && janas_cpu_layout(NULL, 0, &lay) == 0) {
+ if (n_list > 0) {
+ compute = cpu_list;
+ n_compute = n_list;
+ } else if (n_compute != 12 && janas_cpu_layout(NULL, 0, &lay) == 0) {
if (n_compute < 1 || n_compute > lay.n)
n_compute = lay.n;
compute = lay.cpus;
diff --git a/tests/test_expert_cache.c b/tests/test_expert_cache.c
index 719b10e..146b54a 100644
--- a/tests/test_expert_cache.c
+++ b/tests/test_expert_cache.c
@@ -7,7 +7,9 @@
* file system, not tmpfs) whose every expert slot is filled with its own
* (layer, expert) identity, then checks on random request sequences that
* every returned slot holds the expert asked for, and that hits and misses
- * match a reference model of the replacement policy.
+ * match a reference model of the replacement policy. Reads ahead
+ * (janas_expert_cache_prefetch): hits with the right bytes when their layer
+ * asks, never evicted before it has, unprotected once it has.
*/
#define _GNU_SOURCE
#include <fcntl.h>
@@ -277,7 +279,24 @@ static void check_resident(struct janas_jns *j, struct janas_pool *io)
/* hits load nothing: a GPU's copy stays true */
CHECK(janas_expert_cache_loads(c) == ALL, "hits changed loads to %llu",
(unsigned long long)janas_expert_cache_loads(c));
- janas_expert_cache_destroy(c);
+ /* moved to memory of another's (as a GPU driver's): every expert
+ where fetch says, with its bytes, in the new arena */
+ uint8_t *moved = aligned_alloc(4096, (size_t)ALL * SLOT);
+ CHECK(moved && janas_expert_cache_rebase(c, moved) == 0,
+ "rebase failed");
+ for (uint32_t k = 0; moved && k < ALL; k++) {
+ uint32_t e = k % N_EXPERT;
+ CHECK(janas_expert_cache_fetch(c, k / N_EXPERT, &e, 1, &slot) == 0,
+ "fetch after rebase");
+ CHECK(slot >= moved && slot + SLOT <= moved + (size_t)ALL * SLOT,
+ "slot outside the new arena");
+ fill_slot(expect, k / N_EXPERT, e);
+ CHECK(memcmp(slot, expect, SLOT) == 0, "rebased: wrong bytes");
+ }
+ CHECK(janas_expert_cache_resident(c, &bytes, &loads) == moved,
+ "resident is not the new arena");
+ janas_expert_cache_destroy(c); /* not the arena: it is ours */
+ free(moved);
}
/* filled in the background: never while it runs, then resident */
@@ -309,6 +328,125 @@ static void check_resident(struct janas_jns *j, struct janas_pool *io)
}
/* The whole check, once with the reads on the ring and once without it. */
+/* A request of one layer, checked: every slot holds its expert. */
+static void ask(struct janas_expert_cache *c, uint32_t layer,
+ const uint32_t *ids, int n, const char *what)
+{
+ static uint8_t expect[SLOT];
+ const uint8_t *slots[K];
+ CHECK(janas_expert_cache_fetch(c, layer, ids, (size_t)n, slots) == 0,
+ "%s: fetch failed", what);
+ for (int i = 0; i < n; i++) {
+ fill_slot(expect, layer, ids[i]);
+ CHECK(memcmp(slots[i], expect, SLOT) == 0,
+ "%s: layer %u expert %u has the wrong bytes", what, layer,
+ ids[i]);
+ }
+}
+
+/* Reads ahead: only with io_uring (without, prefetch reads nothing). */
+static void check_prefetch(struct janas_jns *j, struct janas_pool *io)
+{
+ char err[256];
+ struct janas_expert_cache_stats st;
+ struct janas_expert_cache *c = janas_expert_cache_create(
+ j, (uint64_t)SLOTS * SLOT, 3, io, err, sizeof(err));
+ CHECK(c != NULL, "create (prefetch): %s", err);
+ if (!c)
+ return;
+ /* the basic case: read ahead, then asked - hits, the right bytes */
+ uint32_t ahead[4] = {0, 1, 2, 3};
+ int n = janas_expert_cache_prefetch(c, 1, ahead, 4, 2);
+ const char *u = getenv("JANAS_URING");
+ int ring = !(u && atoi(u) == 0);
+ if (!ring) {
+ CHECK(n == 0, "prefetch without io_uring read %d", n);
+ janas_expert_cache_destroy(c);
+ return;
+ }
+ if (n == 0) { /* no io_uring in this kernel: nothing to check */
+ janas_expert_cache_destroy(c);
+ return;
+ }
+ CHECK(n == 2, "prefetch read %d of at most 2", n);
+ uint32_t want[3] = {0, 1, 5};
+ ask(c, 1, want, 3, "after a prefetch");
+ janas_expert_cache_stats(c, &st);
+ CHECK(st.hits == 2 && st.misses == 1, "prefetched: %llu hits, %llu misses",
+ (unsigned long long)st.hits, (unsigned long long)st.misses);
+ CHECK(st.prefetch_reads == 2 && st.prefetch_used == 2,
+ "prefetch stats %llu read, %llu used",
+ (unsigned long long)st.prefetch_reads,
+ (unsigned long long)st.prefetch_used);
+ CHECK(st.bytes_read == SLOT && st.prefetch_bytes == 2 * SLOT,
+ "bytes %llu, ahead %llu", (unsigned long long)st.bytes_read,
+ (unsigned long long)st.prefetch_bytes);
+ /* protection: the cache full, a prefetch for layer 2 takes two slots;
+ layer 0 then asks for three new experts, and must not take them */
+ uint32_t l0a[3] = {0, 1, 2};
+ ask(c, 0, l0a, 3, "filling");
+ uint32_t ahead2[2] = {6, 7};
+ CHECK(janas_expert_cache_prefetch(c, 2, ahead2, 2, 2) == 2,
+ "prefetch into a full cache");
+ uint32_t l0b[3] = {3, 4, 5};
+ ask(c, 0, l0b, 3, "evicting around a prefetch");
+ janas_expert_cache_reset_stats(c);
+ uint32_t l2[3] = {6, 7, 0};
+ ask(c, 2, l2, 3, "the prefetched layer");
+ janas_expert_cache_stats(c, &st);
+ CHECK(st.hits == 2 && st.prefetch_used == 2,
+ "prefetched and protected: %llu hits, %llu used",
+ (unsigned long long)st.hits, (unsigned long long)st.prefetch_used);
+ /* unused: read ahead and not asked, it is protected no longer - the
+ misses that follow may take its slot */
+ uint32_t ahead3[1] = {4};
+ CHECK(janas_expert_cache_prefetch(c, 1, ahead3, 1, 1) == 1,
+ "prefetch of one");
+ uint32_t l1[3] = {0, 1, 2};
+ ask(c, 1, l1, 3, "a layer that did not want it");
+ uint32_t l0c[1] = {6};
+ ask(c, 0, l0c, 1, "one miss");
+ janas_expert_cache_reset_stats(c);
+ uint32_t l1b[1] = {4};
+ ask(c, 1, l1b, 1, "the unused one again");
+ janas_expert_cache_stats(c, &st);
+ CHECK(st.misses == 1, "an unused prefetch stayed in the cache");
+ /* the engine's order: layer l + 1 read ahead before layer l asks, so
+ two sets are out at once - the one for l + 1 must survive layer l's
+ request and its misses, and be counted when l + 1 asks */
+ {
+ struct janas_expert_cache *e = janas_expert_cache_create(
+ j, (uint64_t)SLOTS * SLOT, 3, io, err, sizeof(err));
+ CHECK(e != NULL, "create (two sets): %s", err);
+ if (e) {
+ uint32_t a1[1] = {4}, a2[1] = {5};
+ CHECK(janas_expert_cache_prefetch(e, 1, a1, 1, 1) == 1,
+ "ahead of layer 1");
+ uint32_t r0[3] = {0, 1, 2};
+ ask(e, 0, r0, 3, "layer 0 with layer 1 read ahead");
+ CHECK(janas_expert_cache_prefetch(e, 2, a2, 1, 1) == 1,
+ "ahead of layer 2");
+ uint32_t r1[3] = {4, 0, 1};
+ ask(e, 1, r1, 3, "layer 1 with layer 2 read ahead");
+ janas_expert_cache_stats(e, &st);
+ CHECK(st.prefetch_used == 1, "layer 1's read ahead: %llu used",
+ (unsigned long long)st.prefetch_used);
+ uint32_t r2[3] = {5, 0, 1};
+ ask(e, 2, r2, 3, "layer 2");
+ janas_expert_cache_stats(e, &st);
+ CHECK(st.prefetch_used == 2 && st.prefetch_reads == 2,
+ "two sets: %llu of %llu used",
+ (unsigned long long)st.prefetch_used,
+ (unsigned long long)st.prefetch_reads);
+ janas_expert_cache_destroy(e);
+ }
+ }
+ /* destroyed with reads ahead in flight */
+ uint32_t ahead4[2] = {1, 2};
+ janas_expert_cache_prefetch(c, 2, ahead4, 2, 2);
+ janas_expert_cache_destroy(c);
+}
+
static void run(const char *path, const char *how)
{
rng = 0x9E3779B97F4A7C15ull;
@@ -436,6 +574,7 @@ static void run(const char *path, const char *how)
}
janas_expert_cache_destroy(c);
+ check_prefetch(&j, io);
check_resident(&j, io);
janas_pool_destroy(io);
janas_jns_close(&j);
diff --git a/tests/test_sample.c b/tests/test_sample.c
new file mode 100644
index 0000000..5cb39cf
--- /dev/null
+++ b/tests/test_sample.c
@@ -0,0 +1,106 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * test_sample.c - the sampler's random sequence: the same seed draws the
+ * same tokens, and going back n draws (janas_sampler_rewind) draws the last
+ * n again, as a reply cut short after a speculative pass needs; at
+ * temperature 0 the most likely token, going back or not.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "llm/sample.h"
+
+static int failures;
+
+#define CHECK(c, ...) \
+ do { \
+ if (!(c)) { \
+ printf(__VA_ARGS__); \
+ printf("\n"); \
+ failures++; \
+ } \
+ } while (0)
+
+#define NV 64
+#define DRAWS 40
+
+/* logits spread enough that the draws vary */
+static void fill(float *lg, int step)
+{
+ for (int i = 0; i < NV; i++)
+ lg[i] = (float)((i * 7 + step * 13) % NV) / 16.0f;
+}
+
+static void picks(struct janas_sampler *s, int from, int n, int32_t *out)
+{
+ float lg[NV];
+ for (int i = 0; i < n; i++) {
+ fill(lg, from + i);
+ out[i] = janas_sampler_pick(s, lg, NULL);
+ }
+}
+
+int main(void)
+{
+ alarm(60);
+ struct janas_sampler *a = janas_sampler_create(NV);
+ struct janas_sampler *b = janas_sampler_create(NV);
+ if (!a || !b) {
+ printf("test_sample: out of memory\n");
+ return 1;
+ }
+ const struct janas_sample_params warm = {.temperature = 1.0f};
+ janas_sampler_set(a, &warm, 12345);
+ janas_sampler_set(b, &warm, 12345);
+ int32_t ta[DRAWS], tb[DRAWS], again[DRAWS];
+ picks(a, 0, DRAWS, ta);
+ picks(b, 0, DRAWS, tb);
+ int differ = 0;
+ for (int i = 0; i < DRAWS; i++) {
+ CHECK(ta[i] == tb[i], "same seed, draw %d: %d against %d", i, ta[i],
+ tb[i]);
+ differ |= ta[i] != ta[0];
+ }
+ CHECK(differ, "the draws never vary: the test proves nothing");
+
+ /* b goes back 15 draws and draws them again: the same tokens */
+ janas_sampler_rewind(b, 15);
+ picks(b, DRAWS - 15, 15, again);
+ for (int i = 0; i < 15; i++)
+ CHECK(again[i] == ta[DRAWS - 15 + i],
+ "after going back 15, draw %d: %d against %d", i, again[i],
+ ta[DRAWS - 15 + i]);
+ /* and from there on both go on alike */
+ picks(a, DRAWS, 10, ta);
+ picks(b, DRAWS, 10, tb);
+ for (int i = 0; i < 10; i++)
+ CHECK(ta[i] == tb[i], "after the rewind, draw %d: %d against %d", i,
+ ta[i], tb[i]);
+
+ /* greedy: the most likely token every time, going back or not */
+ const struct janas_sample_params cold = {.temperature = 0.0f};
+ janas_sampler_set(a, &cold, 7);
+ picks(a, 0, 5, ta);
+ janas_sampler_rewind(a, 3);
+ picks(a, 5, 5, ta + 5);
+ for (int i = 0; i < 10; i++) {
+ float lg[NV];
+ fill(lg, i);
+ int best = 0;
+ for (int k = 1; k < NV; k++)
+ if (lg[k] > lg[best])
+ best = k;
+ CHECK(ta[i] == best, "greedy, draw %d: %d against %d", i, ta[i], best);
+ }
+
+ janas_sampler_destroy(a);
+ janas_sampler_destroy(b);
+ if (failures) {
+ printf("test_sample: %d failures\n", failures);
+ return 1;
+ }
+ printf("test_sample: ok\n");
+ return 0;
+}