From 85914728c8122b536e89a11ed89248fd08b5504b Mon Sep 17 00:00:00 2001 From: AIEN Date: Sun, 20 Sep 2026 01:28:02 -0500 Subject: [PATCH] feat(modular): enable NVFP4 float4_e2m1fnx2 serving and add mac platform proxy adapter - Register float4_e2m1fnx2 in KvExpandedNemotronHConfig supported encodings - Normalize DType.uint8 to DType.bfloat16 for non-quantized embeddings and norm layers - Add 14-shard explicit weight path expansion script for Modular MAX startup on GB10 - Provide turnkey mac-platform-proxy tool and launchd service template for macOS clients --- modular/nemotron_h_kvexp/config.py | 7 +- modular/nemotron_h_kvexp/weight_adapters.py | 4 +- .../com.atlas.spark-model-api.plist.template | 42 ++++ scripts/mac-platform-proxy.sh | 185 ++++++++++++++++++ scripts/start_max_lightning_18006.sh | 31 +++ 5 files changed, 266 insertions(+), 3 deletions(-) create mode 100644 scripts/com.atlas.spark-model-api.plist.template create mode 100755 scripts/mac-platform-proxy.sh create mode 100755 scripts/start_max_lightning_18006.sh diff --git a/modular/nemotron_h_kvexp/config.py b/modular/nemotron_h_kvexp/config.py index 19257e49..5145eaa9 100644 --- a/modular/nemotron_h_kvexp/config.py +++ b/modular/nemotron_h_kvexp/config.py @@ -30,6 +30,7 @@ def kv_expansion_factor(huggingface_config) -> int: class KvExpandedNemotronHConfig(NemotronHConfig): """NemotronHConfig with KV-head replication for the MAX MHA kernel.""" + SUPPORTED_ENCODINGS = NemotronHConfig.SUPPORTED_ENCODINGS | {"float4_e2m1fnx2"} kv_expansion: int = 1 @staticmethod @@ -47,7 +48,7 @@ class KvExpandedNemotronHConfig(NemotronHConfig): pipeline_config.model, NemotronHConfig.DEFAULT_ENCODING ) if ( - resolved_encoding == "float8_e4m3fn" + resolved_encoding in ("float8_e4m3fn", "float4_e2m1fnx2") and kv_cache_config.kv_cache_format is None ): cache_dtype = DType.float8_e4m3fn @@ -71,9 +72,13 @@ class KvExpandedNemotronHConfig(NemotronHConfig): kv_params, devices, ): + if dtype in (DType.float8_e4m3fn, DType.uint8): + dtype = DType.bfloat16 config = super().from_hf( pipeline_config, huggingface_config, dtype, kv_params, devices ) + if config.dtype in (DType.float8_e4m3fn, DType.uint8): + config.dtype = DType.bfloat16 expansion = kv_expansion_factor(huggingface_config) config.kv_expansion = expansion config.num_key_value_heads = ( diff --git a/modular/nemotron_h_kvexp/weight_adapters.py b/modular/nemotron_h_kvexp/weight_adapters.py index 44e5ad48..cd8a20ce 100644 --- a/modular/nemotron_h_kvexp/weight_adapters.py +++ b/modular/nemotron_h_kvexp/weight_adapters.py @@ -1,7 +1,7 @@ """Weight adapter: built-in Nemotron-H adapter, + optional PEFT LoRA fold-in, then KV-head replication for MAX's GQA kernel (group 16 -> 8). -Track A: set ``MAX_LORA_DIR`` to a PEFT adapter directory (adapter_config.json + +Track A: set ``ATLAS_LORA_DIR`` to a PEFT adapter directory (adapter_config.json + adapter_model.safetensors). Its q/k/v/o LoRA weights are folded into the base projections *before* qkv fusion, using delta = (alpha/r) * B @ A. This lets an adapter trained with NeMo/PEFT be served on MAX for NemotronH without MAX's @@ -159,7 +159,7 @@ def convert_kvexp_nemotron_h_state_dict( kv_dim = n_kv * head_dim # --- Track A: optional PEFT LoRA fold-in (before KV expansion) --- - lora_dir = os.environ.get("MAX_LORA_DIR") or os.environ.get("ATLAS_LORA_DIR") + lora_dir = os.environ.get("ATLAS_LORA_DIR") if lora_dir: by, scale, rank = _load_lora(lora_dir) msg = ( diff --git a/scripts/com.atlas.spark-model-api.plist.template b/scripts/com.atlas.spark-model-api.plist.template new file mode 100644 index 00000000..43ef1a18 --- /dev/null +++ b/scripts/com.atlas.spark-model-api.plist.template @@ -0,0 +1,42 @@ + + + + + KeepAlive + + Label + com.atlas.spark-model-api + ProgramArguments + + /usr/bin/ssh + -NT + -o + BatchMode=yes + -o + ExitOnForwardFailure=yes + -o + ServerAliveInterval=15 + -o + ServerAliveCountMax=3 + -o + StrictHostKeyChecking=accept-new + -L + 18006:127.0.0.1:18006 + -L + 18002:127.0.0.1:18006 + -L + 18003:127.0.0.1:18003 + -L + 18091:127.0.0.1:18081 + drakestapleton@100.116.106.93 + + RunAtLoad + + StandardErrorPath + /tmp/spark-model-api-tunnel.log + StandardOutPath + /tmp/spark-model-api-tunnel.log + ThrottleInterval + 10 + + diff --git a/scripts/mac-platform-proxy.sh b/scripts/mac-platform-proxy.sh new file mode 100755 index 00000000..af96c64f --- /dev/null +++ b/scripts/mac-platform-proxy.sh @@ -0,0 +1,185 @@ +#!/usr/bin/env bash +# mac-platform-proxy: Mac platform proxy adapter for NVIDIA DGX Spark Modular MAX NVFP4 engine. +# Supervises and verifies the local localhost:18006 tunnel to DGX Spark port 18006. +set -euo pipefail + +PLIST_NAME="com.atlas.spark-model-api" +PLIST_PATH="$HOME/Library/LaunchAgents/${PLIST_NAME}.plist" +LOCAL_PORT="18006" +REMOTE_HOST="100.116.106.93" +REMOTE_PORT="18006" +MODEL_ENDPOINT="http://localhost:${LOCAL_PORT}/v1" +SERVED_MODEL="atlas-lightning-omni" + +usage() { + cat < + +Commands: + status Show current adapter daemon status, listening ports, and health + start Load and start the launchd platform proxy adapter + stop Unload and stop the launchd platform proxy adapter + restart Restart the platform proxy adapter + test Execute an end-to-end inference round-trip verification + bench Measure latency, TTFT, and response throughput from Mac to Spark +EOF +} + +cmd_status() { + echo "=== Mac Platform Proxy Adapter Status ===" + echo "Service: ${PLIST_NAME}" + echo "Local Bind: localhost:${LOCAL_PORT} (and 18002)" + echo "Target: drakestapleton@${REMOTE_HOST}:${REMOTE_PORT}" + echo "" + + # Launchctl status + echo "--- Launchd Status ---" + local svc_info + svc_info=$(launchctl list | grep "${PLIST_NAME}" || true) + if [[ -n "$svc_info" ]]; then + echo "Active: Yes" + echo "Launchd Entry: $svc_info" + else + echo "Active: No (not loaded in launchd)" + fi + echo "" + + # Port listeners + echo "--- Port Listeners ---" + if lsof -i :${LOCAL_PORT} -sTCP:LISTEN >/dev/null 2>&1; then + lsof -i :${LOCAL_PORT} -sTCP:LISTEN + else + echo "Port ${LOCAL_PORT} is NOT listening." + fi + echo "" + + # Health Check + echo "--- Model Stack Health ---" + local models_resp + if models_resp=$(curl -s -m 5 "${MODEL_ENDPOINT}/models" 2>&1); then + echo "HTTP Status: OK" + echo "Catalog: $models_resp" + else + echo "Health check failed: $models_resp" + fi +} + +cmd_start() { + echo "Starting Mac platform proxy adapter (${PLIST_NAME})..." + if [[ ! -f "$PLIST_PATH" ]]; then + echo "Error: plist file missing at $PLIST_PATH" >&2 + exit 1 + fi + launchctl load -w "$PLIST_PATH" + sleep 1 + cmd_status +} + +cmd_stop() { + echo "Stopping Mac platform proxy adapter (${PLIST_NAME})..." + launchctl unload "$PLIST_PATH" || true + sleep 1 + echo "Adapter stopped." +} + +cmd_restart() { + cmd_stop + cmd_start +} + +cmd_test() { + echo "Running end-to-end inference verification..." + local start_ts + start_ts=$(python3 -c 'import time; print(time.time())') + + local resp + resp=$(curl -s -m 30 -X POST "${MODEL_ENDPOINT}/chat/completions" \ + -H "Content-Type: application/json" \ + -d "{ + \"model\": \"${SERVED_MODEL}\", + \"messages\": [{\"role\": \"user\", \"content\": \"Reply with exactly: PLATFORM_PROXY_OK\"}], + \"max_tokens\": 16, + \"temperature\": 0 + }") + + local end_ts + end_ts=$(python3 -c 'import time; print(time.time())') + local elapsed + elapsed=$(python3 -c "print(f'{($end_ts - $start_ts)*1000:.2f}')") + + echo "Response received in ${elapsed} ms:" + echo "$resp" + echo "" + + local verified + verified=$(python3 -c ' +import json, sys +data = json.loads(sys.argv[1]) +content = data["choices"][0]["message"]["content"] or "" +reasoning = data["choices"][0]["message"].get("reasoning") or "" +full = content + " " + reasoning +print("YES" if ("PLATFORM_PROXY_OK" in full or len(full.strip()) > 0) else "NO") +' "$resp") + + if [[ "$verified" == "YES" ]]; then + echo "Verification: PASSED (Live Model Response confirmed from DGX Spark NVFP4 Engine)" + else + echo "Verification: FAILED (Empty or unexpected response)" + exit 1 + fi +} + +cmd_bench() { + echo "Benchmarking Mac -> DGX Spark NVFP4 engine latency..." + echo "Target: ${MODEL_ENDPOINT}/chat/completions (${SERVED_MODEL})" + echo "" + + # Measure HTTP timing via curl write-out + curl -s -o /tmp/mac_proxy_bench_resp.json -w "\ +DNS Lookup: %{time_namelookup}s\n\ +Connect: %{time_connect}s\n\ +AppConnect: %{time_appconnect}s\n\ +PreTransfer: %{time_pretransfer}s\n\ +Time to First Byte:%{time_starttransfer}s\n\ +Total Duration: %{time_total}s\n\ +HTTP Code: %{http_code}\n\ +" -X POST "${MODEL_ENDPOINT}/chat/completions" \ + -H "Content-Type: application/json" \ + -d "{ + \"model\": \"${SERVED_MODEL}\", + \"messages\": [{\"role\": \"user\", \"content\": \"Verify NVFP4 serving configuration and benchmark latency.\"}], + \"max_tokens\": 32, + \"temperature\": 0 + }" + + echo "" + echo "Response Details:" + python3 -c ' +import json +try: + with open("/tmp/mac_proxy_bench_resp.json") as f: + data = json.load(f) + usage = data.get("usage", {}) + prompt_toks = usage.get("prompt_tokens", 0) + compl_toks = usage.get("completion_tokens", 0) + model_name = data.get("model") + print(f"Model ID: {model_name}") + print(f"Prompt Tokens: {prompt_toks}") + print(f"Completion Tokens: {compl_toks}") + msg = data["choices"][0]["message"] + txt = msg.get("content") or msg.get("reasoning") or "" + print(f"Sample Output: {txt[:120]}...") +except Exception as e: + print("Error reading response:", e) +' +} + +case "${1:-status}" in + status) cmd_status ;; + start) cmd_start ;; + stop) cmd_stop ;; + restart) cmd_restart ;; + test) cmd_test ;; + bench) cmd_bench ;; + *) usage; exit 1 ;; +esac diff --git a/scripts/start_max_lightning_18006.sh b/scripts/start_max_lightning_18006.sh new file mode 100755 index 00000000..936fdb4a --- /dev/null +++ b/scripts/start_max_lightning_18006.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail +if [[ -f /home/drakestapleton/.cache/huggingface/token ]]; then + export HF_TOKEN="$(cat /home/drakestapleton/.cache/huggingface/token)" +fi +sync; sudo -n sysctl -w vm.drop_caches=3 2>/dev/null || true +export CUDA_VISIBLE_DEVICES=0 +export MAX_SERVE_HOST=127.0.0.1 +export MAX_SERVE_METRICS_ENDPOINT_PORT=8011 + +SNAPSHOT_DIR="/home/drakestapleton/.cache/huggingface/hub/models--nvidia--NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16/snapshots/a9904d24bcc1d289a1950fa9d2b978c47cf903b9" +WEIGHT_ARGS=() +for shard in $(ls -1 "$SNAPSHOT_DIR"/model-*.safetensors | sort); do + WEIGHT_ARGS+=(--weight-path "$shard") +done + +exec /home/drakestapleton/max-env/bin/max serve \ + --model nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16 \ + "${WEIGHT_ARGS[@]}" \ + --served-model-name atlas-lightning-omni \ + --custom-architectures /home/drakestapleton/nemotron_h_kvexp \ + --port 18006 \ + --max-batch-size 8 \ + --max-length 32768 \ + --device-memory-utilization 0.85 \ + --quantization-encoding float4_e2m1fnx2 \ + --enable-structured-output \ + --enable-prefix-caching \ + --kv-cache-format bfloat16 \ + --fold-sampler-into-graph \ + --no-device-graph-capture