Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

fix(st): publish the lazy shard-mapping table without a data race

basil-k-aji-dev7b46843e54c5
diff --git a/c/st.h b/c/st.h
index 4a4a4d0c..003b3667 100644
--- a/c/st.h
+++ b/c/st.h
@@ -1008,20 +1008,42 @@ static int st_map_experts_enabled(void) {
return on;
}
+/* Reached from parallel regions: glm53.c's `#pragma omp parallel for` over the
+ * batch calls expert_read -> st_map_shard_range -> here from every worker at
+ * once, and qwen38_core.h does the same. Two threads racing the plain version
+ * of this both saw g_st_shard_tried[fd] == 0, both mapped the file, and one
+ * leaked its mapping while a third could read g_st_shard_len[fd] as 0 through
+ * an already-published base -- st_map_shard_range then rejects every range for
+ * that shard. Latent only because COLI_MAP_EXPERTS is opt-in; #1350 proposes
+ * flipping that default.
+ *
+ * Lock-free rather than the mutex qwen38_core.h uses for its lazy HITS table,
+ * because st.h is also compiled into c/tools/check_glm53_container.c, whose
+ * documented build line is plain `gcc -O2 -std=gnu11 -Ic ... -lm` with neither
+ * -pthread nor -fopenmp. */
static const uint8_t *st_shard_mapped(int fd) {
if (fd < 0 || fd >= ST_MAX_MAPPED_FD || !st_map_experts_enabled()) return NULL;
- if (g_st_shard_base[fd]) return g_st_shard_base[fd];
- if (g_st_shard_tried[fd]) return NULL;
- g_st_shard_tried[fd] = 1;
+ /* Acquire: a base published below carries g_st_shard_len[fd] with it. */
+ const uint8_t *base = __atomic_load_n(&g_st_shard_base[fd], __ATOMIC_ACQUIRE);
+ if (base) return base;
+ /* Claim the fd exactly once. The losing thread does not block: NULL is the
+ * documented "use pread" answer, so it takes the pread path for this one
+ * call rather than parking an OpenMP worker behind an mmap. */
+ signed char unclaimed = 0;
+ if (!__atomic_compare_exchange_n(&g_st_shard_tried[fd], &unclaimed, (signed char)1,
+ 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE))
+ return __atomic_load_n(&g_st_shard_base[fd], __ATOMIC_ACQUIRE);
int64_t len = (int64_t)lseek(fd, 0, SEEK_END);
if (len <= 0) return NULL;
compat_ro_map map; const void *data;
if (compat_map_readonly(fd, 0, (size_t)len, &map, &data) != 0) return NULL;
/* The compat_ro_map itself is intentionally not tracked for unmap: shard
* mappings live exactly as long as the fd they wrap, i.e. the process. */
- g_st_shard_base[fd] = (uint8_t *)data;
+ /* Length first, then release-store the base: whoever sees the base through
+ * the acquire load above necessarily sees the length too. */
g_st_shard_len[fd] = len;
- return g_st_shard_base[fd];
+ __atomic_store_n(&g_st_shard_base[fd], (uint8_t *)data, __ATOMIC_RELEASE);
+ return (const uint8_t *)data;
}
/* Serves [off, off+nbytes) of file `fd` directly out of its persistent