Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Prefill: upload the CPU embedding rows pinned, narrow and asynchronous, widen on the device
YanissAmzf8c78c572ea3
diff --git a/exllamav3/model/model_ls.py b/exllamav3/model/model_ls.pyindex 1e17f3f..f60b3f8 100644--- a/exllamav3/model/model_ls.py+++ b/exllamav3/model/model_ls.py@@ -298,6 +298,15 @@ class Model_LSMixin(ABC):yield+ def _name_embedding_target(self, x: torch.Tensor, params: dict):+ """A long chunk of token ids headed for a CPU-resident embedding: tell it the device of the module that consumes its output+ (Embedding.forward then uploads the rows pinned and asynchronously, see EXL3_PF_EMB_UPLOAD)."""+ if x.device.type == "cpu" and x.numel() >= 1024 and len(self.fwd_modules) > 1:+ dev = self.fwd_modules[1][0].device+ if dev is not None and torch.device(dev).type == "cuda":+ params["emb_next_device"] = dev++def prefill_ls(self,x: torch.Tensor,@@ -305,6 +314,7 @@ class Model_LSMixin(ABC):):for h in getattr(self.config, "moe_cpu_hosts", {}).values():h.begin_pass()+ self._name_embedding_target(x, params)for module, instance, idx in self.fwd_modules:params["layer_instance"] = instancepf = (idx, instance) == self.last_kv_module_idx_instance@@ -328,6 +338,7 @@ class Model_LSMixin(ABC):):for h in getattr(self.config, "moe_cpu_hosts", {}).values():h.begin_pass()+ self._name_embedding_target(x, params)span = _FWD_SPAN and x.dim() >= 3 and x.shape[1] <= 8 # (batch, rows, ..): decode/verify only, not prefill chunksfor module, instance, idx in self.fwd_modules:params["layer_instance"] = instancediff --git a/exllamav3/modules/arch_specific/qwen3_5_mtp.py b/exllamav3/modules/arch_specific/qwen3_5_mtp.pyindex 9d22941..8dc69d4 100644--- a/exllamav3/modules/arch_specific/qwen3_5_mtp.py+++ b/exllamav3/modules/arch_specific/qwen3_5_mtp.py@@ -101,7 +101,11 @@ class Qwen3_5MTPInputLayer(Module):# Token embeddingif not self.attached_model().loaded_tp:- x = self.attached_model().modules[0].forward(x, params, out_dtype = torch.half)+ emb = self.attached_model().modules[0]+ if hasattr(emb, "forward_device"):+ x = emb.forward_device(x, params, torch.half, self.device)+ else:+ x = emb.forward(x, params, out_dtype = torch.half)else:x = self.attached_model().tp_producer.send(x)x = self.attached_model().tp_dispatch_master(mp_model_forward_embedding, (x, params))diff --git a/exllamav3/modules/embedding.py b/exllamav3/modules/embedding.pyindex 2f777fd..eec0ce8 100644--- a/exllamav3/modules/embedding.py+++ b/exllamav3/modules/embedding.py@@ -1,9 +1,11 @@from __future__ import annotationsfrom typing_extensions import override+import osimport torchfrom torch import nnfrom ..model.config import Configfrom ..util.tensor import to2+from ..util.device_copy import to_devicefrom . import Modulefrom ..tokenizer.mm_embedding import FIRST_MM_EMBEDDING_INDEX, mm_rowsfrom ..model.model_tp_alloc import TPAllocation@@ -83,6 +85,7 @@ class Embedding(Module):indexed_emb = params.get("indexed_embeddings")input_ids = x+ explicit_dtype = out_dtype is not Noneout_dtype = out_dtype or self.out_dtype or x.dtype# Indexed embedding masks@@ -147,6 +150,9 @@ class Embedding(Module):# No indexed embeddings, or none in current batchelse:+ dev = params.get("emb_next_device")+ if dev is not None and not explicit_dtype and self._narrow_upload_ok(x, params):+ return self._upload_narrow(self._gather_narrow(x), x, out_dtype, dev)x = self.embedding.forward(x)if self.multiplier != 1.0:x *= self.multiplier@@ -169,6 +175,53 @@ class Embedding(Module):x = bufreturn x+ # EXL3_PF_EMB_UPLOAD=1: a long chunk (>= 1024 rows) of a CPU-resident embedding is gathered straight into a pinned buffer in the+ # table's own 16-bit dtype and uploaded asynchronously; the widening to out_dtype (exact, fp16/bf16 -> fp32) happens on the device+ # in Module.prepare_for_device (finish_narrow). The default path gathers, widens on the host and copies 4 bytes per element from+ # pageable memory (94 MB per 4583-row chunk: ~25 ms with the GPU idle, 3.8 GB/s). Same values bit for bit.+ def _narrow_upload_ok(self, ids: torch.Tensor, params: dict) -> bool:+ if os.environ.get("EXL3_PF_EMB_UPLOAD", "0") != "1" or ids.device.type != "cpu" or self.normalize or params.get("pinned_staging"):+ return False+ w = self.embedding.weight+ return w.device.type == "cpu" and w.dtype in (torch.half, torch.bfloat16) and ids.numel() >= 1024 and torch.cuda.is_available()++ def forward_device(self, ids: torch.Tensor, params: dict, out_dtype: torch.dtype, device) -> torch.Tensor:+ """forward(ids, params, out_dtype) followed by a move to `device`, with the long-chunk upload of _gather_narrow."""+ if ids.device.type == "cpu" and not params.get("indexed_embeddings") and self._narrow_upload_ok(ids, params):+ # the MTP block embeds the very rows the target forward just uploaded: reuse them (same bf16 -> fp16 rounding, on the device)+ hit = getattr(self, "_dev_rows", None)+ self._dev_rows = None+ if hit is not None and hit[0].shape == ids.shape and hit[1].device == torch.device(device) and torch.equal(hit[0], ids):+ return hit[1] if hit[1].dtype == out_dtype else hit[1].to(out_dtype)+ return self._upload_narrow(self._gather_narrow(ids), ids, out_dtype, device)+ return to_device(self.forward(ids, params, out_dtype = out_dtype), device)++ def _gather_narrow(self, ids: torch.Tensor) -> torch.Tensor:+ w = self.embedding.weight.detach()+ n = ids.numel()+ buf = getattr(self, "_narrow_buf", None)+ if buf is not None and getattr(self, "_narrow_ev", None) is not None:+ self._narrow_ev.synchronize() # the previous upload out of this buffer has completed+ if buf is None or buf.shape[0] < n or buf.dtype != w.dtype:+ buf = torch.empty((n, self.hidden_size), dtype = w.dtype, pin_memory = True)+ self._narrow_buf = buf+ self._narrow_ev = None+ y = buf[:n]+ torch.index_select(w, 0, ids.reshape(-1), out = y)+ if self.multiplier != 1.0:+ y *= self.multiplier+ return y.view(*ids.shape, self.hidden_size)++ def _upload_narrow(self, y: torch.Tensor, ids: torch.Tensor, out_dtype, device) -> torch.Tensor:+ """Upload the pinned 16-bit rows without blocking the host and widen on the device (exact for bf16/fp16 -> fp32, the same+ round-to-nearest the host conversion does for bf16 -> fp16). The rows stay cached for the MTP block (forward_device)."""+ d = y.to(device, non_blocking = True)+ if self._narrow_ev is None:+ self._narrow_ev = torch.cuda.Event()+ self._narrow_ev.record()+ self._dev_rows = (ids.clone(), d) # consumed by forward_device (the MTP block), else replaced by the next chunk+ return d if d.dtype == out_dtype else d.to(out_dtype)+def make_tp_allocation(self, options: dict) -> list[TPAllocation]:return []@@ -203,4 +256,4 @@ class Embedding(Module):)emb = consumer.recv(exported["embedding.weight"], cuda = False)module.embedding.weight = nn.Parameter(emb)- return module\ No newline at end of file+ return modulediff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 67005c5..f45f429 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -605,7 +605,10 @@ SERVE_ENV = (("EXL3_HOST_LEAN", "1"), ("EXL3_HOST_CUTS", "1"), # batched verifHIP_ONLY_SERVE_ENV = frozenset(("EXL3_BRANCH_CKPT", "EXL3_GDN_HF", "EXL3_MOE_WMMA_MIN_ROWS", "EXL3_NC2_ABLIT_F16", "EXL3_NC2_ASYNC_STASH","EXL3_NC2_ATTN_F16", "EXL3_GEMV_R_WIDE8", "EXL3_REPLY_FIRST", "EXL3_TAIL_DENSE", "EXL3_TAIL_MAXGAP","EXL3_TAIL_REPLY", "EXL3_TAIL_SUB", "EXL3_TOPK_PAR"))-CUDA_SERVE_ENV = (("EXL3_CUDA_GRAPH", "1"), ("EXL3_DRAFT_VOCAB", "98304"), ("QWSPEC_THF", "0.3"), ("QWSPEC_THV", "0.1"), ("QWSPEC_THFD", "0.6"), ("QWSPEC_THVD", "0.4"))+# EXL3_PF_EMB_UPLOAD: a long prefill chunk gathers the CPU-resident embedding rows straight into pinned memory in the table dtype (bf16),+# uploads them asynchronously and widens on the device (bit-identical): 94 MB of pageable fp32 per 4.5K-row chunk plus the 47 MB of the MTP+# block (~37 ms of idle GPU per chunk) become two async 47 MB copies. Served prefill 4K 1712.8 -> 1729.0, 35K 1515.7 -> 1523.8 tok/s, text identical.+CUDA_SERVE_ENV = (("EXL3_PF_EMB_UPLOAD", "1"), ("EXL3_CUDA_GRAPH", "1"), ("EXL3_DRAFT_VOCAB", "98304"), ("QWSPEC_THF", "0.3"), ("QWSPEC_THV", "0.1"), ("QWSPEC_THFD", "0.6"), ("QWSPEC_THVD", "0.4"))HC_GS_SIDECAR = "hc_gs_sidecar.safetensors"# The sidecar of the published pack. A file with another hash (wrong pack, damaged download) is not used: plain group rounding, one log line.