FreeToken brings datacenter-scale model serving to your desktop. Run massive models locally, fast and efficiently.
perf(moe): spin-wait the cpu moe pool between layers (#619)
Xiaoze Fan1c183e74ae39
diff --git a/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cppindex e2cb0d9c..fb6a33f4 100644--- a/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp+++ b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp@@ -49,6 +49,14 @@namespace {+inline void cpu_relax() {+#if CPU_MOE_X86+ _mm_pause();+#elif defined(__aarch64__)+ asm volatile("yield" ::: "memory");+#endif+}+using bf16_t = uint16_t;inline float bf16_to_f32(bf16_t v) {@@ -1290,13 +1298,19 @@ struct CpuMoeExecutor {std::mutex sync_mtx;std::condition_variable sync_cv;- bool stop = false;+ std::atomic<bool> stop{false}; // spinning workers read it without the lockuint64_t cur_gen = 0;MoeTask* cur_task = nullptr;- std::atomic<uint64_t> submitted{0};- std::atomic<uint64_t> completed{0};+ // Separate cache lines: idle workers poll `submitted` while busy workers hit p1_next/p2_next.+ alignas(64) std::atomic<uint64_t> submitted{0};+ alignas(64) std::atomic<uint64_t> completed{0};++ // Spin-then-park waits. Off unless the Python wrapper finds spare CPUs for the spinners.+ static constexpr auto kSpinWindow = std::chrono::milliseconds(50);+ std::atomic<bool> spin_wait{false};+ bool coord_pinned = false;- std::atomic<int64_t> p1_next{0};+ alignas(64) std::atomic<int64_t> p1_next{0};std::atomic<int64_t> p2_next{0};std::atomic<int64_t> prt_next{0}; // ds_fp4 intermediate fp8 round-trip phaseint64_t p1_total = 0, p2_total = 0, prt_total = 0;@@ -1866,19 +1880,34 @@ struct CpuMoeExecutor {}}+ // Tasks arrive once per MoE layer, sub-ms apart. Spinning skips a futex wakeup per worker per layer; parking after kSpinWindow keeps an idle server off the CPU.void worker_loop(int tid) {pin_self(tid);uint64_t my_gen = 0;+ using wclk = std::chrono::steady_clock;+ auto last_active = wclk::now();for (;;) {- MoeTask* t;- {+ uint64_t gen = submitted.load(std::memory_order_acquire);+ if (gen == my_gen && spin_wait.load(std::memory_order_relaxed)) {+ unsigned polls = 0;+ while (gen == my_gen) {+ cpu_relax();+ if (stop.load(std::memory_order_relaxed)) return;+ if ((++polls & 1023u) == 0 && wclk::now() - last_active > kSpinWindow) break;+ gen = submitted.load(std::memory_order_acquire);+ }+ }+ if (gen == my_gen) {std::unique_lock<std::mutex> lk(task_mtx);- task_cv.wait(lk, [&] { return stop || cur_gen != my_gen; });- if (stop) return;- my_gen = cur_gen;- t = cur_task;+ task_cv.wait(lk, [&] { return stop.load() || cur_gen != my_gen; });+ if (stop.load()) return;+ gen = cur_gen;}+ // submit() writes cur_task before the release store to `submitted`.+ my_gen = gen;+ MoeTask* t = cur_task;run_task_body(t);+ last_active = wclk::now();if (done_count.fetch_add(1) + 1 == num_threads) {completed.store(my_gen, std::memory_order_release);{@@ -1961,8 +1990,19 @@ struct CpuMoeExecutor {task_cv.notify_all();}- void sync() {+ // Only a coordinator on its own core may spin: host-func callbacks and eager calls share cores with the workers.+ void sync(bool spin = false) {const uint64_t target = submitted.load(std::memory_order_acquire);+ if (spin) {+ using sclk = std::chrono::steady_clock;+ const auto t0 = sclk::now();+ unsigned polls = 0;+ while (completed.load(std::memory_order_acquire) < target) {+ cpu_relax();+ if ((++polls & 1023u) == 0 && sclk::now() - t0 > kSpinWindow) break;+ }+ if (completed.load(std::memory_order_acquire) >= target) return;+ }std::unique_lock<std::mutex> lk(sync_mtx);sync_cv.wait(lk, [&] { return completed.load(std::memory_order_acquire) >= target; });}@@ -2003,6 +2043,7 @@ struct CpuMoeExecutor {}flag_served.assign(num_slots, 0);coord_stop.store(false);+ coord_pinned = CPU_MOE_HAS_AFFINITY && pin_core >= 0;coord_thread = std::thread([this, pin_core] {#if CPU_MOE_HAS_AFFINITYif (pin_core >= 0) {@@ -2050,7 +2091,7 @@ struct CpuMoeExecutor {}if (t != nullptr) {submit(t);- sync();+ sync(coord_pinned && spin_wait.load(std::memory_order_relaxed));}// Release: the workers' y stores are visible before the GPU sees done.flag_store_release(&done_flags[L], 1);@@ -2144,7 +2185,11 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {.def("set_input_prequant",[](CpuMoeExecutor& e, bool v) { e.input_prequant = v; },py::arg("value"))- .def("isa_name", &CpuMoeExecutor::isa_name);+ .def("isa_name", &CpuMoeExecutor::isa_name)+ .def("set_spin_wait",+ [](CpuMoeExecutor& e, bool v) { e.spin_wait.store(v, std::memory_order_relaxed); },+ py::arg("enabled"))+ .def("get_spin_wait", [](const CpuMoeExecutor& e) { return e.spin_wait.load(); });m.def("memops_probe", &cumemops_probe, py::arg("stream"), py::arg("scratch_addr"));m.def("memop_submit", &cumemop_submit, py::arg("stream"), py::arg("done_addr"),py::arg("ready_addr"), py::arg("slot"));diff --git a/python/freetoken/moe/cpu_executor.py b/python/freetoken/moe/cpu_executor.pyindex e2e48d14..a4680674 100644--- a/python/freetoken/moe/cpu_executor.py+++ b/python/freetoken/moe/cpu_executor.py@@ -53,6 +53,8 @@ _FLAG_SYNC = os.getenv("FREETOKEN_CPU_MOE_FLAG_SYNC", "1") != "0"# sizes plus any eager padded sizes); more than that is unheard of, and the overflow# just keeps the host-func path for the extra combos._FLAG_SLOTS_PER_LAYER = 16+# Pool threads spin up to 50 ms before they park. FREETOKEN_CPU_MOE_SPIN=0 opts out.+_SPIN_WAIT = os.getenv("FREETOKEN_CPU_MOE_SPIN", "1") != "0"# Activation ids must match ActKind in csrc/cpu_moe/cpu_moe_ext.cpp. Id 3 is the# clamped (up + 1) swiglu: "swigluoai" runs it in the generic GEMV epilogue,@@ -116,6 +118,17 @@ def physical_core_cpus() -> list[int]:return reps or allowed or [0]+def _spin_wait_ok(core_ids: list[int], coord_core: int) -> bool:+ """Spin only if each pool thread owns a distinct CPU and two CPUs stay free for the main and CUDA callback threads."""+ if not _SPIN_WAIT or not hasattr(os, "sched_getaffinity"):+ return False+ pool = list(core_ids) + ([coord_core] if coord_core >= 0 else [])+ if len(set(pool)) != len(pool):+ return False+ spare = set(os.sched_getaffinity(0)) - set(pool)+ return len(spare) >= 2++def resolve_threads_and_affinity(requested: int) -> tuple[int, list[int]]:"""Return (num_threads, core_ids) for the worker pool.@@ -246,6 +259,8 @@ class CpuMoeExecutor:self.num_threads = nthreadsself.core_ids = core_idsself.isa = self._ext.isa_name()+ self.spin_wait = _spin_wait_ok(core_ids, coord_core)+ self._ext.set_spin_wait(self.spin_wait)spare = len(physical_core_cpus()) - nthreads - (1 if coord_core >= 0 else 0) - 1clamp = max(1, min(torch.get_num_threads(), spare))@@ -319,7 +334,8 @@ class CpuMoeExecutor:f"CPU MoE executor ready: threads={nthreads} (pinned to cores "f"{core_ids[0]}..{core_ids[-1]}) isa={self.isa} fmt={fmt} "f"H={self.H} I={self.I} experts={self.num_experts} layers={self.num_layers} "- f"top_k={self.top_k} act={activation} max_tokens={self.max_tokens}"+ f"top_k={self.top_k} act={activation} max_tokens={self.max_tokens} "+ f"spin_wait={self.spin_wait}")def _make_table(self, layers: list[torch.Tensor]) -> torch.Tensor: