Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions container/deps/sglang/discover_nixl_ucx_layout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Discover NIXL's private UCX libraries and native UCX consumers."""
Comment thread
Chokoyo marked this conversation as resolved.
Resolved

from __future__ import annotations

import ctypes
import re
from importlib.metadata import Distribution, distributions
from pathlib import Path


def cuda_distributions(
package_prefix: str,
) -> list[tuple[str, str, Distribution]]:
"""Return installed CUDA distributions matching a package prefix."""
pattern = re.compile(rf"{re.escape(package_prefix)}-cu([0-9]+)", re.IGNORECASE)
matches = []
for distribution in distributions():
name = distribution.metadata.get("Name", "")
normalized_name = re.sub(r"[-_.]+", "-", name)
match = pattern.fullmatch(normalized_name)
if match is not None:
matches.append((name, match.group(1), distribution))
return matches


def distribution_description(name: str, distribution: Distribution) -> str:
"""Return an installed distribution name and its import root."""
install_root = Path(distribution.locate_file("")).resolve()
return f"{name} ({install_root})"


def read_ucx_version(libucp_path: Path) -> str:
"""Read the UCX release from a specific libucp implementation."""
try:
libucp = ctypes.CDLL(str(libucp_path), mode=ctypes.RTLD_LOCAL)
except OSError as error:
raise SystemExit(
f"nixl-ucx-compat: failed to load {libucp_path}: {error}"
) from error

try:
get_version = libucp.ucp_get_version
except AttributeError as error:
raise SystemExit(
f"nixl-ucx-compat: {libucp_path} does not export ucp_get_version"
) from error

major = ctypes.c_uint()
minor = ctypes.c_uint()
release = ctypes.c_uint()
get_version.argtypes = [
ctypes.POINTER(ctypes.c_uint),
ctypes.POINTER(ctypes.c_uint),
ctypes.POINTER(ctypes.c_uint),
]
get_version.restype = None
get_version(ctypes.byref(major), ctypes.byref(minor), ctypes.byref(release))
return f"{major.value}.{minor.value}.{release.value}"


def main() -> None:
"""Print the discovered layout as tab-separated records."""
nixl_matches = cuda_distributions("nixl")
if not nixl_matches:
raise SystemExit(
"nixl-ucx-compat: no nixl-cu* distribution found; "
"the upstream NIXL wheel layout may have changed"
)
if len(nixl_matches) > 1:
found = sorted(
distribution_description(name, distribution)
for name, _, distribution in nixl_matches
)
raise SystemExit(
f"nixl-ucx-compat: expected one nixl-cu* distribution, found {found}"
)
Comment thread
Chokoyo marked this conversation as resolved.
Resolved

nixl_name, nixl_cuda_major, nixl = nixl_matches[0]
nixl_files = list(nixl.files or ())

plugins = set()
for _, _, nvshmem in cuda_distributions("nvidia-nvshmem"):
for item in nvshmem.files or ():
if Path(item).name.startswith("nvshmem_transport_ucx.so"):
path = Path(nvshmem.locate_file(item)).resolve()
if path.is_file():
plugins.add(path)

aliases = []
for stem in ("libucp", "libucs"):
pattern = re.compile(rf"{stem}-[0-9A-Fa-f]+[.]so[.]([0-9]+)(?:[.][0-9]+)*")
candidates = {}
for item in nixl_files:
match = pattern.fullmatch(Path(item).name)
if match is None:
continue
path = Path(nixl.locate_file(item)).resolve()
if path.is_file():
candidates[path] = match.group(1)
if len(candidates) != 1:
raise SystemExit(
f"nixl-ucx-compat: expected one private {stem} library, "
f"found {sorted(map(str, candidates))}"
)
target, major = next(iter(candidates.items()))
aliases.append((f"{stem}.so.{major}", target))

lib_dirs = {target.parent for _, target in aliases}
if len(lib_dirs) != 1:
raise SystemExit(
"nixl-ucx-compat: UCX libraries span multiple directories: "
f"{sorted(map(str, lib_dirs))}"
)
nixl_lib_dir = next(iter(lib_dirs))
libucp_target = next(
target for alias, target in aliases if alias.startswith("libucp.so.")
)
ucx_version = read_ucx_version(libucp_target)

print(f"nixl\t{nixl_name}\t{nixl_cuda_major}")
print(f"ucx\t{ucx_version}")
print(f"libdir\t{nixl_lib_dir}")
for plugin in sorted(plugins):
print(f"plugin\t{plugin}")
for alias, target in aliases:
print(f"alias\t{alias}\t{target}")


if __name__ == "__main__":
main()
141 changes: 141 additions & 0 deletions container/deps/sglang/install_nixl_ucx_compat.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
#!/usr/bin/env bash
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

set -euo pipefail

readonly OUTPUT_DIR="${1:-/opt/dynamo/nixl-ucx-compat}"
readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"

die() {
echo "nixl-ucx-compat: $*" >&2
exit 1
}

validate_ucx_dependencies() {
local consumer="$1"
local resolved="$2"
local dependency_count=0
local soname arrow resolved_path remainder

while read -r soname arrow resolved_path remainder; do
[[ "${arrow}" == "=>" ]] || continue
((dependency_count += 1))
if [[ "${resolved_path}" == "not" && "${remainder}" == found* ]]; then
die "${consumer}: unresolved UCX dependency ${soname}; the generic alias set may need updating"
fi
case "${resolved_path}" in
"${OUTPUT_DIR}/"*|"${NIXL_LIB_DIR}/"*) ;;
*)
die "${consumer}: ${soname} resolved outside NIXL's UCX: ${resolved_path}"
;;
esac
done < <(grep -E '(^|[[:space:]/])libuc[mpst][-.]' <<<"${resolved}" || true)

[[ "${dependency_count}" -gt 0 ]] || \
die "${consumer}: no UCX dependencies found in ldd output"
}

[[ "${OUTPUT_DIR}" == /* && "${OUTPUT_DIR}" != "/" ]] || \
die "output directory must be an absolute non-root path"

for tool in dirname env grep ldd ln mkdir python3 readlink; do
command -v "${tool}" >/dev/null || die "required tool not found: ${tool}"
done

readonly DISCOVER_SCRIPT="${SCRIPT_DIR}/discover_nixl_ucx_layout.py"
[[ -f "${DISCOVER_SCRIPT}" ]] || die "layout discovery script not found: ${DISCOVER_SCRIPT}"

# NIXL CUDA wheels carry auditwheel-renamed UCX libraries, while other native
# components can request the generic UCX SONAMEs. Resolve both names to the same
# wheel-owned files so one process cannot load two UCX implementations.
LAYOUT_OUTPUT="$(python3 "${DISCOVER_SCRIPT}")"

mapfile -t LAYOUT <<<"${LAYOUT_OUTPUT}"

declare -a PLUGINS=()
declare -A ALIASES=()
NIXL_PACKAGE=""
NIXL_LIB_DIR=""
UCX_VERSION=""
for record in "${LAYOUT[@]}"; do
IFS=$'\t' read -r kind first second <<<"${record}"
case "${kind}" in
nixl) NIXL_PACKAGE="${first}" ;;
ucx) UCX_VERSION="${first}" ;;
libdir) NIXL_LIB_DIR="${first}" ;;
plugin) PLUGINS+=("${first}") ;;
alias) ALIASES["${first}"]="${second}" ;;
*) die "unexpected layout record: ${record}" ;;
esac
done

[[ -n "${NIXL_PACKAGE}" ]] || die "failed to identify the NIXL CUDA wheel"
[[ -n "${UCX_VERSION}" ]] || die "failed to identify the NIXL UCX version"
[[ -d "${NIXL_LIB_DIR}" ]] || die "failed to locate the NIXL private library directory"
# The NVSHMEM transport directly needs generic libucp and libucs only. Their
# libuct and libucm dependencies use auditwheel-mangled names resolved by
# $ORIGIN, so adding generic aliases for those libraries would be unnecessary.
[[ "${#ALIASES[@]}" -eq 2 ]] || die "failed to locate both NIXL UCX core libraries"
if [[ "${#PLUGINS[@]}" -eq 0 ]] && \
[[ "${NIXL_UCX_COMPAT_ALLOW_NO_CONSUMER:-0}" != "1" ]]; then
die "no NVSHMEM UCX transport found; aliases were not validated against a consumer;" \
"set NIXL_UCX_COMPAT_ALLOW_NO_CONSUMER=1 to accept this"
fi

# Keep the generic names beside NIXL's private libraries. Loading libucp or
# libucs through a separate symlink directory changes $ORIGIN and prevents UCX
# from finding both its hashed core dependencies and its ucx/ module directory.
Comment thread
Chokoyo marked this conversation as resolved.
Resolved
# These aliases are not tracked by the wheel's RECORD, so a later NIXL uninstall
# or upgrade can leave stale or dangling links. Run this after the final install
# step that can modify the nixl-cu* wheel.
for alias in "${!ALIASES[@]}"; do
target="${ALIASES[${alias}]}"
[[ -f "${target}" ]] || die "alias target is missing: ${target}"
[[ "${target%/*}" == "${NIXL_LIB_DIR}" ]] || \
die "alias target is outside the NIXL private library directory: ${target}"
alias_path="${NIXL_LIB_DIR}/${alias}"
if [[ -e "${alias_path}" || -L "${alias_path}" ]]; then
[[ -L "${alias_path}" && "$(readlink -f "${alias_path}")" == "${target}" ]] || \
die "refusing to replace existing path: ${alias_path}"
else
ln -s "${target##*/}" "${alias_path}"
fi
[[ "$(readlink -f "${alias_path}")" == "${target}" ]] || \
die "failed to install ${alias}"
done

# Expose the discovered wheel directory through a stable image path for ENV.
if [[ -e "${OUTPUT_DIR}" || -L "${OUTPUT_DIR}" ]]; then
[[ -L "${OUTPUT_DIR}" && "$(readlink -f "${OUTPUT_DIR}")" == "${NIXL_LIB_DIR}" ]] || \
die "refusing to replace existing output path: ${OUTPUT_DIR}"
else
mkdir -p "$(dirname "${OUTPUT_DIR}")"
ln -s "${NIXL_LIB_DIR}" "${OUTPUT_DIR}"
fi

# Do not inherit the image's ambient NIXL paths here: they would mask a broken
# $ORIGIN closure in the compatibility layout.
for plugin in "${PLUGINS[@]}"; do
resolved="$(env -u LD_LIBRARY_PATH LD_LIBRARY_PATH="${OUTPUT_DIR}" ldd "${plugin}")"
validate_ucx_dependencies "${plugin}" "${resolved}"
grep -E '^[[:space:]]*libucp[.]so[^[:space:]]*[[:space:]]+=>' <<<"${resolved}" >/dev/null || \
die "${plugin}: generic libucp dependency was not found"
grep -E '^[[:space:]]*libucs[.]so[^[:space:]]*[[:space:]]+=>' <<<"${resolved}" >/dev/null || \
die "${plugin}: generic libucs dependency was not found"
done

# UCX discovers loadable transports relative to libucs at runtime. Validate the
# CUDA modules and their private UCX dependency closure through the stable path.
for module_name in libuct_cuda.so libucm_cuda.so; do
module_path="${OUTPUT_DIR}/ucx/${module_name}"
[[ -e "${module_path}" ]] || die "missing NIXL UCX CUDA module: ${module_path}"
resolved="$(env -u LD_LIBRARY_PATH LD_LIBRARY_PATH="${OUTPUT_DIR}" ldd "${module_path}")"
validate_ucx_dependencies "${module_path}" "${resolved}"
done

if [[ "${#PLUGINS[@]}" -eq 0 ]]; then
echo "nixl-ucx-compat: no NVSHMEM UCX transport found; consumer validation explicitly skipped"
fi
Comment thread
Chokoyo marked this conversation as resolved.
Resolved
echo "nixl-ucx-compat: installed ${#ALIASES[@]} aliases for" \
"${NIXL_PACKAGE} UCX ${UCX_VERSION} in ${NIXL_LIB_DIR}"
13 changes: 13 additions & 0 deletions container/templates/sglang_runtime.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,19 @@ RUN --mount=type=bind,source=./container/deps/requirements.sglang.txt,target=/tm
pip install --break-system-packages --force-reinstall --no-deps \
--requirement /tmp/requirements.sglang.txt

{% if device != "xpu" and target not in ("dev", "local-dev") %}
# Add generic UCX aliases beside NIXL's private libraries so native consumers
# use the same implementation without breaking UCX's $ORIGIN-based core and
# module lookup. The wheel's auditwheel dependency directory is deliberately
# placed first for every process; it contains only hash-mangled dependencies
# plus the two generic UCX aliases. No existing wheel file or ELF metadata is
# modified.
RUN --mount=type=bind,source=./container/deps/sglang/install_nixl_ucx_compat.sh,target=/tmp/install_nixl_ucx_compat.sh,readonly \
--mount=type=bind,source=./container/deps/sglang/discover_nixl_ucx_layout.py,target=/tmp/discover_nixl_ucx_layout.py,readonly \
bash /tmp/install_nixl_ucx_compat.sh /opt/dynamo/nixl-ucx-compat
ENV LD_LIBRARY_PATH=/opt/dynamo/nixl-ucx-compat${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
Comment thread
Chokoyo marked this conversation as resolved.
Resolved
Comment thread
Chokoyo marked this conversation as resolved.
Resolved
{% endif %}

# Copy tests, deploy and components for CI with correct ownership
COPY --chmod=775 --chown=dynamo:0 tests /workspace/tests
COPY --chmod=775 --chown=dynamo:0 examples /workspace/examples
Expand Down
Loading