Skip to content

Commit 2c984cf

Browse files
devopsfortunatoashhart
authored andcommitted
perf: Flash Next reads a prompt chunk's n-gram rows on 16 threads, same bytes
HostTable.gather copied a prompt's n-gram rows with one fancy index per file, so rows whose pages were not in the page cache were read from disk one page fault at a time. On a DGX Spark with a 131,072-token cache the ~31 GB tables barely fit in the page cache, and how much of them the start-up prefetch leaves cached varies from start to start. A gather of 1,024 rows or more (a prompt chunk of 64 tokens or more) now copies on up to 16 threads, 512 rows or more each. numpy's fancy indexing releases the GIL, so the page faults overlap: staging costs about 0.07 ms a fault instead of 0.25 ms. Decode steps keep the single-threaded copy. The bytes are the same. One Spark, 131,072-token cache, default 2,048-row chunks, a fresh process each with the n-gram files dropped from the page cache before it (the start-up prefetch refills what fits), release and branch alternated, every prompt new text: 606 tokens 0.37-0.55 -> 0.36-0.42 s, 1,118 tokens 0.56-0.73 -> 0.55-0.59 s, 4,186 tokens 1.95-2.31 -> 1.92-1.97 s, 8,192 tokens 3.65-4.29 -> 3.60-3.70 s, 32,768 tokens 15.1-16.5 -> 15.1-15.2 s, 120,000 tokens 65.4-65.7 -> 64.7-65.3 s. Decode unchanged. Checked: the threaded copy is byte-identical to the single-threaded one (new test, and 1,000 to 131,072 random rows of the real table); teacher-forced NLL through the prompt and the decode path identical to the release on all 119,980 values; 55 replayed benchmark replies byte-identical; drafted vs serial 9/9; needles 9/9.
1 parent b4042e8 commit 2c984cf

2 files changed

Lines changed: 41 additions & 3 deletions

File tree

‎src/tensorfold/families/qwen4_exp/host_table.py‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import json
66
import os
77
import struct
8+
from concurrent.futures import ThreadPoolExecutor
89
from pathlib import Path
910
from typing import Any
1011

@@ -13,6 +14,12 @@
1314
from tensorfold.families.qwen4_exp.ssd_table import SSDTable
1415

1516
_PARTS = ("weight", "scales", "biases")
17+
# A prompt chunk's gather (2 GATHER_SPLIT rows or more) copies them on up to GATHER_THREADS threads, GATHER_SPLIT
18+
# rows or more each: numpy's fancy indexing releases the GIL, so rows whose pages are not in the page cache are read
19+
# from disk in parallel instead of one page fault at a time. The bytes are the same; a decode step's few rows (and
20+
# GATHER_THREADS 1) keep the single-threaded copy.
21+
GATHER_THREADS = 16
22+
GATHER_SPLIT = 512
1623

1724

1825
def ngrams_on_host(model_dir: Path, ssd: bool = False) -> bool:
@@ -61,6 +68,8 @@ def __init__(self, files: list[tuple[Path, dict, dict, dict]]) -> None:
6168
self.wbase, self.sbase, self.bbase = (np.array(x, dtype=np.int64) for x in (wbase, sbase, bbase))
6269
self.wrow = self.words[0].shape[1] * 4
6370
self.grow = self.scales[0].shape[1] * 2
71+
# threads start with the first threaded gather
72+
self._pool = ThreadPoolExecutor(GATHER_THREADS, thread_name_prefix="ngram-gather")
6473

6574
def gather(self, ids: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
6675
"""Rows ``ids`` (global) -> words [n, W] uint32, scales and biases [n, G] (bf16 bits as uint16)."""
@@ -77,12 +86,23 @@ def gather(self, ids: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
7786
sc = np.empty((n, self.grow), dtype=np.uint8)
7887
bi = np.empty((n, self.grow), dtype=np.uint8)
7988
aw, ag = np.arange(self.wrow), np.arange(self.grow)
80-
for f in np.unique(where):
81-
at = np.nonzero(where == f)[0]
82-
mm = self.files[f]
89+
90+
def copy(job) -> None:
91+
mm, at = job
8392
w[at] = mm[wo[at, None] + aw]
8493
sc[at] = mm[so[at, None] + ag]
8594
bi[at] = mm[bo[at, None] + ag]
95+
96+
if GATHER_THREADS > 1 and n >= 2 * GATHER_SPLIT: # a prompt chunk: copy on threads
97+
jobs = []
98+
for f in np.unique(where):
99+
at = np.nonzero(where == f)[0]
100+
parts = max(1, min(GATHER_THREADS, len(at) // GATHER_SPLIT))
101+
jobs += [(self.files[f], piece) for piece in np.array_split(at, parts)]
102+
list(self._pool.map(copy, jobs))
103+
else:
104+
for f in np.unique(where):
105+
copy((self.files[f], np.nonzero(where == f)[0]))
86106
return w.view(np.uint32), sc.view(np.uint16), bi.view(np.uint16)
87107

88108
def lock(self) -> bool:

‎tests/test_ple_ssd.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,24 @@ def test_rows_from_ssd_equal_the_memory_map_byte_for_byte(tmp_path, tables, inte
105105
_same(ssd.gather(ids), want)
106106

107107

108+
@pytest.mark.parametrize("threads", [1, 2, 16])
109+
def test_a_prompt_chunks_gather_on_threads_gives_the_same_bytes(tmp_path, monkeypatch, threads):
110+
"""A gather past 2 GATHER_SPLIT rows copies its rows on GATHER_THREADS threads: the bytes of one thread."""
111+
112+
files, table = _checkpoint(tmp_path)
113+
monkeypatch.setattr(host_table, "GATHER_THREADS", threads)
114+
monkeypatch.setattr(host_table, "GATHER_SPLIT", 8) # the test shards are small: split every 8 rows
115+
host = HostTable(files)
116+
calls = []
117+
real = host._pool.map
118+
monkeypatch.setattr(host._pool, "map", lambda fn, jobs: calls.append(len(jobs)) or real(fn, jobs))
119+
for ids in (np.random.default_rng(5).integers(0, host.rows, (40, 16)), # 640 rows: threaded when threads > 1
120+
np.arange(host.rows)[::-1], np.array([3, 3, 1]), []): # every row reversed; a few; none
121+
flat = np.asarray(ids, dtype=np.int64).reshape(-1)
122+
_same(host.gather(ids), tuple(part[flat] for part in table))
123+
assert (len(calls) > 0) == (threads > 1)
124+
125+
108126
def test_from_checkpoint_picks_the_reader_by_argument_not_environment(tmp_path, monkeypatch):
109127
_, table = _checkpoint(tmp_path)
110128
monkeypatch.setenv("TF_NGRAM_HOST", "0")

0 commit comments

Comments
 (0)