Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 18 additions & 21 deletions families/qwen3_5/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2460,25 +2460,17 @@ def build(request: "BuildRequest", writer: "BundleWriter") -> None:
_TWO_ENGINE_MEMORY_FRACTION = 0.8


def _two_engines_fit(weight_bytes: int, gpu_bytes: int | None) -> bool:
"""Whether the prefill engine, which carries its own copy of every weight, fits beside the decode engine.
def _require_two_engines_fit(engine_bytes: int, gpu_bytes: int | None) -> None:
"""Fail the build when the prefill engine does not fit beside the decode engine.

Without it, prompts run through the decode engine one token at a time (the bundle stays loadable). An
unknown GPU capacity keeps that single-engine layout, which every earlier bundle had.
``engine_bytes`` is the serialized decode engine; the prefill engine carries the same weights. Prompts never
fall back to the decode engine one token at a time to save memory. An unknown GPU capacity builds both engines.
"""
if gpu_bytes is None:
print("Skipping the prefill engine: the GPU memory could not be queried", file=sys.stderr)
return False
if 2 * weight_bytes <= gpu_bytes * _TWO_ENGINE_MEMORY_FRACTION:
return True
print(f"Skipping the prefill engine: the decode and prefill engines need about {2 * weight_bytes / 1024**3:.0f} "
f"GiB of weights and the GPU has {gpu_bytes / 1024**3:.0f} GiB; prompts run through the decode engine",
file=sys.stderr)
return False


def _host_weight_bytes(weights) -> int:
return sum(value.nbytes for value in weights.values() if isinstance(value, np.ndarray))
if gpu_bytes is None or 2 * engine_bytes <= gpu_bytes * _TWO_ENGINE_MEMORY_FRACTION:
return
raise ValueError(
f"qwen3_5: the decode and prefill engines need about {2 * engine_bytes / 1024**3:.0f} GiB "
f"and the GPU has {gpu_bytes / 1024**3:.0f} GiB; use a GPU with more memory or a smaller checkpoint")


def _gpu_memory_bytes() -> int | None:
Expand Down Expand Up @@ -2617,10 +2609,9 @@ def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mt
# TensorRT 11.4 cannot lower NVFP4 dynamic activation quantization over a
# runtime row count, so NVFP4 bundles keep the token loop.
nvfp4 = quantization == "nvfp4" or getattr(quant_ctx, "has_nvfp4_weights", False)
split = (not visual and not require_mtp and draft_config is None and not nvfp4
and _two_engines_fit(_host_weight_bytes(weights), _gpu_memory_bytes()))
split = not visual and not require_mtp and draft_config is None and not nvfp4
# Stage the target before building the other engines; do not retain its serialized bytes.
writer.add_bytes("engine.plan", model.build_engine(
target = model.build_engine(
config,
weights,
max_sequence_length,
Expand All @@ -2631,8 +2622,14 @@ def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mt
quant_ctx=quant_ctx,
export_hidden_state=require_mtp,
feature_layers=() if draft_config is None else draft_config.feature_layers,
))
)
target_bytes = target.nbytes
writer.add_bytes("engine.plan", target)
del target
if split:
# Measured on the built target rather than estimated from host weights, whose storage differs from the
# engine's (FP32 host copies, quantized payloads held outside the weight dict).
_require_two_engines_fit(target_bytes, _gpu_memory_bytes())
writer.add_bytes("prefill.plan", model.build_engine(
config, weights, max_sequence_length, precision=precision,
verbose=bool(request.verbose), quant_ctx=quant_ctx,
Expand Down
14 changes: 7 additions & 7 deletions families/qwen3_5/tests/test_chunked_prefill.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,11 +205,11 @@ def test_triangular_solve_matches_numpy_on_nearly_parallel_keys() -> None:
assert np.abs(got - want).max() <= 1e-4 * np.abs(want).max()


def test_the_prefill_engine_is_built_only_when_a_second_weight_copy_fits() -> None:
def test_a_text_bundle_whose_second_weight_copy_does_not_fit_fails_to_build() -> None:
gib = 1024**3
assert model._two_engines_fit(18 * gib, 121 * gib) # 9B FP16 on a 128 GB unified-memory GPU
assert not model._two_engines_fit(54 * gib, 121 * gib) # 27B FP16: the decode engine alone
assert model._two_engines_fit(54 * gib, 275 * gib)
assert not model._two_engines_fit(2 * gib, None) # no device to ask: keep the single-engine layout
weights = {"w": np.zeros((4, 8), dtype=np.float16), "_rows": 4}
assert model._host_weight_bytes(weights) == 64
model._require_two_engines_fit(17 * gib, 121 * gib) # 9B FP16 on a 128 GB unified-memory GPU
model._require_two_engines_fit(54 * gib, 275 * gib)
model._require_two_engines_fit(2 * gib, None) # no device to ask: build both engines
# 27B FP16 on 128 GB: never fall back to a one-token-at-a-time prompt prefill.
with pytest.raises(ValueError, match="need about 108 GiB and the GPU has 121 GiB"):
model._require_two_engines_fit(54 * gib, 121 * gib)
45 changes: 17 additions & 28 deletions families/qwen3_5_moe/native_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2382,21 +2382,19 @@ def _runtime_config(model_dir: Path, config: ModelConfig, model: _Qwen35MoeModel
_TWO_ENGINE_MEMORY_FRACTION = 0.8


def _two_engines_fit(weight_bytes: int, gpu_bytes: int | None) -> bool:
"""Whether the prefill engine, which carries its own copy of every weight, fits beside the decode engine.
def _require_two_engines_fit(weight_bytes: int, gpu_bytes: int | None) -> None:
"""Fail the build when the prefill engine, which carries its own copy of every weight, does not fit beside
the decode engine.

Without it, prompts run through the decode engine one token at a time (the bundle stays loadable). An
unknown GPU capacity keeps that single-engine layout.
Prompts never fall back to the decode engine one token at a time to save memory. An unknown GPU capacity
builds both engines.
"""
if gpu_bytes is None:
print("Skipping the prefill engine: the GPU memory could not be queried", file=sys.stderr)
return False
if 2 * weight_bytes <= gpu_bytes * _TWO_ENGINE_MEMORY_FRACTION:
return True
print(f"Skipping the prefill engine: the decode and prefill engines need about {2 * weight_bytes / 1024**3:.0f} "
f"GiB of weights and the GPU has {gpu_bytes / 1024**3:.0f} GiB; prompts run through the decode engine",
file=sys.stderr)
return False
if gpu_bytes is None or 2 * weight_bytes <= gpu_bytes * _TWO_ENGINE_MEMORY_FRACTION:
return
raise ValueError(
f"qwen3_5_moe: the decode and prefill engines need about {2 * weight_bytes / 1024**3:.0f} GiB of "
f"weights and the GPU has {gpu_bytes / 1024**3:.0f} GiB; use a GPU with more memory or a smaller "
"checkpoint")


def _checkpoint_bytes(readers) -> int:
Expand All @@ -2406,22 +2404,13 @@ def _checkpoint_bytes(readers) -> int:

def _wants_prefill_engine(weights, readers, *, tensor_parallel_size: int, require_mtp: bool,
has_draft: bool) -> bool:
"""Whether the bundle adds the chunked prefill engine: single-GPU GPTQ without MTP or a draft, if it fits."""
return (not require_mtp and not has_draft and tensor_parallel_size == 1
and _dense_prefill_experts(weights)
and _two_engines_fit(_checkpoint_bytes(readers), _gpu_memory_bytes()))

"""Whether the bundle adds the chunked prefill engine: single-GPU GPTQ without MTP or a draft.

def _stage_prefill_engine(writer, build) -> bool:
"""Stage ``prefill.plan`` from ``build()``. The engine is optional: if its build fails, the bundle keeps
the single-engine layout and prompts run through the decode engine."""
try:
plan = build()
except (RuntimeError, MemoryError) as error:
print(f"Skipping the prefill engine: its build failed ({error}); prompts run through the decode engine",
file=sys.stderr)
Such a bundle fails to build when the engine's second weight copy does not fit.
"""
if require_mtp or has_draft or tensor_parallel_size != 1 or not _dense_prefill_experts(weights):
return False
writer.add_bytes("prefill.plan", plan)
_require_two_engines_fit(_checkpoint_bytes(readers), _gpu_memory_bytes())
return True


Expand Down Expand Up @@ -2545,7 +2534,7 @@ def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mt
del plan # The section is staged; do not retain a full plan during the next build.
if split:
try:
split = _stage_prefill_engine(writer, lambda: model.build_engine(
writer.add_bytes("prefill.plan", model.build_engine(
config, weights, max_sequence_length, precision=precision,
verbose=bool(request.verbose), media_inputs=visual, prefill_rows=PREFILL_MAX_TOKENS,
))
Expand Down
50 changes: 20 additions & 30 deletions families/qwen3_5_moe/tests/test_prefill_rows.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,22 +137,23 @@ def one(network, x):
np.testing.assert_array_equal(got[[row, ROWS + row]], want)


def test_the_prefill_engine_is_built_only_when_a_second_weight_copy_fits():
def test_a_bundle_whose_second_weight_copy_does_not_fit_fails_to_build():
gib = 1024**3
assert native_model._two_engines_fit(20 * gib, 121 * gib) # 35B-A3B GPTQ on a 128 GB unified-memory GPU
assert not native_model._two_engines_fit(67 * gib, 121 * gib) # the BF16 original: decode engine alone
assert not native_model._two_engines_fit(2 * gib, None) # no device to ask: keep the single-engine layout
native_model._require_two_engines_fit(20 * gib, 121 * gib) # 35B-A3B GPTQ on a 128 GB unified-memory GPU
native_model._require_two_engines_fit(2 * gib, None) # no device to ask: build both engines
# Never fall back to a one-token-at-a-time prompt prefill.
with pytest.raises(ValueError, match="need about 134 GiB of weights and the GPU has 121 GiB"):
native_model._require_two_engines_fit(67 * gib, 121 * gib)


@pytest.mark.parametrize(
("gpu_gib", "options", "wanted"),
[
(121, {}, True),
(30, {}, False),
(None, {}, False),
(121, {"require_mtp": True}, False),
(121, {"has_draft": True}, False),
(121, {"tensor_parallel_size": 2}, False),
(None, {}, True),
(30, {"require_mtp": True}, False),
(30, {"has_draft": True}, False),
(30, {"tensor_parallel_size": 2}, False),
],
)
def test_the_split_decision_uses_the_mapped_shards_and_the_gpu_memory(monkeypatch, gpu_gib, options, wanted):
Expand All @@ -165,30 +166,19 @@ def test_the_split_decision_uses_the_mapped_shards_and_the_gpu_memory(monkeypatc
assert native_model._wants_prefill_engine(weights, readers, **arguments) is wanted


def test_a_gptq_bundle_that_cannot_hold_the_prefill_engine_fails_to_build(monkeypatch):
gib = 1024**3
readers = [SimpleNamespace(mapping=_Sized(20 * gib))]
weights = {"layer.0.moe": _experts(np.random.default_rng(3))}
monkeypatch.setattr(native_model, "_gpu_memory_bytes", lambda: 30 * gib)
with pytest.raises(ValueError, match="the GPU has 30 GiB"):
native_model._wants_prefill_engine(weights, readers, tensor_parallel_size=1, require_mtp=False,
has_draft=False)


class _Sized:
def __init__(self, size: int):
self.size = size

def __len__(self) -> int:
return self.size


class _RecordingWriter:
def __init__(self):
self.sections: dict[str, object] = {}

def add_bytes(self, name: str, data) -> None:
self.sections[name] = data


def test_a_failed_prefill_build_keeps_the_single_engine_bundle():
writer = _RecordingWriter()
assert native_model._stage_prefill_engine(writer, lambda: b"plan")
assert writer.sections == {"prefill.plan": b"plan"}

def failed():
raise RuntimeError("TensorRT engine build failed")

writer = _RecordingWriter()
assert not native_model._stage_prefill_engine(writer, failed)
assert writer.sections == {}
Loading