"""CPU tests for dtype-aware PLE mmap gathering and checkpoint validation. Run inside the vLLM image (needs numpy + torch, no GPU): docker run --rm -v $PWD:/t -w /t --entrypoint python3 vllm/vllm-openai:qwen38-flash-next test_ple_mmap_cpu.py """ import json import os import struct import sys import tempfile import time import numpy as np import torch sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import vllm_ple_mmap as m # noqa: E402 import patch_qwen4_exp_config as config_compat # noqa: E402 import patch_qwen4_exp_quantized_lm_head as lm_head_compat # noqa: E402 import patch_parallel_lm_head_linear_attrs as lm_head_attrs # noqa: E402 source_fixture = """\ class QwenTextConfig: def __init__(self, layer_types=None, **kwargs): super().__init__(layer_types=layer_types, **kwargs) """ patched_fixture = config_compat.patch_source(source_fixture) assert 'layer_type == "qwen_sparse_attention"' in patched_fixture assert '"full_attention"' in patched_fixture assert config_compat.patch_source(patched_fixture) == patched_fixture lm_head_source_fixture = """\ self.lm_head = ParallelLMHead( config.vocab_size, config.hidden_size, prefix=maybe_prefix(prefix, "lm_head"), ) """ lm_head_patched_fixture = lm_head_compat.patch_source(lm_head_source_fixture) assert "quant_config=self.quant_config," in lm_head_patched_fixture assert 'prefix="lm_head",' in lm_head_patched_fixture assert lm_head_compat.patch_source(lm_head_patched_fixture) == lm_head_patched_fixture mtp_lm_head_source_fixture = """\ self.lm_head = ParallelLMHead( config.vocab_size, config.hidden_size, prefix=maybe_prefix(prefix, "lm_head"), ) """ mtp_lm_head_patched_fixture = lm_head_compat.patch_source(mtp_lm_head_source_fixture) assert " quant_config=self.quant_config," in mtp_lm_head_patched_fixture assert ' prefix="lm_head",' in mtp_lm_head_patched_fixture parallel_lm_head_fixture = """\ self.quant_config = quant_config if bias: self._register_bias() """ parallel_lm_head_patched = lm_head_attrs.patch_source(parallel_lm_head_fixture) assert "self.output_partition_sizes = [self.num_embeddings_per_partition]" in parallel_lm_head_patched assert "self.has_bias = bias" in parallel_lm_head_patched assert lm_head_attrs.patch_source(parallel_lm_head_patched) == parallel_lm_head_patched fp8 = m._resolve_ple_dtype("F8_E4M3") assert fp8.torch_dtype == torch.float8_e4m3fn assert fp8.itemsize == 1 and fp8.needs_scale is True assert m._row_bytes(160, fp8) == 160 bf16 = m._resolve_ple_dtype("BF16") assert bf16.torch_dtype == torch.bfloat16 assert bf16.itemsize == 2 and bf16.needs_scale is False assert m._row_bytes(160, bf16) == 320 try: m._resolve_ple_dtype("F32") raise AssertionError("unsupported PLE dtype must fail") except ValueError as exc: assert "unsupported PLE shard dtype" in str(exc) assert m._read_required_scale("BF16", None) is None try: m._read_required_scale("F8_E4M3", None) raise AssertionError("FP8 PLE without a scale must fail") except RuntimeError as exc: assert "FP8 shards without ngram_embedding.weight_scale" in str(exc) ROWS, COLS, PARTS = 100_000, 160, 8 shard_size = -(-ROWS // PARTS) rng = np.random.default_rng(0) table = rng.integers(0, 256, size=(ROWS, COLS), dtype=np.uint8) tmp = tempfile.mkdtemp() # write shards into 2 safetensors files (4 shards each) with a dummy tensor first, # so data offsets are non-trivial file_of = {} for fi in range(2): tensors = {"dummy.weight": np.arange(37, dtype=np.float32).tobytes()} header = {"dummy.weight": {"dtype": "F32", "shape": [37], "data_offsets": [0, 37 * 4]}} off = 37 * 4 for si in range(fi * 4, fi * 4 + 4): rows = table[si * shard_size : (si + 1) * shard_size] name = f"model.language_model.layers.1.ple.ple_embedding.ngram_embedding.shard_{si}.weight" header[name] = {"dtype": "F8_E4M3", "shape": list(rows.shape), "data_offsets": [off, off + rows.nbytes]} tensors[name] = rows.tobytes() off += rows.nbytes file_of[name] = f"model-plefp8-0000{fi}.safetensors" if fi == 1: name = "model.language_model.layers.1.ple.ple_embedding.ngram_embedding.weight_scale" header[name] = {"dtype": "F32", "shape": [], "data_offsets": [off, off + 4]} tensors[name] = struct.pack("7}: OK in {dt*1e3:7.2f} ms") # torch view path used by the placeholder emb = m._MmapNgramEmbedding(ROWS, COLS) emb.table = t ids_t = torch.from_numpy(rng.integers(0, ROWS, size=(300, 16), dtype=np.int64)) out = emb(ids_t) assert out.shape == (300, 16, COLS) and out.dtype == torch.float8_e4m3fn assert np.array_equal(out.view(torch.uint8).numpy().reshape(-1, COLS), table[ids_t.numpy().reshape(-1)]) print("placeholder forward: OK (fp8 view, shape", tuple(out.shape), ")") # BF16 checkpoint path: exact values, a partial final shard, cross-shard ids, # duplicates, and a non-trivial safetensors data offset. BF_ROWS, BF_COLS, BF_PARTS = 1_031, 7, 8 bf_shard_size = -(-BF_ROWS // BF_PARTS) bf_ref = ( torch.arange(BF_ROWS * BF_COLS, dtype=torch.float32) .remainder(997) .div(31) .to(torch.bfloat16) .reshape(BF_ROWS, BF_COLS) ) bf_u8 = bf_ref.view(torch.uint8).numpy().reshape(BF_ROWS, BF_COLS * 2) bf_tmp = tempfile.mkdtemp() bf_file_of = {} for fi in range(2): tensors = {"dummy.weight": np.arange(11, dtype=np.float32).tobytes()} header = { "dummy.weight": { "dtype": "F32", "shape": [11], "data_offsets": [0, 11 * 4], } } off = 11 * 4 for si in range(fi * 4, fi * 4 + 4): rows = bf_u8[si * bf_shard_size : (si + 1) * bf_shard_size] name = f"model.language_model.layers.1.ple.ple_embedding.ngram_embedding.shard_{si}.weight" header[name] = { "dtype": "BF16", "shape": [len(rows), BF_COLS], "data_offsets": [off, off + rows.nbytes], } tensors[name] = rows.tobytes() off += rows.nbytes bf_file_of[name] = f"model-plebf16-{fi}.safetensors" hb = json.dumps(header).encode() with open(os.path.join(bf_tmp, f"model-plebf16-{fi}.safetensors"), "wb") as f: f.write(struct.pack("