Skip to content

Commit 738ad3c

Browse files
committed
[TRTLLM-17271][refactor] Read trtllm-serve environment variables through one typed module
tensorrt_llm/serve/envs.py declares every environment variable that tensorrt_llm/serve/ (except scripts/) and the trtllm-serve CLI read: 54 variables in three blocks (34 deployment switches, 18 launcher-internal variables, 2 set by MPI or Slurm), each with the reader that reproduces the parsing of the call site it replaces, its default, a description and the secret flag. Every in-scope read now goes through envs.NAME, read at access time; writes, the launcher enums and the whole-environment copy stay where they are. tests/test_common/serve/env_lint.py rejects direct os.environ reads in those directories and value imports from the module (which would freeze the value at import time); tests/unittest/serve/test_envs.py runs it and pins every reader's parsing in six environment states, so no default or parser changes. The VisualGen part of the lint lives under tests/unittest/serve/api/visual_gen/ so CI's VisualGen narrowing runs it. Signed-off-by: JunyiXu-nv <219237550+JunyiXu-nv@users.noreply.github.com>
1 parent ed7d996 commit 738ad3c

24 files changed

Lines changed: 1676 additions & 106 deletions

‎tensorrt_llm/commands/serve.py‎

Lines changed: 33 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@
7777
resolve_auto_reasoning_parser)
7878
from tensorrt_llm.logger import logger, severity_map
7979
from tensorrt_llm.mapping import CpType
80-
from tensorrt_llm.serve import OpenAIDisaggServer, OpenAIServer
80+
from tensorrt_llm.serve import OpenAIDisaggServer, OpenAIServer, envs
8181
from tensorrt_llm.serve._frontend_processes import (
8282
_frontend_affinity_sockets, _init_multi_frontend_mode,
8383
_signal_frontend_ready, _spawn_attached_frontends,
@@ -499,7 +499,7 @@ def _share_prometheus_multiproc_dir(llm, ipc_dir: str) -> None:
499499
Not via set_prometheus_multiproc_dir(): it keeps only its latest
500500
TemporaryDirectory alive, so OpenAIServer's later call would delete this one.
501501
"""
502-
if os.environ.get("PROMETHEUS_MULTIPROC_DIR"):
502+
if envs.PROMETHEUS_MULTIPROC_DIR:
503503
return
504504
if llm.args.return_perf_metrics or llm.args.perf_metrics_output_dir:
505505
path = tempfile.mkdtemp(prefix="prometheus_", dir=ipc_dir)
@@ -613,7 +613,7 @@ def _check_context_only_settings(llm_args: dict, *, warn: bool) -> None:
613613
"""
614614
if not _dense_dwdp_setting(llm_args.get("dwdp_config")):
615615
return
616-
role = _serving_role(os.environ.get(DisaggLauncherEnvs.TLLM_DISAGG_ROLE))
616+
role = _serving_role(envs.TRTLLM_DISAGG_ROLE)
617617
if role == "generation":
618618
raise click.BadParameter(
619619
f"{_DENSE_DWDP_FOR_CONTEXT_ONLY} Remove it from this server's "
@@ -694,7 +694,7 @@ def launch_server(
694694
# launcher is its parent.
695695
multi_frontend_serving = None
696696
if multi_frontend.is_attached_frontend:
697-
attached_launcher_uds = os.environ.pop(LAUNCHER_UDS_ENV, None)
697+
attached_launcher_uds = envs.consume(LAUNCHER_UDS_ENV)
698698
if attached_launcher_uds is not None:
699699
multi_frontend_serving = MultiFrontendServing(
700700
launcher_uds=attached_launcher_uds,
@@ -719,7 +719,7 @@ def launch_server(
719719
# frontends behind one SO_REUSEPORT port, a follow-up request may
720720
# land on a sibling that has no record of the previous response.
721721
# Disable storage group-wide (OpenAIServer.enable_store).
722-
if not os.getenv("TRTLLM_RESPONSES_API_DISABLE_STORE"):
722+
if not envs.TRTLLM_RESPONSES_API_DISABLE_STORE:
723723
logger.warning(
724724
"num_serve_frontends > 1: stateful Responses API storage "
725725
"(store/previous_response_id) is disabled; the per-frontend "
@@ -818,7 +818,7 @@ def launch_server(
818818
_apply_fastapi_middlewares(server.app, middleware)
819819

820820
# Optionally disable GC (default: not disabled)
821-
if os.getenv("TRTLLM_SERVER_DISABLE_GC", "0") == "1":
821+
if envs.TRTLLM_SERVER_DISABLE_GC:
822822
gc.disable()
823823

824824
_signal_frontend_ready(multi_frontend)
@@ -1513,7 +1513,7 @@ def serve(
15131513
"--enable_sleep_mode is only supported by the HTTP server.")
15141514
runtime_control_api_key = None
15151515
if enable_sleep_mode:
1516-
runtime_control_api_key = os.getenv("TRTLLM_RUNTIME_CONTROL_API_KEY")
1516+
runtime_control_api_key = envs.TRTLLM_RUNTIME_CONTROL_API_KEY
15171517
if not runtime_control_api_key:
15181518
raise click.UsageError(
15191519
"--enable_sleep_mode requires TRTLLM_RUNTIME_CONTROL_API_KEY.")
@@ -2339,7 +2339,7 @@ def disaggregated(
23392339
# increment, and observed that `count0` (obtained by `gc.get_count()`)
23402340
# increases by fewer than 1,000 after every 200,000 requests, while the
23412341
# maximum value of `count0` exceeded 3,000,000 during the test.
2342-
if os.getenv("TRTLLM_DISAGG_SERVER_DISABLE_GC", "1") == "1":
2342+
if envs.TRTLLM_DISAGG_SERVER_DISABLE_GC:
23432343
gc.disable()
23442344

23452345
set_lifecycle_phase("serving")
@@ -2479,14 +2479,13 @@ def _serve_coordinator_and_fleet(disagg_cfg, config_file,
24792479
from tensorrt_llm.serve.disagg_coordinator import DisaggCoordinatorService
24802480

24812481
public_host, public_port = disagg_cfg.hostname, disagg_cfg.port
2482-
coord_port = int(
2483-
os.environ.get(DisaggWorkerEnvs.TLLM_DISAGG_COORDINATOR_PORT,
2484-
public_port - 1))
2482+
coord_port = envs.TRTLLM_DISAGG_COORDINATOR_PORT
2483+
if coord_port is None:
2484+
coord_port = public_port - 1
24852485
# The fleet is co-located with the implicit coordinator, so route its hot
24862486
# /select,/finish over a Unix domain socket (avoids the TCP loopback stack
24872487
# that dominated per-request latency). Opt-out via the UDS env = "0".
2488-
use_uds = os.environ.get(DisaggWorkerEnvs.TLLM_DISAGG_COORDINATOR_UDS,
2489-
"1") == "1"
2488+
use_uds = envs.TRTLLM_DISAGG_COORDINATOR_UDS
24902489
coord_uds = (
24912490
f"/tmp/trtllm_disagg_coord_{public_port}.sock" # nosec B108
24922491
if use_uds else None)
@@ -2591,13 +2590,13 @@ def _init_fleet_worker_process():
25912590
# A worker is a plain HTTP process, never an MPI rank; drop WEB_CONCURRENCY so
25922591
# it is never itself re-forked into multiple uvicorn workers.
25932592
os.environ.pop("WEB_CONCURRENCY", None)
2594-
if os.getenv("TRTLLM_DISAGG_SERVER_DISABLE_GC", "1") == "1":
2593+
if envs.TRTLLM_DISAGG_SERVER_DISABLE_GC:
25952594
gc.disable()
25962595

25972596
# This is a fresh Python process, so the TRT-LLM logger defaults to WARNING
25982597
# and would drop the workers' INFO logs (per-request [ttft_split] /
25992598
# [coord_api]). Restore the parent's level.
2600-
_worker_log_level = os.environ.get(DisaggWorkerEnvs.TLLM_DISAGG_LOG_LEVEL)
2599+
_worker_log_level = envs.TRTLLM_DISAGG_LOG_LEVEL
26012600
if _worker_log_level:
26022601
logger.set_level(_worker_log_level)
26032602

@@ -2621,18 +2620,14 @@ def _build_disagg_server_from_env() -> "OpenAIDisaggServer":
26212620
disagg-id) is read from ``TLLM_DISAGG_WORKER_PROCESS_ID``, which the launcher
26222621
set explicitly per worker (see ``worker_local_process_id``).
26232622
"""
2624-
config_file = os.environ[DisaggWorkerEnvs.TLLM_DISAGG_CONFIG_FILE]
2625-
coordinator_url = os.environ[DisaggWorkerEnvs.TLLM_DISAGG_COORDINATOR_URL]
2626-
metadata_config_file = os.environ.get(
2627-
DisaggWorkerEnvs.TLLM_DISAGG_METADATA_CONFIG_FILE)
2628-
request_timeout = int(
2629-
os.environ.get(DisaggWorkerEnvs.TLLM_DISAGG_REQUEST_TIMEOUT, "180"))
2630-
server_start_timeout = int(
2631-
os.environ.get(DisaggWorkerEnvs.TLLM_DISAGG_SERVER_START_TIMEOUT,
2632-
"180"))
2623+
config_file = envs.TRTLLM_DISAGG_CONFIG_FILE
2624+
coordinator_url = envs.TRTLLM_DISAGG_COORDINATOR_URL
2625+
metadata_config_file = envs.TRTLLM_DISAGG_METADATA_CONFIG_FILE
2626+
request_timeout = envs.TRTLLM_DISAGG_REQUEST_TIMEOUT
2627+
server_start_timeout = envs.TRTLLM_DISAGG_SERVER_START_TIMEOUT
26332628

26342629
disagg_cfg = parse_disagg_config_file(config_file)
2635-
schedule_style = os.environ.get(DisaggWorkerEnvs.TLLM_DISAGG_SCHEDULE_STYLE)
2630+
schedule_style = envs.TRTLLM_DISAGG_SCHEDULE_STYLE
26362631
if schedule_style:
26372632
disagg_cfg.schedule_style = schedule_style
26382633
metadata_server_cfg = parse_metadata_server_config_file(
@@ -2685,18 +2680,18 @@ def _run_fleet_worker_impl():
26852680
except OSError as e:
26862681
raise RuntimeError(
26872682
f"Fleet worker failed to SO_REUSEPORT-bind {host}:{port}: {e}")
2688-
pidx = os.environ.get(DisaggWorkerEnvs.TLLM_DISAGG_WORKER_PROCESS_ID, "0")
2683+
pidx = envs.TRTLLM_DISAGG_WORKER_PROCESS_ID
26892684
logger.info(f"Fleet worker process_id={pidx} bound {host}:{port} "
26902685
f"(SO_REUSEPORT)")
26912686
set_lifecycle_phase("serving")
26922687
asyncio.run(server(host, port, sockets=[s]))
26932688

26942689

26952690
def set_cuda_device():
2696-
if (os.getenv("OMPI_COMM_WORLD_RANK")):
2697-
env_global_rank = int(os.environ["OMPI_COMM_WORLD_RANK"])
2698-
elif (os.getenv("SLURM_PROCID")):
2699-
env_global_rank = int(os.environ["SLURM_PROCID"])
2691+
if (envs.OMPI_COMM_WORLD_RANK):
2692+
env_global_rank = int(envs.OMPI_COMM_WORLD_RANK)
2693+
elif (envs.SLURM_PROCID):
2694+
env_global_rank = int(envs.SLURM_PROCID)
27002695
else:
27012696
raise RuntimeError("Could not determine rank from environment")
27022697
device_id = env_global_rank % device_count()
@@ -2787,8 +2782,7 @@ def disaggregated_mpi_worker(config_file: Optional[str], log_level: str,
27872782
_refuse_dense_dwdp_on_generation_servers(disagg_cfg)
27882783

27892784
from tensorrt_llm._utils import mpi_rank
2790-
if os.environ.get(DisaggLauncherEnvs.
2791-
TLLM_DISAGG_RUN_REMOTE_MPI_SESSION_CLIENT) != "1":
2785+
if envs.TLLM_DISAGG_RUN_REMOTE_MPI_SESSION_CLIENT != "1":
27922786
set_cuda_device()
27932787
# Importing mpi4py after setting CUDA device. This is needed to work around an issue with mpi4py and CUDA
27942788
from mpi4py.futures import MPICommExecutor
@@ -2797,19 +2791,17 @@ def disaggregated_mpi_worker(config_file: Optional[str], log_level: str,
27972791
from tensorrt_llm.llmapi.disagg_utils import split_world_comm
27982792

27992793
blocker = _shared_draft_kv_blocker(disagg_cfg.server_configs)
2800-
if blocker is not None and os.environ.get(
2801-
"TRTLLM_DISAGG_SHARED_DRAFT_KV") == "1":
2794+
shared_draft_kv = envs.TRTLLM_DISAGG_SHARED_DRAFT_KV
2795+
if blocker is not None and shared_draft_kv == "1":
28022796
raise click.UsageError(
28032797
f"TRTLLM_DISAGG_SHARED_DRAFT_KV=1 requires {blocker}.")
2804-
if os.environ.get("TRTLLM_DISAGG_SHARED_DRAFT_KV") in (None, "auto"):
2798+
if shared_draft_kv in (None, "auto"):
28052799
os.environ["TRTLLM_DISAGG_SHARED_DRAFT_KV"] = ("0"
28062800
if blocker else "auto")
28072801

28082802
# Run a server with the underlying LLM invokes a RemoteMPISessionClient
2809-
if os.environ.get(DisaggLauncherEnvs.
2810-
TLLM_DISAGG_RUN_REMOTE_MPI_SESSION_CLIENT) == "1":
2811-
instance_idx = os.environ.get(
2812-
DisaggLauncherEnvs.TLLM_DISAGG_INSTANCE_IDX)
2803+
if envs.TLLM_DISAGG_RUN_REMOTE_MPI_SESSION_CLIENT == "1":
2804+
instance_idx = envs.TLLM_DISAGG_INSTANCE_IDX
28132805
server_cfg = disagg_cfg.server_configs[int(instance_idx)]
28142806

28152807
llm_args = _build_llm_args_from_disagg_server_cfg(server_cfg.other_args)
@@ -2883,7 +2875,7 @@ class DisaggWorkerEnvs(StrEnum):
28832875

28842876
def _launch_disaggregated_server(disagg_config_file: str, llm_args: dict):
28852877
# Launching the server
2886-
instance_idx = os.environ.get(DisaggLauncherEnvs.TLLM_DISAGG_INSTANCE_IDX)
2878+
instance_idx = envs.TLLM_DISAGG_INSTANCE_IDX
28872879
assert instance_idx is not None, f"{DisaggLauncherEnvs.TLLM_DISAGG_INSTANCE_IDX} should be set by the launcher"
28882880
disagg_config = parse_disagg_config_file(disagg_config_file)
28892881
server_cfg = disagg_config.server_configs[int(instance_idx)]
@@ -2934,8 +2926,7 @@ def _launch_disaggregated_leader(sub_comm, instance_idx: int, config_file: str,
29342926
os.environ[DisaggLauncherEnvs.TLLM_DISAGG_INSTANCE_IDX] = str(instance_idx)
29352927

29362928
logger.debug(
2937-
f"proxy controller address: {os.environ[LlmLauncherEnvs.TLLM_SPAWN_PROXY_PROCESS_IPC_ADDR]}"
2938-
)
2929+
f"proxy controller address: {envs.TLLM_SPAWN_PROXY_PROCESS_IPC_ADDR}")
29392930

29402931
# The MPI-related environment variables will invoke duplicate MPI_Init in
29412932
# the forked process, so we need to remove them before launching the server

‎tensorrt_llm/serve/AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ Name files and symbols here, never line numbers.
2929
Check: `tests/unittest/serve/test_layering.py`.
3030
- VisualGen serve tests live under a path that contains `visual_gen/`
3131
(`tests/unittest/serve/api/visual_gen/`), or CI selection misses them.
32+
- Environment variables: read them only through `serve/envs.py`, where each one is declared
33+
once (name, kind, default, description, secret). Check: `tests/unittest/serve/test_envs.py`.
3234

3335
## Moving code
3436

‎tensorrt_llm/serve/_frontend_processes.py‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
from tensorrt_llm.llmapi.mpi_session import split_mpi_env
2121
from tensorrt_llm.logger import logger
22+
from tensorrt_llm.serve import envs
2223

2324

2425
class FrontendStartupCancelled(RuntimeError):
@@ -56,9 +57,7 @@ def _init_multi_frontend_mode(llm_args: dict, enabled: bool) -> MultiFrontendMod
5657
)
5758
return MultiFrontendMode(1, False)
5859

59-
mode = MultiFrontendMode(
60-
llm_args.get("num_serve_frontends", 1), os.getenv("TLLM_EXECUTOR_ATTACH_INFO") is not None
61-
)
60+
mode = MultiFrontendMode(llm_args.get("num_serve_frontends", 1), envs.TLLM_EXECUTOR_ATTACH_INFO)
6261
if mode.is_launcher and llm_args.get("orchestrator_type") is not None:
6362
raise ValueError(
6463
"num_serve_frontends > 1 requires the default (classic IPC) "
@@ -155,7 +154,7 @@ def _wait_attached_frontends_ready(
155154
report_failure: Callable[[int, str, str], None] | None = None,
156155
) -> None:
157156
"""Block until every attached frontend writes its READY byte."""
158-
timeout = float(os.getenv("TLLM_FRONTEND_READY_TIMEOUT", "300"))
157+
timeout = envs.TLLM_FRONTEND_READY_TIMEOUT
159158
deadline = time.monotonic() + timeout
160159
pending = dict(zip(ready_fds, children))
161160
with selectors.DefaultSelector() as selector:
@@ -205,7 +204,7 @@ def _signal_frontend_ready(multi_frontend: MultiFrontendMode) -> None:
205204
middleware registration) has succeeded; the launcher blocks group
206205
startup on this byte (see _wait_attached_frontends_ready).
207206
"""
208-
ready_fd = os.environ.pop("TLLM_FRONTEND_READY_FD", None)
207+
ready_fd = envs.consume("TLLM_FRONTEND_READY_FD")
209208
if not (multi_frontend.is_attached_frontend and ready_fd):
210209
return
211210
fd = int(ready_fd)
@@ -292,8 +291,8 @@ def _frontend_affinity_sockets(
292291
reserved: dict[int, socket.socket] = {}
293292
try:
294293
if ports and multi_frontend.is_attached_frontend:
295-
frontend_id = int(os.environ["TLLM_EXECUTOR_FRONTEND_ID"])
296-
inherited_fd = os.environ.pop("TLLM_FRONTEND_AFFINITY_FD", None)
294+
frontend_id = envs.TLLM_EXECUTOR_FRONTEND_ID
295+
inherited_fd = envs.consume("TLLM_FRONTEND_AFFINITY_FD")
297296
if inherited_fd is not None:
298297
own = socket.socket(fileno=int(inherited_fd))
299298
own.set_inheritable(False)

‎tensorrt_llm/serve/anthropic_batches.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,12 @@
3535

3636
import asyncio
3737
import json
38-
import os
3938
from dataclasses import dataclass, field
4039
from datetime import datetime, timedelta, timezone
4140
from typing import Any, Awaitable, Callable, Dict, List, Literal, Optional, Tuple
4241

4342
from tensorrt_llm.logger import logger
43+
from tensorrt_llm.serve import envs
4444
from tensorrt_llm.serve.anthropic_protocol import (
4545
AnthropicBatchRequestCounts,
4646
AnthropicBatchRequestItem,
@@ -73,7 +73,7 @@ def _rfc3339(value: datetime) -> str:
7373

7474

7575
def _int_env(name: str, default: int) -> int:
76-
raw = os.environ.get(name)
76+
raw = getattr(envs, name)
7777
if not raw:
7878
return default
7979
try:

‎tensorrt_llm/serve/chat_tokenization.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@
1515

1616
from __future__ import annotations
1717

18-
import os
1918
from typing import TYPE_CHECKING, Callable, Optional, cast
2019

2120
from transformers import PretrainedConfig
2221

22+
from tensorrt_llm.serve import envs
2323
from tensorrt_llm.serve.openai_protocol import ChatCompletionRequest
2424

2525
if TYPE_CHECKING:
@@ -40,7 +40,7 @@ def uses_harmony_tokenization(
4040
model_type: Optional[str] = None,
4141
model_type_resolver: Optional[Callable[[], Optional[str]]] = None,
4242
) -> bool:
43-
if os.getenv("DISABLE_HARMONY_ADAPTER", "0") == "1":
43+
if envs.DISABLE_HARMONY_ADAPTER:
4444
return False
4545
if use_harmony is not None:
4646
return use_harmony

‎tensorrt_llm/serve/disagg_coordinator.py‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636
"""
3737

3838
import asyncio
39-
import os
4039
import time
4140
from abc import ABC, abstractmethod
4241
from typing import Any, Dict, Optional, Tuple
@@ -53,6 +52,7 @@
5352
worker_local_process_id, # noqa: F401
5453
)
5554
from tensorrt_llm.logger import logger
55+
from tensorrt_llm.serve import envs
5656
from tensorrt_llm.serve.cluster_storage import (
5757
ClusterStorage,
5858
WatchEventType,
@@ -80,18 +80,12 @@
8080
]
8181

8282
COORDINATOR_RESERVATION_TIMEOUT_ENV = "TRTLLM_DISAGG_COORDINATOR_RESERVATION_TIMEOUT"
83-
COORDINATOR_RESERVATION_TIMEOUT_DEFAULT_S = 180.0
8483
COORDINATOR_RESERVATION_LOCK_STRIPES = 256
8584
COORDINATOR_STATE_SYNC_INTERVAL_S = 3.0
8685

8786

8887
def coordinator_reservation_timeout() -> float:
89-
return float(
90-
os.environ.get(
91-
COORDINATOR_RESERVATION_TIMEOUT_ENV,
92-
COORDINATOR_RESERVATION_TIMEOUT_DEFAULT_S,
93-
)
94-
)
88+
return envs.TRTLLM_DISAGG_COORDINATOR_RESERVATION_TIMEOUT
9589

9690

9791
class DisaggCoordinator(ABC):
@@ -405,9 +399,7 @@ async def cluster_info(self) -> Dict[str, Any]:
405399
return info
406400

407401
async def _wait_for_all_servers_ready(self) -> None:
408-
import os
409-
410-
gen_only = os.getenv("TRTLLM_DISAGG_BENCHMARK_GEN_ONLY") == "1"
402+
gen_only = envs.TRTLLM_DISAGG_BENCHMARK_GEN_ONLY
411403

412404
async def check_servers_ready():
413405
elapsed_time = 0

0 commit comments

Comments
 (0)