Skip to content

Commit ac3de87

Browse files
committed
feat: DeepSeek-V4-Flash on Macs, faster Flash Next prompts on M1-M4, and stack dumps while serving
- DeepSeek-V4-Flash as the deepseek_v4 family on MLX: compressed sparse attention, mxfp4 experts, hyper-connections, DeepSeek's own prompt encoder and DSML tool calls, with DSpark or MTP draft heads converted from DeepSeek's releases. Replies equal "draft": false ones. Recipe: docs/recipes/deepseek-v4-flash.md. - Flash Next's prompt path on M1-M4: block scores as one batched matmul, two query heads a simdgroup in the GQA kernel and a simdgroup scan for the top-512 cuts; a one-row chunk keeps the indexer's product. Same bits. - kill -USR1 prints every thread's stack while serving too: armed again after the CUDA engine's warmup and after each request, since an in-process compiler takes the signal when it first loads. - The CUDA tool-call tests expect typed values as on the Mac, the null-parameter HTTP tests skip without MLX, a prepared request names its defaulted fields, and the docs say to restart both ranks after a generation error. Fixes #14.
1 parent fe2b514 commit ac3de87

48 files changed

Lines changed: 4821 additions & 70 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ pythonpath = ["src", "tests"]
6666

6767
[tool.ruff]
6868
line-length = 120
69+
extend-exclude = ["src/tensorfold/families/deepseek_v4/vendor"] # third-party code kept unmodified
6970

7071
[tool.setuptools.dynamic]
7172
version = { attr = "tensorfold.__version__" }

‎src/tensorfold/cli.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from typing import Any
1414

1515
from tensorfold import __version__
16+
from tensorfold.server import stacks
1617
from tensorfold.server.memory_budget import MEMORY_FRACTION
1718
from tensorfold.serve_options import check as _check_serve_options, vision_options as _vision_options
1819

@@ -359,6 +360,7 @@ def _serve_cuda(args: argparse.Namespace, family: Any, model_dir: Path, context:
359360
where = f", rank {args.rank} of 2" if args.tp == 2 else ""
360361
print(f"[tensorfold] loading {served}: {family.title} ({family.model_type}) on CUDA{where}", flush=True)
361362
engine = family.package.cuda_engine(model_dir, **options)
363+
stacks.arm() # its warmup may have loaded a compiler that took USR1
362364
if args.tp == 2 and args.rank == 1:
363365
print(f"[tensorfold] rank 1 ready in {time.perf_counter() - started:.1f}s, following rank 0", flush=True)
364366
engine.follow()
@@ -435,10 +437,7 @@ def cmd_serve(args: argparse.Namespace) -> int:
435437
if needs_full_snapshot and check is not None:
436438
check(model_dir) # checks that need the complete index, such as an MTP head
437439

438-
# `kill -USR1 <pid>` prints every thread's Python stack: the way to see where a silent server waits
439-
import faulthandler
440-
441-
faulthandler.register(signal.SIGUSR1, all_threads=True)
440+
stacks.start() # `kill -USR1 <pid>` prints every thread's Python stack: where a silent server waits
442441
if backend == "cuda":
443442
return _serve_cuda(args, family, model_dir, context)
444443
for key, value in getattr(family.package, "MLX_ENV", {}).items():

‎src/tensorfold/cuda/server.py‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@
1111
from datetime import datetime
1212
from contextlib import nullcontext
1313
from dataclasses import dataclass
14-
from http.server import BaseHTTPRequestHandler
1514
from pathlib import Path
1615
from typing import Any, Callable
1716

1817
from tensorfold.server.cancellation import RequestCancelled, socket_cancellation
1918
from tensorfold.server.errors import CapacityError, RequestError
2019
from tensorfold.server.http import Server
20+
from tensorfold.server.stacks import Rearming
2121
from tensorfold.server.messages import (_normalize_tool_call_arguments, late_system_role, normalize_messages,
2222
validate_modalities)
2323
from tensorfold.server.request_options import parse_numbers
@@ -205,7 +205,8 @@ def render(messages: list[dict[str, Any]], **images: bool) -> str: # text rend
205205
lambda messages: render(messages, allow_images=True),
206206
context_limit=self._context_limit())
207207
return PreparedRequest(rendered.tokens, max_tokens, tools, thinking,
208-
self.sampling_for(body, rendered.tokens), ignore_eos, stop, rendered.vision)
208+
self.sampling_for(body, rendered.tokens), ignore_eos=ignore_eos, stop=stop,
209+
vision=rendered.vision)
209210
text = render(body["messages"])
210211
else:
211212
text = body.get("prompt")
@@ -215,7 +216,8 @@ def render(messages: list[dict[str, Any]], **images: bool) -> str: # text rend
215216
if not prompt:
216217
raise RequestError("rendered prompt is empty")
217218
# sampling is resolved here, so a malformed control is refused before a stream opens
218-
return PreparedRequest(prompt, max_tokens, tools, thinking, self.sampling_for(body, prompt), ignore_eos, stop)
219+
return PreparedRequest(prompt, max_tokens, tools, thinking, self.sampling_for(body, prompt),
220+
ignore_eos=ignore_eos, stop=stop)
219221

220222
def check(self, body: dict[str, Any], *, prepared: PreparedRequest | None = None) -> str | None:
221223
"""Why the request cannot run, or None; rendered before a stream's headers are sent."""
@@ -427,7 +429,7 @@ def _log_error(exc: BaseException) -> None:
427429

428430

429431
def make_handler(app: App):
430-
class Handler(BaseHTTPRequestHandler):
432+
class Handler(Rearming): # USR1's stack dump armed again after each request
431433
protocol_version = "HTTP/1.1"
432434

433435
def log_message(self, fmt, *args): # quiet

‎src/tensorfold/engine/prefill_plan.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ def between(self, begin: int, end: int) -> list[tuple[int, int]]:
102102
def message_markers(tokenizer: Any) -> tuple[tuple[int, ...], tuple[int, ...]]:
103103
"""(the special tokens that open a message, the tokens that open an assistant message) in this chat template."""
104104

105+
if getattr(type(tokenizer), "message_markers", None) is not None: # markers the probe cannot see (not special)
106+
return tokenizer.message_markers
105107
from tensorfold.server.text import render_prompt_ids, template_late_system
106108

107109
decoder = getattr(tokenizer, "added_tokens_decoder", None) or {}
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
"""DeepSeek-V4-Flash (model_type ``deepseek_v4``): an MLX engine on a 256 GB Mac."""
2+
3+
from __future__ import annotations
4+
5+
from pathlib import Path
6+
from typing import Any
7+
8+
MODEL_TYPES = ("deepseek_v4",)
9+
TITLE = "DeepSeek-V4-Flash"
10+
LANES = True
11+
# affine 4-bit groups of 64, routed experts in mxfp4 (DeepSeek's own FP4 bytes)
12+
MODELS = ("mlx-community/DeepSeek-V4-Flash-4bit",)
13+
KERNEL_PACKAGE = "tensorfold.kernels.deepseek.v4"
14+
KERNEL_VERSION = "v1"
15+
# the shared GLM-5.3 pieces this engine runs (hyper-connections, row linears), hashed into snapshot keys
16+
KERNEL_DEPENDENCIES = ("tensorfold.kernels.glm.flash.v1", "tensorfold.families.glm5_next.linear",
17+
"tensorfold.families.glm5_next.model")
18+
QUANT_METHODS = {"mlx": ("mlx",)}
19+
# buffers of 200 ops and 200 MB, so a prompt chunk's memory frees as it runs; no TF32: row kernels repeat fp32
20+
MLX_ENV = {"MLX_MAX_OPS_PER_BUFFER": "200", "MLX_MAX_MB_PER_BUFFER": "200", "MLX_ENABLE_TF32": "0"}
21+
LEAST_MLX = (0, 32, 2)
22+
23+
24+
def check(model_dir: str | Path) -> None:
25+
"""Refuse what the engine does not read, from config.json alone (MLX is not imported here)."""
26+
27+
import sys
28+
29+
from tensorfold.families import OWN_MODEL_HELP, read_config
30+
from tensorfold.families.deepseek_v4.config import Config
31+
from tensorfold.families.deepseek_v4.weights import unreadable
32+
33+
config = read_config(model_dir)
34+
Config.from_dict(config)
35+
bad = unreadable(config)
36+
if bad:
37+
raise ValueError(f"DeepSeek-V4-Flash's Mac engine reads MLX affine 4-bit weights in groups of 64 and mxfp4 "
38+
f"routed experts ({MODELS[0]}); this checkpoint stores {len(bad)} module(s) otherwise, "
39+
f"{bad[0]} first. {OWN_MODEL_HELP}")
40+
if sys.platform == "darwin":
41+
_require_mlx(LEAST_MLX)
42+
43+
44+
def _require_mlx(least: tuple[int, ...]) -> None:
45+
import re
46+
from importlib.metadata import PackageNotFoundError, version
47+
48+
try:
49+
found = version("mlx")
50+
except PackageNotFoundError:
51+
return
52+
if tuple(int(p) for p in re.findall(r"\d+", found)[:3]) < least:
53+
need = ".".join(str(p) for p in least)
54+
raise ValueError(f"DeepSeek-V4-Flash needs MLX {need} or later (this is {found}): install it with "
55+
f"python -m pip install \"mlx>={need}\"")
56+
57+
58+
def load(model_dir: Path, **options: Any) -> tuple[Any, Any]:
59+
"""The MLX engine and its tokenizer."""
60+
61+
import mlx.core as mx
62+
63+
from tensorfold.families.deepseek_v4.runtime import load as load_runtime
64+
65+
# about 152 GB of weights on a 256 GB Mac: keep them wired, or macOS can page them out between steps
66+
if mx.metal.is_available():
67+
limit = int(mx.device_info().get("max_recommended_working_set_size", 0))
68+
if limit:
69+
mx.set_wired_limit(limit)
70+
return load_runtime(Path(model_dir), **options)
71+
72+
73+
def engine_settings(model: Any) -> dict[str, Any]:
74+
"""Rows a round verifies at most: the widest window checked exact at load."""
75+
76+
width = int(getattr(model, "exact_width", 1) or 1)
77+
return {"max_rows": width, "max_draft": max(0, width - 1)}
78+
79+
80+
def kernel_version(model: Any) -> str:
81+
"""Names the kernels behind a prefix snapshot: this engine's, its kernels' and the shared GLM pieces' sources."""
82+
83+
import hashlib
84+
import importlib
85+
86+
import mlx.core as mx
87+
88+
digest = hashlib.sha256()
89+
for module in (__name__, KERNEL_PACKAGE, *KERNEL_DEPENDENCIES):
90+
source = Path(str(importlib.import_module(module).__file__))
91+
paths = sorted(source.parent.glob("*.py")) if source.name == "__init__.py" else [source]
92+
for path in paths:
93+
digest.update(path.relative_to(source.parent).as_posix().encode())
94+
digest.update(path.read_bytes())
95+
digest.update(mx.__version__.encode())
96+
return f"{MODEL_TYPES[0]}-{KERNEL_VERSION}-" + digest.hexdigest()[:12]

0 commit comments

Comments
 (0)