Files
tokenspeed/test/runtime/test_gpu_memory_summary.py
Chen Hongtao 3e41a30c57 feat(dsv41): read Engram shards directly over NVLink within and across engines (#3892)
## Summary

DeepSeek-V4.1-Flash has **188.83 GiB of immutable Engram weights**
across two tables. This PR lets GPUs in one NVLink domain share those
tables. Each GPU loads its own range of rows from the checkpoint and
maps the peer shards into a contiguous view using CUDA FABRIC handles.

- **Within one engine**, each rank looks up its local token IDs
directly. This removes the Engram lookup all-reduce for TP-sharded
tables and the gather and reduce-scatter for query-sharded inputs.
- **Across engines**, separately launched instances share one copy of
each table. Once all shards have loaded, the engines can serve different
batches independently.

For example, two 2-GPU instances can both pass `--engram-group-size 4
--engram-group-store /shared/run-42/engram`. The store must be a fresh
shared directory, and all workers need access to the same IMEX channel.
Shards reside in HBM by default. Add `--engram-host-table` to place each
shard in its GPU’s local host NUMA memory.

## GB200 benchmark

We compared node-shared host tables with 16-way HBM sharding on **one
decode engine spanning four GB200 nodes**. Each configuration ran AgentX
at concurrency 3,018 for 20 minutes on DeepSeek-V4.1-Flash FP4. Both
used three 4-GPU prefill engines with node-shared host tables.

| Metric | Node-shared host tables | 16-way HBM shards | Change |
|---|---:|---:|---:|
| P90 time per output token | 5.17 ms | 5.09 ms | −1.55% |
| Output tokens per second per serving GPU | 4,182.39 | 4,220.77 |
+0.92% |

**Across all four decode nodes**, the baseline stored one copy of the
Engram tables per node, using **755.3 GiB of host DRAM in total**. The
sharded configuration stored one copy across those same nodes, using
**188.8 GiB of HBM in total**. Both figures are calculated from the
resident table size and placement.

## Test Plan

The two-GPU integration test covers HBM and host-NUMA placement. It
checks BF16 outputs and MXFP8 codes and scales against checkpoint rows
on both sides of a shard boundary, then replays a CUDA graph on one
worker after the other releases its table. On GB200, runtime logs
confirmed that all 16 decode ranks published their shards for both
Engram layers.

---------

Signed-off-by: chenht2022 <chenht2022@gmail.com>
2026-11-30 15:24:46 -08:00

175 lines
6.2 KiB
Python

# Copyright (c) 2026 LightSeek Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""The startup device memory summary: weight buckets and the KV cache row."""
from __future__ import annotations
import logging
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
import torch
from torch import nn
from tokenspeed.runtime.engine.scheduler_utils import (
_classify_param,
_kv_pool_bytes,
log_gpu_memory_summary,
)
@pytest.mark.parametrize(
"name, group",
[
("model.layers.1.engram.embed.weight", "engram_weights"),
("model.layers.1.engram.wkv.weight", "engram_weights"),
("model.layers.1.self_attn.wo.weight", "attention_weights"),
("model.layers.3.mlp.experts.w13_weight", "moe_weights"),
("model.layers.3.mlp.shared_experts.down_proj.weight", "dense_mlp_weights"),
("model.embed_tokens.weight", "other_weights"),
("lm_head.weight", "other_weights"),
],
)
def test_classify_param(name, group):
assert _classify_param(name) == group
def test_kv_pool_bytes_dedupes_views_of_one_arena():
arena = object()
target = SimpleNamespace(arena=arena, get_kv_size_bytes=lambda: 1 << 20)
draft = SimpleNamespace(arena=arena, get_kv_size_bytes=lambda: 1 << 20)
assert _kv_pool_bytes(target, draft, None) == 1 << 20
def _summary_rows(message):
return {
line.split("|")[1].strip(): float(line.split("|")[2])
for line in message.splitlines()
if line.startswith("| ") and not line.startswith("| Component")
}
class _Model(nn.Module):
def __init__(self, device):
super().__init__()
self.embed_tokens = nn.Embedding(64, 32, device=device)
self.layers = nn.ModuleList(
[
nn.Module(),
]
)
self.layers[0].engram = nn.Module()
self.layers[0].engram.embed = nn.Module()
# 64 MiB: large enough to survive the table's two-decimal GB rounding.
self.layers[0].engram.embed.weight = nn.Parameter(
torch.zeros(1 << 22, 8, dtype=torch.bfloat16, device=device),
requires_grad=False,
)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_summary_lists_engram_tables_and_kv_pool_bytes(caplog):
device = torch.device("cuda", 0)
model = _Model(device)
kv = torch.empty(48 << 20, dtype=torch.uint8, device=device)
pool = SimpleNamespace(
arena=SimpleNamespace(buffer=kv), get_kv_size_bytes=lambda: kv.nbytes
)
logger = logging.getLogger("tokenspeed.test_gpu_memory_summary")
logger.propagate = True
with caplog.at_level(logging.INFO, logger=logger.name):
log_gpu_memory_summary(
model,
0,
0,
logger,
kv_pool=pool,
device="cuda",
host_backed_parameter_ids=set(),
)
assert len(caplog.records) == 1, "the summary must be one record"
table = _summary_rows(caplog.records[0].getMessage())
gb = 1024**3
engram_bytes = model.layers[0].engram.embed.weight.nbytes
assert table["Engram weights (tables/wkv)"] == round(engram_bytes / gb, 2) > 0
assert table["KV cache"] == round(kv.nbytes / gb, 2) > 0
caplog.clear()
with caplog.at_level(logging.INFO, logger=logger.name):
log_gpu_memory_summary(
model,
0,
0,
logger,
kv_pool=pool,
device="cuda",
host_backed_parameter_ids={id(model.layers[0].engram.embed.weight)},
)
assert "Engram weights" not in caplog.records[0].getMessage()
# No Engram parameters on the device: the row is omitted, not printed as 0.
caplog.clear()
with caplog.at_level(logging.INFO, logger=logger.name):
log_gpu_memory_summary(
nn.Embedding(4, 4, device=device),
0,
0,
logger,
device="cuda",
host_backed_parameter_ids=set(),
)
assert "Engram weights" not in caplog.records[0].getMessage()
def test_summary_counts_local_vmm_allocation_once(caplog, monkeypatch):
from tokenspeed.runtime.models.deepseek_v41_engram import (
EngramGroup,
RowShardedEngramEmbedding,
)
gb = 1 << 30
group = Mock(spec=EngramGroup, host=False)
group.allocate.return_value = (torch.empty(8, 33, dtype=torch.uint8), 0, 4, gb)
model = nn.Module()
model.layer = nn.Module()
model.layer.engram = RowShardedEngramEmbedding(
8,
32,
SimpleNamespace(attn=SimpleNamespace(tp_size=1, tp_group=[0])),
"cpu",
group,
1,
)
counters = SimpleNamespace(
memory_allocated=lambda _: 2 * gb,
memory_reserved=lambda _: 3 * gb,
mem_get_info=lambda _: (3 * gb, 8 * gb),
)
monkeypatch.setattr(torch, "get_device_module", lambda _: counters)
logger = logging.getLogger(__name__)
with caplog.at_level(logging.INFO, logger=logger.name):
log_gpu_memory_summary(
model, 0, 0, logger, device="cpu", host_backed_parameter_ids=set()
)
rows = _summary_rows(caplog.records[-1].getMessage())
assert rows["Engram weights (tables/wkv)"] == 1
assert rows["Activations + device graphs"] == 2
assert rows["Non-torch (context/collectives)"] == 1