diff --git a/Magpie/modes/benchmark/benchmarker.py b/Magpie/modes/benchmark/benchmarker.py index c5bbb8f..1610434 100644 --- a/Magpie/modes/benchmark/benchmarker.py +++ b/Magpie/modes/benchmark/benchmarker.py @@ -234,7 +234,28 @@ def run(self, task_id: Optional[str] = None) -> BenchmarkResult: result.errors.append(f"AgentX setup failed: {e}") return result - # 0b. Optionally pick idle GPU(s) and pin VISIBLE_DEVICES. + # 1. Copy Magpie generic scripts to InferenceX/benchmarks/ + if not self._managed_agentx: + self._prepare_benchmark_scripts() + + # 2. Determine runner type from GPU + runner_type = runner_type or self._get_runner_type() + + # 3. Find and validate benchmark script BEFORE container starts + try: + benchmark_script = self._get_benchmark_script(runner_type) + logger.info(f"Selected benchmark script: {benchmark_script}") + except FileNotFoundError as e: + result = BenchmarkResult( + framework=self.config.framework, + model=self.config.model, + scenario=self.config.scenario, + ) + result.success = False + result.errors.append(str(e)) + return result + + # Optionally pick idle GPU(s) and pin VISIBLE_DEVICES. # When server_lifecycle will reuse an existing HTTP server, skip # find_idle_gpus so ROCR/HIP/CUDA_VISIBLE_* are not reshuffled versus # the already-running server's physical devices. @@ -245,7 +266,9 @@ def run(self, task_id: Optional[str] = None) -> BenchmarkResult: ) skip_idle_gpu_for_reuse = bool(lifecycle_server_healthy) try: - if skip_idle_gpu_for_reuse: + if self._is_http_client(benchmark_script): + logger.info("HTTP-only benchmark client: skipping GPU selection") + elif skip_idle_gpu_for_reuse: # Restores Docker GPU visibility for an eligible reuse chain. # A mismatch is reported by the lifecycle executor below; GPU # discovery must not fail first just because the old server is @@ -268,27 +291,6 @@ def run(self, task_id: Optional[str] = None) -> BenchmarkResult: result.errors.append(str(e)) return result - # 1. Copy Magpie generic scripts to InferenceX/benchmarks/ - if not self._managed_agentx: - self._prepare_benchmark_scripts() - - # 2. Determine runner type from GPU - runner_type = runner_type or self._get_runner_type() - - # 3. Find and validate benchmark script BEFORE container starts - try: - benchmark_script = self._get_benchmark_script(runner_type) - logger.info(f"Selected benchmark script: {benchmark_script}") - except FileNotFoundError as e: - result = BenchmarkResult( - framework=self.config.framework, - model=self.config.model, - scenario=self.config.scenario, - ) - result.success = False - result.errors.append(str(e)) - return result - # 4. Create workspace workspace = self.workspace_mgr.create(self.config.to_dict()) @@ -955,6 +957,16 @@ def _validate_results(self, result: BenchmarkResult) -> bool: return False + def _is_http_client(self, benchmark_script: str, *, phase: str = "all") -> bool: + """Identify HTTP-only execution before selecting or exposing GPUs.""" + return phase == "client" or ( + phase == "all" + and not self.config.is_agentx + and Path(benchmark_script).parent == Path("benchmarks") + and Path(benchmark_script).name in MAGPIE_BUILTIN_SCRIPTS + and bool(self.config.get_env_vars().get("BENCHMARK_BASE_URL", "").strip()) + ) + def _build_docker_command( self, docker_image: str, @@ -978,8 +990,9 @@ def _build_docker_command( Returns: Docker command as list of strings """ - # Detect GPU vendor for device flags - vendor, arch = detect_gpu() + benchmark_script = self._get_benchmark_script(runner_type) + env_vars = self.config.get_env_vars() + client_only = self._is_http_client(benchmark_script, phase=phase) cmd = ["docker", "run"] if detach: @@ -1002,18 +1015,23 @@ def _build_docker_command( ] ) - # Add GPU-specific flags - if vendor == GPUVendor.AMD: - cmd.extend([ - "--device=/dev/kfd", - "--device=/dev/dri", - "--cap-add=SYS_PTRACE", - "--security-opt", "seccomp=unconfined", - ]) - elif vendor == GPUVendor.NVIDIA: - cmd.extend([ - "--gpus", "all", - ]) + # HTTP-only clients do not need GPU devices or serving privileges. + if client_only: + # The client also opens one socket per in-flight request. + cmd.extend(["--ulimit", "nofile=65536:65536"]) + else: + vendor, arch = detect_gpu() + if vendor == GPUVendor.AMD: + cmd.extend([ + "--device=/dev/kfd", + "--device=/dev/dri", + "--cap-add=SYS_PTRACE", + "--security-opt", "seccomp=unconfined", + ]) + elif vendor == GPUVendor.NVIDIA: + cmd.extend([ + "--gpus", "all", + ]) # HuggingFace cache mount hf_cache = self.config.hf_cache_path or os.path.expanduser("~/.cache/huggingface") @@ -1037,8 +1055,6 @@ def _build_docker_command( cmd.extend(["-v", f"{workspace}:/workspace"]) # Environment variables - benchmark_script = self._get_benchmark_script(runner_type) - env_vars = self.config.get_env_vars() self._set_generic_eval_defaults(env_vars, benchmark_script) env_vars["RESULT_FILENAME"] = "inferencex_result" env_vars["RESULT_DIR"] = "/workspace" diff --git a/docs/reference/benchmark-config.md b/docs/reference/benchmark-config.md index e785733..9ba61fd 100644 --- a/docs/reference/benchmark-config.md +++ b/docs/reference/benchmark-config.md @@ -133,6 +133,15 @@ benchmark: benchmark_script: null # Override benchmark script ``` +With a built-in fixed-sequence benchmark script, setting +`benchmark.envs.BENCHMARK_BASE_URL` runs only the HTTP client against that +endpoint. It skips automatic GPU selection. Its Docker container does not +request GPU devices or serving privileges, and has an open-file limit of +65,536 for concurrent requests. +The explicit client phase uses the same CPU-only permissions. Server-only +and normal combined server/client launches retain their GPU options. +Custom scripts retain them unless explicitly launched in the client phase. + ## AgentX trace replay Enable AgentX with one line. For a new installation, Magpie checks out diff --git a/tests/unit/modes/test_benchmarker.py b/tests/unit/modes/test_benchmarker.py index 392e768..ee4d101 100644 --- a/tests/unit/modes/test_benchmarker.py +++ b/tests/unit/modes/test_benchmarker.py @@ -47,6 +47,54 @@ def successful_result(): ) +@pytest.mark.parametrize( + "script,endpoint,client_only", + [ + ("sglang_mi355x.sh", "http://server:8000", True), + ("sglang_mi355x.sh", "", False), + ("custom.sh", "http://server:8000", False), + ], +) +def test_run_http_client_without_gpus(monkeypatch, tmp_path, script, endpoint, client_only): + config = make_config( + tmp_path, framework="sglang", runner_type="mi355x", run_mode="docker", + docker_image="image:test", benchmark_script=script, + gpu_selection=GpuSelectionConfig(auto=True), + envs={"BENCHMARK_BASE_URL": endpoint}, + ) + benchmarks = Path(config.inferencex_path) / "benchmarks" + benchmarks.mkdir(parents=True) + (benchmarks / "custom.sh").write_text("#!/bin/bash\n") + mode = BenchmarkMode(config, output_dir=str(tmp_path / "results")) + monkeypatch.setattr(benchmarker, "ensure_inferencex_available", lambda path: path) + monkeypatch.setattr(mode, "_select_image", lambda: "image:test") + + def no_gpus(**kwargs): + raise RuntimeError("no GPUs on this host") + + def no_detection(): + pytest.fail("HTTP-only clients must not detect GPUs") + + monkeypatch.setattr(benchmarker, "find_idle_gpus", no_gpus) + monkeypatch.setattr(benchmarker, "detect_gpu", no_detection) + + def execute(command, workspace): + assert "nofile=65536:65536" in command + assert "--privileged" not in command and "--gpus" not in command + (workspace / "inferencex_result.json").write_text("{}") + return successful_result(), "", "" + + monkeypatch.setattr(mode, "_execute_benchmark", execute) + monkeypatch.setattr( + benchmarker.ResultParser, "parse_inferencex_result", + lambda *args, **kwargs: successful_result(), + ) + result = mode.run() + assert result.success is client_only + if not client_only: + assert any("no GPUs on this host" in error for error in result.errors) + + def test_run_local_happy_path(monkeypatch, tmp_path): config = make_config(tmp_path) mode = BenchmarkMode(config, output_dir=str(tmp_path / "results")) @@ -527,6 +575,48 @@ def test_build_commands_and_script_resolution(monkeypatch, tmp_path): assert env["MAGPIE_SERVER_PID_FILE"].endswith("pid") +@pytest.mark.parametrize("vendor", [GPUVendor.AMD, GPUVendor.NVIDIA]) +@pytest.mark.parametrize( + "phase,endpoint,script,needs_gpu", + [ + ("all", "http://server:8000", "sglang_mi355x.sh", False), + ("client", "", "sglang_mi355x.sh", False), + ("all", "", "sglang_mi355x.sh", True), + ("server", "", "sglang_mi355x.sh", True), + ("all", "http://server:8000", "custom.sh", True), + ("all", "http://server:8000", "custom/sglang_mi355x.sh", True), + ], +) +def test_docker_client_permissions( + monkeypatch, tmp_path, vendor, phase, endpoint, script, needs_gpu +): + config = make_config(tmp_path, envs={"BENCHMARK_BASE_URL": endpoint}) + mode = BenchmarkMode(config) + monkeypatch.setattr(mode, "_get_benchmark_script", lambda runner: f"benchmarks/{script}") + + def detect(): + assert needs_gpu, "an HTTP client must not require GPU detection" + return vendor, "test" + + monkeypatch.setattr(benchmarker, "detect_gpu", detect) + command = mode._build_docker_command("image:test", tmp_path, "mi355x", phase=phase) + privileged = { + "--cap-add=SYS_PTRACE", + "--device=/dev/kfd", "--device=/dev/dri", "--security-opt", + } + assert "--privileged" not in command and "--cap-add=CAP_SYS_ADMIN" not in command + if needs_gpu and vendor == GPUVendor.AMD: + assert privileged.issubset(command) + else: + assert not privileged.intersection(command) + assert ("--gpus" in command) == (needs_gpu and vendor == GPUVendor.NVIDIA) + assert ("nofile=65536:65536" in command) == (not needs_gpu) + assert "--network=host" in command + assert f"MAGPIE_RUN_PHASE={phase}" in command + assert f"BENCHMARK_BASE_URL={endpoint}" in command + assert command[-1] == f"cd /opt/InferenceX && bash benchmarks/{script}" + + def test_prepare_scripts_select_runner_and_docker_nvidia_mounts(monkeypatch, tmp_path): inferencex = tmp_path / "InferenceX" config = make_config(