Experimental remote Engram adapter¶
This example illustrates the vLLM-side row adapter used in the accompanying
research measurements. It is not a standalone RDMA implementation. The
adapter currently imports an external ReaderRuntime and checkpoint inspector
backed by a legacy NIXL/GPUNETIO GPU-GET shim. Neither is supplied by current
public NIXL; NIXL #2544 tracks
the proposed supported interface. Do not use this example as a production
provider or assume it works with an ordinary NIXL wheel.
The self-contained GPU test replaces that external reader with a fake and checks row layout, masking, int32 hash-ID conversion, strided output, and retention on failed retirement. With PyTorch, Triton and a CUDA GPU installed:
This test does not perform RDMA. A separate, explicitly unsupported legacy research snapshot contains the matching owner, reader and GPU GET source. It builds with DOCA 3.1 and a fresh build passed synthetic cross-node READ and a small real vLLM 1P1D correctness/performance study. It is not evidence of current-SDK or production support.
Example materials¶
test_provider_gpu.py
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Small GPU test of the vLLM adapter's row layout and scratch ordering."""
import os
import sys
from types import ModuleType, SimpleNamespace
import torch
os.environ.pop("ENGRAM_SHARED_PREFETCH", None)
class FakeRuntime:
def __init__(self):
self.prefetch_enabled = False
self.storage_layout = "row264"
self.used = []
def fetch(self, ids, layer, lo, hi):
# Each row has a distinct exact FP8 value and one distinct power-of-two
# scale, so head ordering, invalid ids and layer identity are observable.
col = torch.arange(256, device=ids.device)
block = torch.arange(8, device=ids.device)
weights = ((ids.abs()[:, None] % 7) + layer + col % 4).to(torch.float8_e4m3fn)
scales = (127 + (ids.abs()[:, None] + block) % 3).to(torch.uint8)
return ids, weights, scales
def record_consumed(self, layer):
self.used.append(layer)
def close(self):
pass
mock = ModuleType("shared_model_adapter")
mock.ReaderRuntime = FakeRuntime
sys.modules[mock.__name__] = mock
import vllm_rdma_provider # noqa: E402
vllm_rdma_provider.verify_checkpoint_samples = lambda: None
VllmRemoteReader = vllm_rdma_provider.VllmRemoteReader
def main():
table = SimpleNamespace(
dim=256,
block_size=32,
head_start=1,
part_n_hash_cols=2,
rdma_layer_id=1,
vocab_start_idx=10,
vocab_end_idx=20,
num_embeddings=64,
)
ids = torch.tensor([[3, 10], [8, 19], [7, 20]], dtype=torch.int32, device="cuda")
# The second local head is padded; output is a noncontiguous layer view.
selected = torch.tensor([[10, -1], [19, -1], [20, -1]], device="cuda")
valid = (selected >= 10) & (selected < 20)
col = torch.arange(256, device="cuda")
block = torch.arange(8, device="cuda")
raw = ((selected.abs()[..., None] % 7) + 1 + col % 4).to(torch.float8_e4m3fn)
scales = (127 + (selected.abs()[..., None] + block) % 3).to(torch.uint8)
reader = VllmRemoteReader()
for dtype, width in ((torch.bfloat16, 256), (torch.uint8, 264)):
backing = torch.full((3, 2, 2, width), 37, dtype=dtype, device="cuda")
out = backing[:, 0]
reader.lookup(table, ids, out)
if dtype == torch.bfloat16:
expected = torch.where(
valid[..., None],
raw.float() * (2.0 ** (scales[..., col // 32].int() - 127)),
0,
)
torch.testing.assert_close(out, expected.to(dtype))
else:
expected_values = torch.where(valid[..., None], raw.view(torch.uint8), 0)
expected_scales = torch.where(valid[..., None], scales, 0)
torch.testing.assert_close(out[..., :256], expected_values)
torch.testing.assert_close(out[..., 256:], expected_scales)
assert (backing[:, 1] == 37).all().item()
torch.cuda.synchronize()
assert reader.runtime.used == [1, 1]
class FailingClose:
def close(self):
raise RuntimeError("retirement failed")
retained = SimpleNamespace(runtime=FailingClose())
vllm_rdma_provider._reader = retained
try:
vllm_rdma_provider.close_reader()
except RuntimeError:
pass
else:
raise AssertionError("failed retirement was ignored")
assert vllm_rdma_provider._reader is retained
vllm_rdma_provider._reader = reader
vllm_rdma_provider.close_reader()
assert vllm_rdma_provider._reader is None
print("PASS: BF16/packed rows, invalid IDs, TP-head padding, strided output")
if __name__ == "__main__":
main()
vllm_rdma_provider.py
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Research bridge from vLLM Engram lookup to the validated NIXL GET shim.
The SGLang research runtime and its native library must be on PYTHONPATH and
configured before importing this module. This is not a public NIXL API.
"""
import hashlib
import json
import os
from pathlib import Path
import torch
import torch.nn.functional as F
import triton
import triton.language as tl
def verify_checkpoint_samples():
"""Reject mismatched owner weights using published boundary-row samples."""
from real_checkpoint_owner import inspect_checkpoint
ready = json.loads(Path(os.environ["ENGRAM_SHARED_READY"]).read_text())
samples = ready.get("sample_validation")
if not isinstance(samples, list) or {s.get("layer") for s in samples} != {1, 14}:
raise ValueError("owner did not publish the required checkpoint samples")
manifest = inspect_checkpoint(Path(os.environ["ENGRAM_SHARED_MODEL"]))
if manifest["checkpoint_identity"] != ready["checkpoint_id"]:
raise ValueError("checkpoint metadata identity differs from owner")
for sample in samples:
layer = sample["layer"]
for kind, width in (("weight", 256), ("scale", 8)):
spec = next(
s
for s in manifest["specs"]
if s["layer"] == layer and s["kind"] == kind
)
required_rows = sorted({0, 1, spec["rows"] // 2, spec["rows"] - 1})
if sample.get("rows") != required_rows:
raise ValueError("owner checkpoint sample rows are incomplete")
shard = manifest["shards"][spec["shard"]]
digest = hashlib.sha256()
with open(shard["path"], "rb", buffering=0) as file:
for row in sample["rows"]:
if not 0 <= row < spec["rows"]:
raise ValueError("invalid published sample row")
offset = shard["data_start"] + spec["data_offsets"][0] + row * width
data = os.pread(file.fileno(), width, offset)
if len(data) != width:
raise ValueError("short checkpoint sample")
digest.update(row.to_bytes(8, "little") + data)
if digest.hexdigest() != sample[f"{kind}_sample_bytes_sha256"]:
raise ValueError(
f"checkpoint content differs from owner at layer {layer}"
)
@triton.jit
def _scatter_rows(
weight,
scales,
ids,
out,
lo,
hi,
stride_w,
stride_s,
stride_t,
stride_h,
local_heads: tl.constexpr,
packed: tl.constexpr,
):
row = tl.program_id(0)
idx = tl.load(ids + row).to(tl.int64)
owned = (idx >= lo) & (idx < hi)
cols = tl.arange(0, 256)
values = tl.load(weight + row * stride_w + cols, mask=owned, other=0.0)
scale = tl.load(scales + row * stride_s + cols // 32, mask=owned, other=0)
dst = out + (row // local_heads) * stride_t + (row % local_heads) * stride_h
if packed:
tl.store(dst + cols, values.to(tl.uint8, bitcast=True))
tl.store(dst + 256 + cols // 32, scale, mask=cols % 32 == 0)
else:
factor = (scale.to(tl.int32) << 23).to(tl.float32, bitcast=True)
tl.store(dst + cols, (values.to(tl.float32) * factor).to(tl.bfloat16))
class VllmRemoteReader:
def __init__(self):
from shared_model_adapter import ReaderRuntime
if os.environ.get("ENGRAM_SHARED_PREFETCH") == "1":
raise RuntimeError("vLLM prototype requires ENGRAM_SHARED_PREFETCH=0")
verify_checkpoint_samples()
self.runtime = ReaderRuntime()
if self.runtime.storage_layout != "row264":
self.runtime.close()
raise RuntimeError("vLLM prototype requires packed row264 tables")
self.consumed = torch.cuda.Event()
self.inflight = False
def lookup(self, table, indices, out, background=False):
if torch.cuda.is_current_stream_capturing():
raise RuntimeError("remote lookup must run at a vLLM eager boundary")
if table.dim != 256 or table.block_size != 32:
raise ValueError("unsupported remote Engram row format")
if out.dtype not in (torch.bfloat16, torch.uint8) or out.ndim != 3:
raise ValueError("expected 3-D BF16 or packed-byte output")
if out.shape[:2] != (indices.shape[0], table.part_n_hash_cols):
raise ValueError("output shape does not match local Engram heads")
start, heads = table.head_start, table.part_n_hash_cols
local = indices[:, start : start + heads]
if local.shape[1] < heads:
local = F.pad(local, (0, heads - local.shape[1]), value=-1)
ids = local.to(dtype=torch.int64).contiguous().view(-1)
# The native GET validates every input ID before applying rank bounds.
# vLLM uses negative IDs for padding, so give the transport a valid
# placeholder and retain the original IDs for the final ownership mask.
read_ids = torch.where((ids >= 0) & (ids < table.num_embeddings), ids, 0)
stream = torch.cuda.current_stream()
if self.inflight:
stream.wait_event(self.consumed)
_, weight, scale = self.runtime.fetch(
read_ids, table.rdma_layer_id, table.vocab_start_idx, table.vocab_end_idx
)
_scatter_rows[(ids.numel(),)](
weight,
scale,
ids,
out,
table.vocab_start_idx,
table.vocab_end_idx,
weight.stride(0),
scale.stride(0),
out.stride(0),
out.stride(1),
heads,
out.dtype == torch.uint8,
num_warps=4,
)
self.runtime.record_consumed(table.rdma_layer_id)
self.consumed.record(stream)
self.inflight = True
_reader = None
def get_reader():
global _reader
if _reader is None:
_reader = VllmRemoteReader()
return _reader
def close_reader():
"""Retire GPU/NIC work before releasing the owner lease."""
global _reader
if _reader is not None:
_reader.runtime.close()
_reader = None