From 4fbc643269f87d534208fc5a98cd8959bcc7f9f9 Mon Sep 17 00:00:00 2001 From: chaofengw Date: Wed, 25 Nov 2026 05:10:27 +0000 Subject: [PATCH 1/3] fix(qwen3_5): fail the build instead of prefilling one token at a time A qwen3_5 text bundle or a qwen3_5_moe GPTQ bundle dropped its chunked prefill engine when a second weight copy did not fit in 80% of GPU memory, when the GPU could not be queried, or (qwen3_5_moe) when the prefill engine build raised. Prompts then ran through the decode engine one token at a time, which reads every weight once per prompt token. Fail the build with the needed and available sizes instead. An unknown GPU capacity now builds both engines, and a failed prefill engine build fails the bundle. NVFP4, media (qwen3_5), MTP, draft and TP2 bundles keep their single-token prefill: they have no chunked graph, which is unrelated to memory. Signed-off-by: chaofengw --- families/qwen3_5/model.py | 28 +++++------ .../qwen3_5/tests/test_chunked_prefill.py | 12 +++-- families/qwen3_5_moe/native_model.py | 45 +++++++---------- .../qwen3_5_moe/tests/test_prefill_rows.py | 50 ++++++++----------- 4 files changed, 57 insertions(+), 78 deletions(-) diff --git a/families/qwen3_5/model.py b/families/qwen3_5/model.py index f75da2fec6..1d4ba1c484 100644 --- a/families/qwen3_5/model.py +++ b/families/qwen3_5/model.py @@ -2460,21 +2460,18 @@ 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(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, which every earlier bundle had. + 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: the decode and prefill engines need about {2 * weight_bytes / 1024**3:.0f} GiB of weights " + f"and the GPU has {gpu_bytes / 1024**3:.0f} GiB; use a GPU with more memory or a smaller checkpoint") def _host_weight_bytes(weights) -> int: @@ -2617,8 +2614,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 + if split: + _require_two_engines_fit(_host_weight_bytes(weights), _gpu_memory_bytes()) # Stage the target before building the other engines; do not retain its serialized bytes. writer.add_bytes("engine.plan", model.build_engine( config, diff --git a/families/qwen3_5/tests/test_chunked_prefill.py b/families/qwen3_5/tests/test_chunked_prefill.py index 362246631b..2e6b263b91 100644 --- a/families/qwen3_5/tests/test_chunked_prefill.py +++ b/families/qwen3_5/tests/test_chunked_prefill.py @@ -205,11 +205,13 @@ 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 + model._require_two_engines_fit(18 * 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 of weights and the GPU has 121 GiB"): + model._require_two_engines_fit(54 * gib, 121 * gib) weights = {"w": np.zeros((4, 8), dtype=np.float16), "_rows": 4} assert model._host_weight_bytes(weights) == 64 diff --git a/families/qwen3_5_moe/native_model.py b/families/qwen3_5_moe/native_model.py index ecce12a158..7aeca79685 100644 --- a/families/qwen3_5_moe/native_model.py +++ b/families/qwen3_5_moe/native_model.py @@ -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: @@ -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 @@ -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, )) diff --git a/families/qwen3_5_moe/tests/test_prefill_rows.py b/families/qwen3_5_moe/tests/test_prefill_rows.py index d5e069e8e7..b31fd5fc79 100644 --- a/families/qwen3_5_moe/tests/test_prefill_rows.py +++ b/families/qwen3_5_moe/tests/test_prefill_rows.py @@ -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): @@ -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 == {} From 912a69833949bc1d22c20c5f94f57ff6e146fa29 Mon Sep 17 00:00:00 2001 From: chaofengw Date: Wed, 25 Nov 2026 06:38:26 +0000 Subject: [PATCH 2/3] fix(qwen3_5): count FP32 host weights at the engine precision in the fit check TP1 host weights keep unquantized tensors in FP32, but an FP16 engine stores them as FP16 constants. Counting the host bytes doubled the estimate, which now fails builds that fit (for example a 9B FP16 bundle on an 80 GB GPU). Count FP32 host tensors as FP16 in FP16 builds, except in the requested FP32 layers; quantized and packed tensors keep their host size. Signed-off-by: chaofengw --- families/qwen3_5/model.py | 18 +++++++++++++++--- families/qwen3_5/tests/test_chunked_prefill.py | 17 +++++++++++++++-- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/families/qwen3_5/model.py b/families/qwen3_5/model.py index 1d4ba1c484..b41f2233e7 100644 --- a/families/qwen3_5/model.py +++ b/families/qwen3_5/model.py @@ -2474,8 +2474,20 @@ def _require_two_engines_fit(weight_bytes: int, gpu_bytes: int | None) -> None: f"and the GPU has {gpu_bytes / 1024**3:.0f} GiB; use a GPU with more memory or a smaller checkpoint") -def _host_weight_bytes(weights) -> int: - return sum(value.nbytes for value in weights.values() if isinstance(value, np.ndarray)) +def _engine_weight_bytes(weights, precision: str, fp32_layers=()) -> int: + """Bytes of weights that one engine carries. + + TP1 host weights keep unquantized tensors in FP32, but an FP16 build stores them as FP16 constants, except in + the requested FP32 layers. Quantized and packed tensors keep their host size. + """ + fp32_prefixes = tuple(f"layer.{int(layer)}." for layer in fp32_layers) + total = 0 + for name, value in weights.items(): + if not isinstance(value, np.ndarray): + continue + narrowed = precision == "fp16" and value.dtype == np.float32 and not name.startswith(fp32_prefixes) + total += value.size * 2 if narrowed else value.nbytes + return total def _gpu_memory_bytes() -> int | None: @@ -2616,7 +2628,7 @@ def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mt 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 if split: - _require_two_engines_fit(_host_weight_bytes(weights), _gpu_memory_bytes()) + _require_two_engines_fit(_engine_weight_bytes(weights, precision, request.fp32_layers), _gpu_memory_bytes()) # Stage the target before building the other engines; do not retain its serialized bytes. writer.add_bytes("engine.plan", model.build_engine( config, diff --git a/families/qwen3_5/tests/test_chunked_prefill.py b/families/qwen3_5/tests/test_chunked_prefill.py index 2e6b263b91..7e91bb2a24 100644 --- a/families/qwen3_5/tests/test_chunked_prefill.py +++ b/families/qwen3_5/tests/test_chunked_prefill.py @@ -213,5 +213,18 @@ def test_a_text_bundle_whose_second_weight_copy_does_not_fit_fails_to_build() -> # 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 of weights and the GPU has 121 GiB"): model._require_two_engines_fit(54 * gib, 121 * gib) - weights = {"w": np.zeros((4, 8), dtype=np.float16), "_rows": 4} - assert model._host_weight_bytes(weights) == 64 + + +def test_the_fit_check_counts_fp32_host_weights_at_the_engine_precision() -> None: + weights = { + "embedding": np.zeros((4, 8), dtype=np.float32), + "layer.1.w_q": np.zeros((2, 2), dtype=np.float32), + "layer.10.w_q": np.zeros((2, 2), dtype=np.float32), + "layer.1.w_packed": np.zeros(4, dtype=np.int8), + "_rows": 4, + } + # An FP16 build stores the FP32 host tensors as FP16; packed tensors keep their size. + assert model._engine_weight_bytes(weights, "fp16") == 32 * 2 + 4 * 2 + 4 * 2 + 4 + # Requested FP32 layers stay FP32 (layer 1 only, not layer 10). + assert model._engine_weight_bytes(weights, "fp16", (1,)) == 32 * 2 + 4 * 4 + 4 * 2 + 4 + assert model._engine_weight_bytes(weights, "fp32") == 32 * 4 + 4 * 4 + 4 * 4 + 4 From 0b23fcad147c71e053485287b5f8a3305151419d Mon Sep 17 00:00:00 2001 From: chaofengw Date: Wed, 25 Nov 2026 07:26:50 +0000 Subject: [PATCH 3/3] fix(qwen3_5): check the fit on the built decode engine, not host weights Host weights do not match what an engine carries: TP1 keeps unquantized tensors in FP32, FP8 projections are FP16 placeholders whose payload lives in the quantization context, and prepared FP8 and AWQ projections are PreparedLinear objects. Any estimate from the weight dict is wrong for some of these, and an overestimate now fails a build that fits. Build the decode engine first and require twice its serialized size to fit; the prefill engine carries the same weights. Signed-off-by: chaofengw --- families/qwen3_5/model.py | 41 +++++++------------ .../qwen3_5/tests/test_chunked_prefill.py | 19 +-------- 2 files changed, 16 insertions(+), 44 deletions(-) diff --git a/families/qwen3_5/model.py b/families/qwen3_5/model.py index b41f2233e7..ecc8e7bcb1 100644 --- a/families/qwen3_5/model.py +++ b/families/qwen3_5/model.py @@ -2460,36 +2460,19 @@ def build(request: "BuildRequest", writer: "BundleWriter") -> None: _TWO_ENGINE_MEMORY_FRACTION = 0.8 -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. +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. - Prompts never fall back to the decode engine one token at a time to save memory. An unknown GPU capacity - builds both engines. + ``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 or 2 * weight_bytes <= gpu_bytes * _TWO_ENGINE_MEMORY_FRACTION: + 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 * weight_bytes / 1024**3:.0f} GiB of weights " + 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 _engine_weight_bytes(weights, precision: str, fp32_layers=()) -> int: - """Bytes of weights that one engine carries. - - TP1 host weights keep unquantized tensors in FP32, but an FP16 build stores them as FP16 constants, except in - the requested FP32 layers. Quantized and packed tensors keep their host size. - """ - fp32_prefixes = tuple(f"layer.{int(layer)}." for layer in fp32_layers) - total = 0 - for name, value in weights.items(): - if not isinstance(value, np.ndarray): - continue - narrowed = precision == "fp16" and value.dtype == np.float32 and not name.startswith(fp32_prefixes) - total += value.size * 2 if narrowed else value.nbytes - return total - - def _gpu_memory_bytes() -> int | None: """Total memory of the current CUDA device, or None when no device can be queried.""" try: @@ -2627,10 +2610,8 @@ def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mt # 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 - if split: - _require_two_engines_fit(_engine_weight_bytes(weights, precision, request.fp32_layers), _gpu_memory_bytes()) # 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, @@ -2641,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, diff --git a/families/qwen3_5/tests/test_chunked_prefill.py b/families/qwen3_5/tests/test_chunked_prefill.py index 7e91bb2a24..6430c07499 100644 --- a/families/qwen3_5/tests/test_chunked_prefill.py +++ b/families/qwen3_5/tests/test_chunked_prefill.py @@ -207,24 +207,9 @@ def test_triangular_solve_matches_numpy_on_nearly_parallel_keys() -> None: def test_a_text_bundle_whose_second_weight_copy_does_not_fit_fails_to_build() -> None: gib = 1024**3 - model._require_two_engines_fit(18 * gib, 121 * gib) # 9B FP16 on a 128 GB unified-memory GPU + 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 of weights and the GPU has 121 GiB"): + with pytest.raises(ValueError, match="need about 108 GiB and the GPU has 121 GiB"): model._require_two_engines_fit(54 * gib, 121 * gib) - - -def test_the_fit_check_counts_fp32_host_weights_at_the_engine_precision() -> None: - weights = { - "embedding": np.zeros((4, 8), dtype=np.float32), - "layer.1.w_q": np.zeros((2, 2), dtype=np.float32), - "layer.10.w_q": np.zeros((2, 2), dtype=np.float32), - "layer.1.w_packed": np.zeros(4, dtype=np.int8), - "_rows": 4, - } - # An FP16 build stores the FP32 host tensors as FP16; packed tensors keep their size. - assert model._engine_weight_bytes(weights, "fp16") == 32 * 2 + 4 * 2 + 4 * 2 + 4 - # Requested FP32 layers stay FP32 (layer 1 only, not layer 10). - assert model._engine_weight_bytes(weights, "fp16", (1,)) == 32 * 2 + 4 * 4 + 4 * 2 + 4 - assert model._engine_weight_bytes(weights, "fp32") == 32 * 4 + 4 * 4 + 4 * 4 + 4