|
| 1 | +"""Flash Next startup counts file-backed n-grams separately, without loading checkpoint tensors or MLX.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import struct |
| 7 | +import sys |
| 8 | +from types import ModuleType, SimpleNamespace |
| 9 | + |
| 10 | +import pytest |
| 11 | + |
| 12 | +from tensorfold import cli |
| 13 | +from tensorfold.families import qwen4_exp |
| 14 | +from tensorfold.families.qwen4_exp import host_table |
| 15 | +from tensorfold.server import memory_budget |
| 16 | + |
| 17 | +GIB = 1024**3 |
| 18 | +NGRAM = "language_model.model.layers.1.ple.ple_embedding.ngram_embedding" |
| 19 | + |
| 20 | + |
| 21 | +def _file(path, tensors): |
| 22 | + header = {"__metadata__": {"format": "mlx"}} |
| 23 | + offset = 0 |
| 24 | + for name, size in tensors.items(): |
| 25 | + header[name] = {"dtype": "U8", "shape": [size], "data_offsets": [offset, offset + size]} |
| 26 | + offset += size |
| 27 | + data = json.dumps(header).encode() |
| 28 | + data += b" " * (-len(data) % 8) |
| 29 | + with path.open("wb") as stream: |
| 30 | + stream.write(struct.pack("<Q", len(data))) |
| 31 | + stream.write(data) |
| 32 | + stream.truncate(8 + len(data) + offset) # sparse: only headers take disk space |
| 33 | + return path.stat().st_size |
| 34 | + |
| 35 | + |
| 36 | +def _checkpoint(path, main=4096, mapped=1600): |
| 37 | + (path / "config.json").write_text(json.dumps({ |
| 38 | + "model_type": "qwen4_exp", "quantization": {"bits": 4, "group_size": 32}, |
| 39 | + "max_position_embeddings": 262144, |
| 40 | + })) |
| 41 | + total = 0 |
| 42 | + for shard in range(2): |
| 43 | + total += _file(path / f"model-{shard}.safetensors", { |
| 44 | + f"{NGRAM}.shard_{shard}.weight": mapped * 2 // 5, |
| 45 | + f"{NGRAM}.shard_{shard}.scales": mapped // 20, |
| 46 | + f"{NGRAM}.shard_{shard}.biases": mapped // 20, |
| 47 | + f"language_model.model.layers.{shard}.ple.key_proj.weight": main // 2, |
| 48 | + }) |
| 49 | + total += _file(path / "mtp.safetensors", {"language_model.mtp.fc_hidden.weight": 64}) |
| 50 | + return total |
| 51 | + |
| 52 | + |
| 53 | +@pytest.fixture |
| 54 | +def runtime(monkeypatch): |
| 55 | + core = ModuleType("mlx.core") |
| 56 | + core.device_info = lambda: {"max_recommended_working_set_size": 120 * GIB} |
| 57 | + core.set_memory_limit = lambda value: None |
| 58 | + core.set_cache_limit = lambda value: None |
| 59 | + mlx = ModuleType("mlx") |
| 60 | + mlx.core = core |
| 61 | + monkeypatch.setitem(sys.modules, "mlx", mlx) |
| 62 | + monkeypatch.setitem(sys.modules, "mlx.core", core) |
| 63 | + monkeypatch.delenv("TF_NGRAM_HOST", raising=False) |
| 64 | + monkeypatch.delenv("TENSORFOLD_MEMORY_LIMIT_GB", raising=False) |
| 65 | + monkeypatch.setattr(memory_budget, "physical_memory_bytes", lambda: 128 * GIB) |
| 66 | + monkeypatch.setattr("faulthandler.register", lambda *a, **k: None) |
| 67 | + return core |
| 68 | + |
| 69 | + |
| 70 | +@pytest.mark.parametrize("flag, fits", [(None, True), ("1", True), ("0", False)]) |
| 71 | +def test_serve_fits_host_ngrams_within_the_original_budget(tmp_path, monkeypatch, runtime, flag, fits): |
| 72 | + _checkpoint(tmp_path, main=75 * GIB, mapped=30 * GIB) |
| 73 | + if flag is not None: |
| 74 | + monkeypatch.setenv("TF_NGRAM_HOST", flag) |
| 75 | + budgets = [] |
| 76 | + monkeypatch.setattr(cli, "_serve_mlx", lambda args, family, path, context, required, budget, *rest: |
| 77 | + budgets.append(budget) or 0) |
| 78 | + args = cli.build_parser().parse_args(["serve", str(tmp_path), "--backend", "mlx", "--no-update-check"]) |
| 79 | + if fits: |
| 80 | + assert cli.cmd_serve(args) == 0 |
| 81 | + assert budgets == [int(0.70 * 128 * GIB)] |
| 82 | + else: |
| 83 | + with pytest.raises(ValueError, match=r"weights \(105\.0 GiB\) do not fit.*89\.6 GiB"): |
| 84 | + cli.cmd_serve(args) |
| 85 | + assert budgets == [] |
| 86 | + |
| 87 | + |
| 88 | +@pytest.mark.parametrize("flag", [None, "1"]) |
| 89 | +def test_host_mode_still_refuses_resident_weights_past_the_limit(tmp_path, monkeypatch, runtime, flag): |
| 90 | + _checkpoint(tmp_path, main=75 * GIB, mapped=30 * GIB) |
| 91 | + monkeypatch.setenv("TENSORFOLD_MEMORY_LIMIT_GB", "78") # exactly 75 GiB for buffers, no room for the head |
| 92 | + if flag is not None: |
| 93 | + monkeypatch.setenv("TF_NGRAM_HOST", flag) |
| 94 | + monkeypatch.setattr(cli, "_serve_mlx", lambda *a: pytest.fail("weights loaded past the budget")) |
| 95 | + args = cli.build_parser().parse_args(["serve", str(tmp_path), "--backend", "mlx", "--no-update-check"]) |
| 96 | + with pytest.raises(ValueError, match=r"weights \(75\.0 GiB\) do not fit.*78\.0 GiB"): |
| 97 | + cli.cmd_serve(args) |
| 98 | + |
| 99 | + |
| 100 | +def test_only_mapped_table_tensors_are_subtracted(tmp_path, monkeypatch, runtime): |
| 101 | + total = _checkpoint(tmp_path) |
| 102 | + total += _file(tmp_path / "model-extra.safetensors", { |
| 103 | + f"{NGRAM}.shard_0.unrecognized": 128, |
| 104 | + "vision.ple_embedding.ngram_embedding.shard_0.weight": 256, |
| 105 | + "language_model.model.layers.1.ple.ple_embedding.ngram_heads_offsets": 64, |
| 106 | + }) |
| 107 | + total += _file(tmp_path / "unused.safetensors", {f"{NGRAM}.shard_9.weight": 512}) |
| 108 | + monkeypatch.setenv("TF_NGRAM_HOST", "1") |
| 109 | + assert qwen4_exp.weight_bytes(tmp_path) == total - 1600 |
| 110 | + monkeypatch.setenv("TF_NGRAM_HOST", "0") |
| 111 | + monkeypatch.setattr(host_table, "read_header", lambda *a: pytest.fail("resident tables need no header scan")) |
| 112 | + assert qwen4_exp.weight_bytes(tmp_path) == total |
| 113 | + |
| 114 | + |
| 115 | +@pytest.mark.parametrize("flag, expected", [(None, True), ("1", True), ("0", False)]) |
| 116 | +@pytest.mark.parametrize("legacy", [False, True]) |
| 117 | +def test_host_selection_uses_the_loaders_threshold_and_overrides(tmp_path, monkeypatch, runtime, flag, expected, legacy): |
| 118 | + _checkpoint(tmp_path) |
| 119 | + model_size = sum(p.stat().st_size for p in tmp_path.glob("model*.safetensors")) |
| 120 | + runtime.device_info = lambda: {"max_recommended_working_set_size": model_size} |
| 121 | + if legacy: |
| 122 | + runtime.metal = SimpleNamespace(device_info=runtime.device_info) |
| 123 | + del runtime.device_info |
| 124 | + if flag is not None: |
| 125 | + monkeypatch.setenv("TF_NGRAM_HOST", flag) |
| 126 | + assert host_table.ngrams_on_host(tmp_path) is expected |
| 127 | + info = lambda: {"max_recommended_working_set_size": model_size * 2} |
| 128 | + if legacy: |
| 129 | + runtime.metal.device_info = info |
| 130 | + else: |
| 131 | + runtime.device_info = info |
| 132 | + assert host_table.ngrams_on_host(tmp_path) is (flag == "1") |
0 commit comments