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
Embedding on the CPU: map the table from the safetensors file instead of holding an anonymous copy
YanissAmz1f5cd8706f3f
diff --git a/exllamav3/loader/safetensors.py b/exllamav3/loader/safetensors.pyindex 044e96a..d8fd38c 100644--- a/exllamav3/loader/safetensors.py+++ b/exllamav3/loader/safetensors.py@@ -584,6 +584,28 @@ class SafetensorsCollection:}+ def get_tensor_mmap(self, key: str) -> torch.Tensor | None:+ """+ Map a bf16/fp16 tensor straight from its file (private copy-on-write mapping, nothing is copied).+ The pages live in the page cache, so unlike a loaded copy they count as reclaimable file memory+ instead of anonymous RSS. Returns None when the key is not a plain file tensor of such a dtype.+ """+ import numpy as np+ if self.new_tensors and key in self.new_tensors:+ return None+ filename = self.tensor_file_map.get(key)+ if filename is None:+ return None+ header = self.file_headers[filename]+ h = header[key]+ dtype, np_dtype, esize = convert_dtype(h["dtype"])+ if dtype not in (torch.bfloat16, torch.float16):+ return None+ shape = tuple(h["shape"])+ mm = np.memmap(filename, dtype = np.int16, mode = "c", offset = header["_header_offset"] + h["data_offsets"][0],+ shape = (math.prod(shape),))+ return torch.from_numpy(mm).view(dtype).reshape(shape)+def get_tensor_handle(self,key: str,diff --git a/exllamav3/modules/embedding.py b/exllamav3/modules/embedding.pyindex eec0ce8..5c8459a 100644--- a/exllamav3/modules/embedding.py+++ b/exllamav3/modules/embedding.py@@ -1,4 +1,5 @@from __future__ import annotations+import osfrom typing_extensions import overrideimport osimport torch@@ -47,7 +48,12 @@ class Embedding(Module):@overridedef load(self, device: torch.device, **kwargs):self.device = device- weight = self.config.stc.get_tensor(self.key + ".weight", self.device, float2half = True, allow_bf16 = True)+ weight = None+ if self.device.type == "cpu" and os.environ.get("EXL3_EMB_MMAP", "1") != "0" and hasattr(self.config.stc, "get_tensor_mmap"):+ # The table is only gathered from: map it from the file (page cache) rather than holding a 2+ GiB anonymous copy+ weight = self.config.stc.get_tensor_mmap(self.key + ".weight")+ if weight is None:+ weight = self.config.stc.get_tensor(self.key + ".weight", self.device, float2half = True, allow_bf16 = True)self._numel = weight.numel()self.embedding = nn.Embedding(self.vocab_size,diff --git a/tests/test_embedding_mmap.py b/tests/test_embedding_mmap.pynew file mode 100644index 0000000..06d4afb--- /dev/null+++ b/tests/test_embedding_mmap.py@@ -0,0 +1,29 @@+import os, torch+from safetensors.torch import save_file+from exllamav3.loader.safetensors import SafetensorsCollection+++def _anon_kib():+ for l in open("/proc/self/status"):+ if l.startswith("RssAnon:"):+ return int(l.split()[1])+++def test_mmap_tensor_equals_loaded_and_costs_no_anonymous_memory(tmp_path):+ w = torch.randn(40000, 256).to(torch.bfloat16) # 20 MB+ other = torch.arange(10, dtype = torch.float32)+ save_file({"a.weight": w, "b": other}, str(tmp_path / "m.safetensors"))+ stc = SafetensorsCollection(str(tmp_path))+ before = _anon_kib()+ t = stc.get_tensor_mmap("a.weight")+ ids = torch.tensor([0, 7, 39999, 123])+ assert t.dtype == torch.bfloat16 and t.shape == w.shape+ assert torch.equal(torch.nn.functional.embedding(ids, t), w[ids])+ assert _anon_kib() - before < 8000 # the 20 MB table is not copied into anonymous memory+ assert torch.equal(t, stc.get_tensor("a.weight", torch.device("cpu"), allow_bf16 = True))+ t2 = t.clone() # private mapping: writes never reach the file+ t[0] += 1+ assert torch.equal(stc.get_tensor_mmap("a.weight"), w)+ assert stc.get_tensor_mmap("b") is None # fp32: not eligible, falls back to the normal load+ assert stc.get_tensor_mmap("missing") is None+ del t2