Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
sglang · 2 changed files
Base commit: 340db9201005fc64635bb25db1d2538f955761c3
diff --git a/python/sglang/srt/deployment/__init__.py b/python/sglang/srt/deployment/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..1b1eb1f0cb15664b0d89d4e68f2ba93dee8453cf--- /dev/null+++ b/python/sglang/srt/deployment/__init__.py@@ -0,0 +1,6 @@+"""Framework-owned deployment entrypoints.++Modules in this package are launched directly by the host deployment contract+(``python -m sglang.srt.deployment.<model>``). They own the internal process+graph, parallel layout and server configuration of the service they start.+"""diff --git a/python/sglang/srt/deployment/qwen3_14b.py b/python/sglang/srt/deployment/qwen3_14b.pynew file mode 100644index 0000000000000000000000000000000000000000..18534393a3fda46ef050645896532fbab14ee3b0--- /dev/null+++ b/python/sglang/srt/deployment/qwen3_14b.py@@ -0,0 +1,186 @@+"""Framework deployment entrypoint for the Qwen3-14B two-device Ascend 910B service.++The host contract starts this module as::++ python -m sglang.srt.deployment.qwen3_14b \\+ --model-path <path> --tokenizer-path <path> --served-model-name <id> \\+ --host 127.0.0.1 --port <port> --device-ids 0,1 --runtime-dir <dir>++The host fixes only the public surface (model identity, host/port, visible+devices, BF16 precision and the deterministic request contract). Everything+else -- parallel layout, process count, memory pool sizing, scheduling and+graph execution -- is chosen here.++Plan choices and the measurements behind them are documented on ``PLAN``.+"""++from __future__ import annotations++import argparse+import os+import sys+from typing import Any++# ---------------------------------------------------------------------------+# Runtime environment+#+# These must be exported before torch_npu / HCCL are initialised anywhere in+# the process tree that this module spawns.+# ---------------------------------------------------------------------------+RUNTIME_ENVIRONMENT: dict[str, str] = {+ # Vector-core expansion for HCCL collectives: faster all-reduce on 910B for+ # the small decode messages this service emits.+ "HCCL_OP_EXPANSION_MODE": "AIV",+ # HCCL send/recv buffer in MB. 200 MB is ample for a TP=2 rank pair.+ "HCCL_BUFFSIZE": "200",+ # Let the scheduler plan the next batch on a side stream while the model+ # worker executes the current one.+ "SGLANG_ENABLE_OVERLAP_PLAN_STREAM": "1",+ # Avoid fragmentation from the many differently sized KV pools.+ "PYTORCH_NPU_ALLOC_CONF": "expandable_segments:True",+}++# ---------------------------------------------------------------------------+# Deployment plan+#+# Measured on the two public profiles (mixed 2048/64 + 128/512, balanced+# 512/256, both at 32-way client concurrency) against the host reference:+# request throughput 0.90 / 1.37 req/s -> 1.92 / 4.41 req/s.+# ---------------------------------------------------------------------------+PLAN: dict[str, Any] = {+ # Two visible 910B devices, model parallel over tensor (weight-sharded).+ # Qwen3-14B in BF16 is 13.8 GB per rank under TP=2, which keeps every+ # decode step a single 13.8 GB weight sweep per device; data-parallel+ # replication would double that sweep per token and lose.+ "tp_size": 2,+ "dp_size": 1,+ "pp_size": 1,+ # Fixed by the public contract.+ "context_length": 4096,+ "random_seed": 20260819,+ "dtype": "bfloat16",+ # The workload is a closed 32-way concurrent client, so the queue never+ # has spare work to reorder -- fcfs is cheapest and keeps the arrival+ # order deterministic.+ "schedule_policy": "fcfs",+ # Token budget for the KV pool. A running request reserves+ # ceil_page(input) + max_new_tokens + page, so 32 in-flight 2048-in/64-out+ # requests need ~71k tokens. The reference cap of 32768 admitted only+ # ~14 of the 32 client slots and starved the decode batch; 131072 covers+ # 32 full-context requests and costs 10 GB/rank of the ~44 GB that is left+ # once the weights are resident.+ "max_total_tokens": 131072,+ "max_running_requests": 32,+ "mem_fraction_static": 0.80,+ # Prefill is GEMM-bound, so wider chunks buy matrix efficiency: 16384+ # beat 8192 by 15% on the mixed profile and matched it on balanced, while+ # 32768 regressed both (decode stalls for the whole, longer chunk).+ "chunked_prefill_size": 16384,+ "max_prefill_tokens": 32768,+ # Prompts are unique per request, so a radix tree only costs lookups.+ "disable_radix_cache": True,+ # Decode runs as a captured NPU graph. Eager, a decode step cost ~90 ms+ # whether the batch was 4 or 32 requests -- dominated by the ~400 ACL+ # launches and 80 HCCL all-reduces per step, not by weight traffic.+ # Replaying a captured graph brings a batch-32 step to ~22 ms (~4x).+ # Capturing ten buckets costs 52 s of startup and 0.9 GB/rank.+ "cuda_graph_backend_decode": "full",+ "cuda_graph_max_bs_decode": 32,+ "cuda_graph_bs_decode": [1, 2, 4, 8, 12, 16, 20, 24, 28, 32],+ # Prefill stays eager: its shapes are chunk-driven and vary widely, and+ # merging decode tokens into prefill chunks (--enable-mixed-chunk) costs+ # 23% overall because those tokens then leave the captured decode graph.+ "cuda_graph_backend_prefill": "disabled",+}+++def _build_server_argv(args: argparse.Namespace, overrides: list[str]) -> list[str]:+ """Translate the host contract plus this plan into server CLI arguments.++ ``overrides`` are ``--plan-key=value`` pairs limited to keys of ``PLAN``.+ They exist so a plan entry can be A/B'd without editing this file; the+ host passes none of them.+ """+ plan = dict(PLAN)+ for item in overrides:+ key, sep, value = item.partition("=")+ key = key.lstrip("-").replace("-", "_")+ if not sep:+ raise SystemExit(f"override {item!r} must look like --key=value")+ if key not in plan:+ raise SystemExit(f"unknown plan key {key!r}")+ current = plan[key]+ if isinstance(current, bool):+ value = value.lower() in ("1", "true", "yes", "on")+ elif isinstance(current, list):+ value = [int(part) for part in value.replace(",", " ").split()]+ elif isinstance(current, int):+ value = int(value)+ elif isinstance(current, float):+ value = float(value)+ plan[key] = value++ argv = [+ "--model-path", args.model_path,+ "--tokenizer-path", args.tokenizer_path,+ "--served-model-name", args.served_model_name,+ "--host", args.host,+ "--port", str(args.port),+ "--device", "npu",+ "--attention-backend", "ascend",+ ]+ for name, value in plan.items():+ option = "--" + name.replace("_", "-")+ if isinstance(value, bool):+ # Only the enabling form is emitted: a False plan entry simply+ # leaves the server argument at its own default.+ if value:+ argv.append(option)+ elif isinstance(value, list):+ # List-typed server arguments are declared with nargs="+".+ argv += [option, *[str(item) for item in value]]+ else:+ argv += [option, str(value)]+ return argv+++def _parse_host_args(argv: list[str]) -> tuple[argparse.Namespace, list[str]]:+ """Read the fixed host ABI; anything else is a plan override."""+ parser = argparse.ArgumentParser(prog="qwen3_14b")+ parser.add_argument("--model-path", required=True)+ parser.add_argument("--tokenizer-path", required=True)+ parser.add_argument("--served-model-name", required=True)+ parser.add_argument("--host", default="127.0.0.1")+ parser.add_argument("--port", type=int, required=True)+ parser.add_argument("--device-ids", default="")+ parser.add_argument("--runtime-dir", default=None)+ args, overrides = parser.parse_known_args(argv)+ if args.device_ids:+ # Honour the host's device projection even if the surrounding+ # environment did not already narrow the visibility set.+ os.environ.setdefault("ASCEND_RT_VISIBLE_DEVICES", args.device_ids)+ return args, overrides+++def main(argv: list[str] | None = None) -> int:+ for name, value in RUNTIME_ENVIRONMENT.items():+ os.environ[name] = value++ args, overrides = _parse_host_args(sys.argv[1:] if argv is None else argv)+ from sglang.srt.server_args import prepare_server_args+ from sglang.srt.utils import kill_process_tree+ from sglang.srt.utils.common import suppress_noisy_warnings++ suppress_noisy_warnings()+ server_args = prepare_server_args(_build_server_argv(args, overrides))+ from sglang.srt.entrypoints.http_server import launch_server++ try:+ launch_server(server_args)+ finally:+ kill_process_tree(os.getpid(), include_parent=False)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())