Last of four; stacked on #38048. The record is the operator's input; the bags are what is in effect. A reader that takes the record and reads a field off it gets the input, which is the wrong one of the two whenever resolution decided something -- and the mistake is silent, because for most fields and most launches the two agree. Several of these files already read both ways, sometimes in the same expression: ```python get_tokenizer( get_serving().tokenizer_path, tokenizer_mode=server_args.tokenizer_mode, # the input, not the decision ... ) ``` Sixty-odd files convert. Record field reads in runtime code go from 199 to 11. Nine parameters that the conversion emptied are dropped along with the argument at every call site -- the dead-parameter ratchet is what names them. ### "Runs after its process publishes" is a per-entry-point claim Most converted reads sit in the serving and model-executor layers, which only exist after publication, or in the two subprocess entry points, which publish first thing. Three places are not like that, and they keep reading the record they were handed: - **`HttpServerEngineAdapter`** launches the server as a *child*. The parent resolves the record and never publishes, so the adapter's own reads -- the launch banner, the API key in its readiness loop, the TP width in `update_weights_from_tensor` -- are of `self.server_args`. A bag read here fails closed in a bare process, or answers for an unrelated engine in one that happens to have published. - **`serve_grpc`** reads its sidecar port before the integrated servicer builds the `Engine` that publishes. The comment above that line already said so and already bound `cfg = resolving_view(server_args)` for it; the sidecar port and the port it derives from read `cfg`. - **`initialize_dp_attention`** runs from callers whose publish is not guaranteed, so its one predicate stays on the resolution view. `ROLE_NAMESPACE_SETS["dp_controller"]` gains `observability` and `serving`, because the controller's metrics gate, tracing setup and worker-port broadcast now read those namespaces. Under `SGLANG_ROLE_NAMESPACES=enforce` that set is what the process may read, so a conversion that reaches a new namespace has to widen it in the same change. ## Three things worth a reviewer's attention **Eleven reads were `getattr(record, "field", default)`.** An AST scan for attribute access does not see those, so the census that said "43 readers" was counting the shape it could match rather than the thing it was after. `incremental_streaming_output` was read that way twice, and the transcription tests were the only reason it surfaced. **Not every record read is a bag read waiting to happen.** A multimodal processor's `base_gpu_id` is the instance's, not the process's: two engines in one process keep different ones, and `test_publishing_another_config_does_not_move_the_device` exists to say so. It stays on the record while `rl_on_policy_target` beside it moves. `RequestMetricsExporter` is the same shape -- it is handed the directory it writes to, and a test builds several with different ones. `configure_logger` is a third: 17 call sites, one of which passes an `argparse.Namespace`, so it is not a global-context reader at all. Those eleven remaining reads are the ones with a reason. **The fixtures move with the code.** Tests that hung config off a mock manager now publish a record, which is what the serving layer reads; where a test states a value it says so with `override_server_args` instead of assigning through the mock. `test_hisparse_unit` is the last of them: it stubbed a `server_args` onto a fake scheduler to say the decode radix cache was off, and the value it was standing in for is the published default, so the stub goes and the class publishes. ## Two things CI caught that a local sweep could not **`unittest.TestCase.enterContext` is Python 3.11+.** The converted fixtures used it at 18 sites; `requires-python` is `>=3.10` and CI runs 3.10, so every one of them raised `AttributeError` there while passing on a newer local interpreter. They call `enter_override(self, ...)` now -- a four-line helper in `sglang/test/test_utils.py` over the override's own `install()` / `restore()`. **A batched sweep cannot see a missing publish.** Three fixtures needed a published config and did not have one; each *passed* inside a shard where some other file had published, and failed when run alone. The affected cases are `test_serving_completions` (which set `incremental_streaming_output` on the mock manager's record, where nothing reads it now), `test_qwen3_vl_feature_materialization` (same shape for `mm_enable_dp_encoder`), and the two Qwen Rust tests -- whose fixture already carried the comment `# Non-auto: get_resolved_model_impl would choke on a SimpleNamespace` next to the `model_impl` it sets, which is exactly what happened once `get_mm_processor_cls` started reading that value from the bag. Its `publish` mirrors `model_impl` now, like the four fields it already mirrored. ## Verification A full registered-unit sweep (648 files) against this stack's merge-base: 19 failures on both sides, the same 19, none of them config. That sweep is what caught 23 failures the file-scoped runs missed -- and, later, that the narrower 139-file list did not even contain the files this change reaches. It is also what caught the `test_hisparse_unit` fixture above: the file passes inside a shard where something else published, and fails when it is run on its own, which is why every failing file is re-run alone before it is counted.
158 lines
5.7 KiB
Python
158 lines
5.7 KiB
Python
import multiprocessing
|
|
import time
|
|
from typing import List, Optional, Tuple
|
|
|
|
import requests
|
|
import torch
|
|
|
|
from sglang.srt.arg_groups.overrides import resolving_view
|
|
from sglang.srt.arg_groups.serving_hook import ssl_verify_of
|
|
from sglang.srt.entrypoints.EngineBase import EngineBase
|
|
from sglang.srt.entrypoints.http_server import launch_server
|
|
from sglang.srt.server_args import ServerArgs
|
|
from sglang.srt.utils import MultiprocessingSerializer, kill_process_tree
|
|
|
|
|
|
def launch_server_process(server_args: ServerArgs) -> multiprocessing.Process:
|
|
# Resolve here, not in the child: the pipeline probes the device, and a
|
|
# forked child cannot re-initialize CUDA if this process already has. The
|
|
# child's gate then finds nothing left to do.
|
|
server_args.resolve_once()
|
|
|
|
p = multiprocessing.Process(target=launch_server, args=(server_args,))
|
|
p.start()
|
|
|
|
base_url = server_args.url()
|
|
timeout = 300.0 # Increased timeout to 5 minutes for downloading large models
|
|
start_time = time.perf_counter()
|
|
|
|
ssl_verify = ssl_verify_of(server_args)
|
|
# The adapter's own configuration, not the bags: this runs in the parent,
|
|
# and the record it was handed is published only inside the server child.
|
|
cfg = resolving_view(server_args)
|
|
|
|
with requests.Session() as session:
|
|
while time.perf_counter() - start_time < timeout:
|
|
try:
|
|
headers = {
|
|
"Content-Type": "application/json; charset=utf-8",
|
|
"Authorization": f"Bearer {cfg.api_key}",
|
|
}
|
|
response = session.get(
|
|
f"{base_url}/health_generate", headers=headers, verify=ssl_verify
|
|
)
|
|
if response.status_code == 200:
|
|
return p
|
|
except requests.RequestException:
|
|
pass
|
|
|
|
if not p.is_alive():
|
|
raise Exception("Server process terminated unexpectedly.")
|
|
|
|
time.sleep(2)
|
|
|
|
p.terminate()
|
|
raise TimeoutError("Server failed to start within the timeout period.")
|
|
|
|
|
|
class HttpServerEngineAdapter(EngineBase):
|
|
"""
|
|
You can use this class to launch a server from a VerlEngine instance.
|
|
We recommend using this class only you need to use http server.
|
|
Otherwise, you can use Engine directly.
|
|
"""
|
|
|
|
def __init__(self, **kwargs):
|
|
self.server_args = ServerArgs(**kwargs)
|
|
# This process launches the server as a child and never publishes, so
|
|
# every read here is of the record it just built -- a bag read would
|
|
# either fail closed or answer for an unrelated engine in the process.
|
|
cfg = resolving_view(self.server_args)
|
|
print(f"Launch HttpServerEngineAdapter at: {cfg.host}:{cfg.port}")
|
|
self.process = launch_server_process(self.server_args)
|
|
|
|
def _make_request(self, endpoint: str, payload: Optional[dict] = None):
|
|
"""Make a POST request to the specified endpoint with the given payload.
|
|
Args:
|
|
endpoint: The API endpoint to call
|
|
payload: The JSON payload to send (default: empty dict)
|
|
Returns:
|
|
The JSON response from the server
|
|
"""
|
|
url = f"{self.server_args.url()}/{endpoint}"
|
|
response = requests.post(
|
|
url, json=payload or {}, verify=ssl_verify_of(self.server_args)
|
|
)
|
|
response.raise_for_status()
|
|
return response.json()
|
|
|
|
def update_weights_from_tensor(
|
|
self,
|
|
named_tensors: List[Tuple[str, torch.Tensor]],
|
|
load_format: Optional[str] = None,
|
|
flush_cache: bool = False,
|
|
):
|
|
"""
|
|
Update model weights from tensor data. The HTTP server will only post meta data, and the real weights will be copied directly from GPUs.
|
|
Note: The model should be on GPUs rather than CPU for this functionality to work properly.
|
|
If you encounter issues, ensure your model is loaded on GPU devices rather than CPU.
|
|
"""
|
|
|
|
return self._make_request(
|
|
"update_weights_from_tensor",
|
|
{
|
|
"serialized_named_tensors": [
|
|
MultiprocessingSerializer.serialize(named_tensors, output_str=True)
|
|
for _ in range(resolving_view(self.server_args).tp_size)
|
|
],
|
|
"load_format": load_format,
|
|
"flush_cache": flush_cache,
|
|
},
|
|
)
|
|
|
|
def shutdown(self):
|
|
kill_process_tree(self.process.pid, wait_timeout=60)
|
|
|
|
def generate(
|
|
self,
|
|
prompt=None,
|
|
sampling_params=None,
|
|
input_ids=None,
|
|
image_data=None,
|
|
return_logprob=False,
|
|
logprob_start_len=None,
|
|
top_logprobs_num=None,
|
|
token_ids_logprob=None,
|
|
lora_path=None,
|
|
custom_logit_processor=None,
|
|
priority=None,
|
|
session_id=None,
|
|
):
|
|
payload = {
|
|
"text": prompt,
|
|
"sampling_params": sampling_params,
|
|
"input_ids": input_ids,
|
|
"image_data": image_data,
|
|
"return_logprob": return_logprob,
|
|
"logprob_start_len": logprob_start_len,
|
|
"top_logprobs_num": top_logprobs_num,
|
|
"token_ids_logprob": token_ids_logprob,
|
|
"lora_path": lora_path,
|
|
"custom_logit_processor": custom_logit_processor,
|
|
"priority": priority,
|
|
"session_id": session_id,
|
|
}
|
|
# Filter out None values
|
|
payload = {k: v for k, v in payload.items() if v is not None}
|
|
|
|
return self._make_request("generate", payload)
|
|
|
|
def release_memory_occupation(self):
|
|
return self._make_request("release_memory_occupation")
|
|
|
|
def resume_memory_occupation(self):
|
|
return self._make_request("resume_memory_occupation")
|
|
|
|
def flush_cache(self):
|
|
return self._make_request("flush_cache")
|