94057c3d3e
PR Test (NPU) / check-changes (push) Has been cancelled
PR Test (NPU) / pr-gate (push) Has been cancelled
PR Test (NPU) / set-image-config (push) Has been cancelled
PR Test (NPU) / stage-b-test-1-npu-a2 (0) (push) Has been cancelled
PR Test (NPU) / stage-b-test-1-npu-a2 (1) (push) Has been cancelled
PR Test (NPU) / stage-b-test-2-npu-a2 (0) (push) Has been cancelled
PR Test (NPU) / stage-b-test-2-npu-a2 (1) (push) Has been cancelled
PR Test (NPU) / stage-b-test-4-npu-a3 (push) Has been cancelled
PR Test (NPU) / stage-b-test-16-npu-a3 (push) Has been cancelled
PR Test (NPU) / multimodal-gen-test-1-npu-a3 (push) Has been cancelled
PR Test (NPU) / multimodal-gen-test-2-npu-a3 (push) Has been cancelled
PR Test (Arm64) / pr-gate (push) Has been cancelled
PR Test (Arm64) / check-changes (push) Has been cancelled
PR Test (Arm64) / build-test (push) Has been cancelled
PR Test (sgl-router) / gate (push) Has been cancelled
PR Test (sgl-router) / tier-1 — lint (push) Has been cancelled
PR Test (sgl-router) / tier-2 — build + test (push) Has been cancelled
PR Test (sgl-router) / tier-3 — docker (placeholder) (push) Has been cancelled
PR Test (sgl-router) / tier-3 — k8s integration (push) Has been cancelled
PR Test (sgl-router) / tier-3 — e2e (push) Has been cancelled
PR Test (sgl-router) / finish (push) Has been cancelled
PR Test (NPU) / single-node-poc (map[name:qwen3_6_27b_w8a8_1p_in64k_out1k_50ms runner:linux-aarch64-a3-2 test_case:test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_1p_in64k_out1k_50ms.py test_type:perf]) (push) Has been cancelled
PR Test (NPU) / pr-test-npu-finish (push) Has been cancelled
PR Test (Xeon) / pr-gate (push) Has been cancelled
PR Test (Xeon) / check-changes (push) Has been cancelled
PR Test (Xeon) / build-test (, xeon-gnr, base-b-test-cpu) (push) Has been cancelled
PR Test (XPU) / check-changes (push) Has been cancelled
PR Test (XPU) / pr-gate (push) Has been cancelled
PR Test (XPU) / stage-a-test-1-gpu-xpu (push) Has been cancelled
PR Test (XPU) / wait-for-stage-a (push) Has been cancelled
PR Test (XPU) / stage-b-test-1-gpu-xpu (push) Has been cancelled
PR Test (XPU) / finish (push) Has been cancelled
CI Model Inventory / build-inventory (push) Has been cancelled
Lint / lint (push) Has been cancelled
PR Benchmark (SMG Components) / Benchmark Compilation Check (push) Has been cancelled
PR Benchmark (SMG Components) / Benchmark - Manual Policy (push) Has been cancelled
PR Benchmark (SMG Components) / Benchmark - Request Processing (push) Has been cancelled
PR Benchmark (SMG Components) / Benchmark Summary (push) Has been cancelled
PR Test (SMG) / build-wheel (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on windows (x86_64 - auto) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on macos (x86_64 - auto) (push) Has been cancelled
PR Test (SMG) / python-unit-tests (push) Has been cancelled
PR Test (SMG) / unit-tests (push) Has been cancelled
PR Test (SMG) / benchmarks (push) Has been cancelled
PR Test (SMG) / chat-completions (push) Has been cancelled
PR Test (SMG) / chat-completions-4gpu (push) Has been cancelled
PR Test (SMG) / e2e (push) Has been cancelled
PR Test (SMG) / docker-build-test (push) Has been cancelled
PR Test (SMG) / k8s-integration (push) Has been cancelled
PR Test (SMG) / finish (push) Has been cancelled
PR Test (SMG) / summarize-benchmarks (push) Has been cancelled
Release SGLang Model Gateway Docker Image / publish (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on macos (aarch64 - auto) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on linux (aarch64 - auto) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on linux (x86_64 - auto) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on linux (aarch64 - musllinux_1_1) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on linux (x86_64 - musllinux_1_1) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / Build SDist (push) Has been cancelled
Release SGLang Model Gateway to PyPI / Upload to PyPI (push) Has been cancelled
Release SGLang Kernels / build-cu129-matrix (aarch64, 12.9, 3.10, arm-kernel-build-node) (push) Has been cancelled
Release SGLang Kernels / build-cu129-matrix (x86_64, 12.9, 3.10, x64-kernel-build-node) (push) Has been cancelled
Release SGLang Kernels / release-cu129 (push) Has been cancelled
Release SGLang Kernels / build-cu130-matrix (aarch64, 13.0, 3.10, arm-kernel-build-node) (push) Has been cancelled
Release SGLang Kernels / build-cu130-matrix (x86_64, 13.0, 3.10, x64-kernel-build-node) (push) Has been cancelled
Release SGLang Kernels / release-cu130 (push) Has been cancelled
Release SGLang Kernels / build-rocm-matrix (3.10, 700) (push) Has been cancelled
Release SGLang Kernels / build-rocm-matrix (3.10, 720) (push) Has been cancelled
Release SGLang Kernels / release-rocm700 (push) Has been cancelled
Release SGLang Kernels / release-rocm720 (push) Has been cancelled
Release SGLang Kernels / build-musa43 (43, 3.10) (push) Has been cancelled
Release SGLang Kernels / release-musa43 (push) Has been cancelled
199 lines
6.1 KiB
Python
199 lines
6.1 KiB
Python
# SPDX-License-Identifier: Apache-2.0
|
|
"""Zero-copy tensor codec for ZMQ multipart messages.
|
|
|
|
Frame 0: JSON metadata (tensor descriptors + scalar fields)
|
|
Frame 1-N: Raw tensor data buffers (one per tensor)
|
|
"""
|
|
|
|
import ctypes
|
|
import json
|
|
import logging
|
|
from dataclasses import dataclass
|
|
|
|
import torch
|
|
import zmq
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_DTYPE_TO_STR = {
|
|
torch.float16: "float16",
|
|
torch.float32: "float32",
|
|
torch.float64: "float64",
|
|
torch.bfloat16: "bfloat16",
|
|
torch.int8: "int8",
|
|
torch.int16: "int16",
|
|
torch.int32: "int32",
|
|
torch.int64: "int64",
|
|
torch.uint8: "uint8",
|
|
torch.bool: "bool",
|
|
}
|
|
_STR_TO_DTYPE = {v: k for k, v in _DTYPE_TO_STR.items()}
|
|
|
|
|
|
def dtype_to_str(dtype: torch.dtype) -> str:
|
|
s = _DTYPE_TO_STR.get(dtype)
|
|
if s is None:
|
|
raise ValueError(f"Unsupported dtype: {dtype}")
|
|
return s
|
|
|
|
|
|
def str_to_dtype(s: str) -> torch.dtype:
|
|
d = _STR_TO_DTYPE.get(s)
|
|
if d is None:
|
|
raise ValueError(f"Unknown dtype string: {s}")
|
|
return d
|
|
|
|
|
|
class TensorWrapper:
|
|
"""Expose a CPU-contiguous tensor's data buffer for zero-copy ZMQ send."""
|
|
|
|
def __init__(self, tensor: torch.Tensor):
|
|
if tensor.is_cuda or tensor.is_npu:
|
|
tensor = tensor.cpu()
|
|
if not tensor.is_contiguous():
|
|
tensor = tensor.contiguous()
|
|
self.tensor = tensor
|
|
data_ptr = tensor.data_ptr()
|
|
total_bytes = tensor.numel() * tensor.element_size()
|
|
self._c_buf = (ctypes.c_char * total_bytes).from_address(data_ptr)
|
|
self._view = memoryview(self._c_buf)
|
|
|
|
|
|
@dataclass
|
|
class TensorDescriptor:
|
|
field_name: str
|
|
shape: list[int]
|
|
dtype: str
|
|
list_index: int = -1 # -1 means not part of a list
|
|
|
|
def to_dict(self) -> dict:
|
|
return {
|
|
"field_name": self.field_name,
|
|
"shape": self.shape,
|
|
"dtype": self.dtype,
|
|
"list_index": self.list_index,
|
|
}
|
|
|
|
@classmethod
|
|
def from_dict(cls, d: dict) -> "TensorDescriptor":
|
|
return cls(
|
|
field_name=d["field_name"],
|
|
shape=d["shape"],
|
|
dtype=d["dtype"],
|
|
list_index=d.get("list_index", -1),
|
|
)
|
|
|
|
|
|
def pack_tensors(
|
|
tensor_fields: dict[str, torch.Tensor | list[torch.Tensor] | None],
|
|
scalar_fields: dict | None = None,
|
|
) -> tuple[bytes, list[TensorWrapper]]:
|
|
"""Pack tensor fields into metadata + buffer list for send_multipart."""
|
|
descriptors = []
|
|
buffers = []
|
|
|
|
for field_name, value in tensor_fields.items():
|
|
if value is None:
|
|
continue
|
|
|
|
if isinstance(value, torch.Tensor):
|
|
wrapper = TensorWrapper(value)
|
|
descriptors.append(
|
|
TensorDescriptor(
|
|
field_name=field_name,
|
|
shape=list(value.shape),
|
|
dtype=dtype_to_str(value.dtype),
|
|
)
|
|
)
|
|
buffers.append(wrapper)
|
|
|
|
elif isinstance(value, list):
|
|
for i, t in enumerate(value):
|
|
if t is None:
|
|
continue
|
|
if not isinstance(t, torch.Tensor):
|
|
raise TypeError(
|
|
f"Expected Tensor in list for field '{field_name}', "
|
|
f"got {type(t)}"
|
|
)
|
|
wrapper = TensorWrapper(t)
|
|
descriptors.append(
|
|
TensorDescriptor(
|
|
field_name=field_name,
|
|
shape=list(t.shape),
|
|
dtype=dtype_to_str(t.dtype),
|
|
list_index=i,
|
|
)
|
|
)
|
|
buffers.append(wrapper)
|
|
|
|
metadata = {
|
|
"tensor_descriptors": [d.to_dict() for d in descriptors],
|
|
"scalar_fields": scalar_fields or {},
|
|
}
|
|
metadata_bytes = json.dumps(metadata, separators=(",", ":")).encode("utf-8")
|
|
return metadata_bytes, buffers
|
|
|
|
|
|
def send_tensors(
|
|
socket: zmq.Socket,
|
|
tensor_fields: dict[str, torch.Tensor | list[torch.Tensor] | None],
|
|
scalar_fields: dict | None = None,
|
|
flags: int = 0,
|
|
) -> None:
|
|
"""Send tensors over ZMQ using multipart with zero-copy."""
|
|
metadata_bytes, buffers = pack_tensors(tensor_fields, scalar_fields)
|
|
parts: list = [metadata_bytes]
|
|
parts.extend(w._view if isinstance(w, TensorWrapper) else w for w in buffers)
|
|
socket.send_multipart(parts, flags=flags, copy=True)
|
|
|
|
|
|
def unpack_tensors(
|
|
parts: list,
|
|
device: str | torch.device = "cpu",
|
|
) -> tuple[dict[str, torch.Tensor | list[torch.Tensor]], dict]:
|
|
"""Unpack multipart message frames into tensor fields and scalar fields."""
|
|
metadata_frame = parts[0]
|
|
metadata_bytes = (
|
|
bytes(metadata_frame.buffer)
|
|
if hasattr(metadata_frame, "buffer")
|
|
else bytes(metadata_frame)
|
|
)
|
|
metadata = json.loads(metadata_bytes)
|
|
|
|
descriptors = [
|
|
TensorDescriptor.from_dict(d) for d in metadata["tensor_descriptors"]
|
|
]
|
|
scalar_fields = metadata.get("scalar_fields", {})
|
|
|
|
if len(parts) - 1 != len(descriptors):
|
|
raise ValueError(
|
|
f"Expected {len(descriptors)} tensor frames, got {len(parts) - 1}"
|
|
)
|
|
|
|
tensor_fields: dict[str, torch.Tensor | list[torch.Tensor]] = {}
|
|
list_sizes: dict[str, int] = {}
|
|
for desc in descriptors:
|
|
if desc.list_index >= 0:
|
|
current_max = list_sizes.get(desc.field_name, 0)
|
|
list_sizes[desc.field_name] = max(current_max, desc.list_index + 1)
|
|
|
|
for field_name, size in list_sizes.items():
|
|
tensor_fields[field_name] = [None] * size
|
|
|
|
for i, desc in enumerate(descriptors):
|
|
frame = parts[i + 1]
|
|
buf = frame.buffer if hasattr(frame, "buffer") else bytes(frame)
|
|
dtype = str_to_dtype(desc.dtype)
|
|
# clone() to own the memory (decouple from ZMQ buffer lifetime)
|
|
tensor = torch.frombuffer(buf, dtype=dtype).reshape(desc.shape).clone()
|
|
if device != "cpu" and device != torch.device("cpu"):
|
|
tensor = tensor.to(device)
|
|
|
|
if desc.list_index >= 0:
|
|
tensor_fields[desc.field_name][desc.list_index] = tensor
|
|
else:
|
|
tensor_fields[desc.field_name] = tensor
|
|
|
|
return tensor_fields, scalar_fields
|