[Core] Implement Diffusion Profiler Support (#709)

Signed-off-by: lishunyang <lishunyang12@163.com>
Signed-off-by: SYLAR <125541396+lishunyang12@users.noreply.github.com>
This commit is contained in:
SYLAR authored and GitHub committed 2026-01-20 11:35:48 +08:00
1 parent 3fc4f988ea
commit a1c37cc6e3
13 files changed
+610 -68

No files matched your search

+120
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import multiprocessing as mp
import os
import time
import weakref
from collections.abc import Callable, Iterable
@@ -290,6 +291,125 @@ class DiffusionEngine:
def add_req_and_wait_for_response(self, requests: list[OmniDiffusionRequest]):
return scheduler.add_req(requests)
def start_profile(self, trace_filename: str | None = None) -> None:
"""
Start torch profiling on all diffusion workers.
Creates a directory (if needed) and sets up a base filename template
for per-rank profiler traces (typically saved as <template>_rank<N>.json).
Args:
trace_filename: Optional base filename (without extension or rank suffix).
If None, generates one using current timestamp.
"""
if trace_filename is None:
trace_filename = f"stage_0_diffusion_{int(time.time())}_rank"
trace_dir = os.environ.get("VLLM_TORCH_PROFILER_DIR", "./profiles")
# Expand ~ and ~user, then make absolute (robust against cwd changes)
trace_dir = os.path.expanduser(trace_dir)
trace_dir = os.path.abspath(trace_dir)
try:
os.makedirs(trace_dir, exist_ok=True)
except OSError as exc:
logger.error(f"Failed to create profiler directory {trace_dir}: {exc}")
raise
# Build final template path (without rank or extension — torch.profiler appends those)
full_template = os.path.join(trace_dir, trace_filename)
expected_pattern = f"{full_template}*.json"
logger.info(f"Starting diffusion profiling → {expected_pattern}")
# Also log the absolute directory once (useful in multi-node or containers)
logger.debug(f"Profiler output directory: {trace_dir}")
# Propagate to all workers
try:
self.collective_rpc(method="start_profile", args=(full_template,))
except Exception as e:
logger.error("Failed to start profiling on workers", exc_info=True)
raise RuntimeError(f"Could not start profiler: {e}") from e
def stop_profile(self) -> dict:
"""
Stop profiling on all workers and collect the final trace/table paths.
The worker (torch_profiler.py) now handles trace export, compression to .gz,
and deletion of the original .json file. This method only collects and
reports the paths returned by the workers.
Returns:
dict with keys:
- "traces": list of final trace file paths (usually .json.gz)
- "tables": list of table strings (one per rank)
"""
logger.info("Stopping diffusion profiling and collecting results...")
try:
# Give worker enough time — export + compression + table can be slow
results = self.collective_rpc(method="stop_profile", timeout=60000)
except Exception:
logger.error("Failed to stop profiling on workers", exc_info=True)
return {"traces": [], "tables": []}
output_files = {"traces": [], "tables": []}
successful_traces = 0
if not results:
logger.warning("No profiling results returned from any rank")
return output_files
for rank, res in enumerate(results):
if not isinstance(res, dict):
logger.warning(f"Rank {rank}: invalid result format (got {type(res)})")
continue
# 1. Trace file — should be .json.gz if compression succeeded
trace_path = res.get("trace")
if trace_path:
# We trust the worker — it created/compressed the file
logger.info(f"[Rank {rank}] Final trace: {trace_path}")
output_files["traces"].append(trace_path)
successful_traces += 1
# Optional: warn if path looks suspicious (e.g. still .json)
if not trace_path.endswith((".json.gz", ".json")):
logger.warning(f"Rank {rank}: unusual trace path extension: {trace_path}")
# 2. Table file — plain text
table = res.get("table")
if table:
output_files["tables"].append(table)
# Final summary logging
num_ranks = len(results)
if successful_traces > 0:
final_paths_str = ", ".join(output_files["traces"][:3])
if len(output_files["traces"]) > 3:
final_paths_str += f" ... (+{len(output_files['traces']) - 3} more)"
logger.info(
f"Profiling stopped. Collected {successful_traces} trace file(s) "
f"from {num_ranks} rank(s). "
f"Final trace paths: {final_paths_str}"
)
elif output_files["traces"]:
logger.info(
f"Profiling stopped but no traces were successfully collected. "
f"Reported paths: {', '.join(output_files['traces'][:3])}"
f"{' ...' if len(output_files['traces']) > 3 else ''}"
)
else:
logger.info("Profiling stopped — no trace files were collected from any rank.")
if output_files["tables"]:
logger.debug(f"Collected {len(output_files['tables'])} profiling table(s)")
return output_files
def _dummy_run(self):
"""A dummy run to warm up the model."""
prompt = "dummy run"
+9
View File
@@ -0,0 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from .torch_profiler import TorchProfiler
# Default profiler – can be changed later via config
CurrentProfiler = TorchProfiler
__all__ = ["CurrentProfiler", "TorchProfiler"]
+58
View File
@@ -0,0 +1,58 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from abc import ABC, abstractmethod
from vllm.logger import init_logger
logger = init_logger(__name__)
class ProfilerBase(ABC):
"""
Abstract base class for all diffusion profilers.
Defines the common interface used by GPUWorker and DiffusionEngine.
"""
@abstractmethod
def start(self, trace_path_template: str) -> str:
"""
Start profiling.
Args:
trace_path_template: Base path (without rank or extension).
e.g. "/tmp/profiles/sdxl_run"
Returns:
Full path of the trace file this rank will write.
"""
pass
@abstractmethod
def stop(self) -> str | None:
"""
Stop profiling and finalize/output the trace.
Returns:
Path to the saved trace file, or None if not active.
"""
pass
@abstractmethod
def get_step_context(self):
"""
Returns a context manager that advances one profiling step.
Should be a no-op (nullcontext) when profiler is not active.
"""
pass
@abstractmethod
def is_active(self) -> bool:
"""Return True if profiling is currently running."""
pass
@classmethod
def _get_rank(cls) -> int:
import os
return int(os.getenv("RANK", "0"))
@@ -0,0 +1,126 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
import subprocess
from contextlib import nullcontext
import torch
from torch.profiler import ProfilerActivity, profile
from vllm.logger import init_logger
from .base import ProfilerBase
logger = init_logger(__name__)
class TorchProfiler(ProfilerBase):
"""
Torch-based profiler configured for End-to-End continuous recording.
Uses 'on_trace_ready' to handle Trace export.
Compression is offloaded to a background subprocess to avoid blocking the worker loop.
"""
_profiler: profile | None = None
_trace_template: str = ""
@classmethod
def start(cls, trace_path_template: str) -> str:
"""
Start the profiler with the given trace path template.
"""
# 1. Cleanup any existing profiler
if cls._profiler is not None:
logger.warning("[Rank %s] Stopping existing Torch profiler", cls._get_rank())
cls._profiler.stop()
cls._profiler = None
rank = cls._get_rank()
# 2. Make path absolute
trace_path_template = os.path.abspath(trace_path_template)
cls._trace_template = trace_path_template
# Expected paths
json_file = f"{trace_path_template}_rank{rank}.json"
os.makedirs(os.path.dirname(json_file), exist_ok=True)
logger.info(f"[Rank {rank}] Starting End-to-End Torch profiler")
# 3. Define the on_trace_ready handler
def trace_handler(p):
nonlocal json_file
# A. Export JSON Trace
try:
p.export_chrome_trace(json_file)
logger.info(f"[Rank {rank}] Trace exported to {json_file}")
try:
subprocess.Popen(["gzip", "-f", json_file])
logger.info(f"[Rank {rank}] Triggered background compression for {json_file}")
# Update variable to point to the eventual file
json_file = f"{json_file}.gz"
except Exception as compress_err:
logger.warning(f"[Rank {rank}] Background gzip failed to start: {compress_err}")
except Exception as e:
logger.warning(f"[Rank {rank}] Failed to export trace: {e}")
# 4. Initialize profiler with long active period
cls._profiler = profile(
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
schedule=torch.profiler.schedule(
wait=0,
warmup=0,
active=100000, # long capture window
),
on_trace_ready=trace_handler,
record_shapes=True,
profile_memory=True,
with_stack=True,
with_flops=True,
)
# 5. Start profiling
cls._profiler.start()
# Return the expected final path
return f"{trace_path_template}_rank{rank}.json.gz"
@classmethod
def stop(cls) -> dict | None:
if cls._profiler is None:
return None
rank = cls._get_rank()
# Determine expected paths
base_path = f"{cls._trace_template}_rank{rank}"
gz_path = f"{base_path}.json.gz"
try:
# This triggers trace_handler synchronously
# Since we removed table generation and backgrounded compression, this returns fast.
cls._profiler.stop()
except Exception as e:
logger.warning(f"[Rank {rank}] Profiler stop failed: {e}")
cls._profiler = None
# We return the .gz path assuming background compression will succeed.
return {"trace": gz_path, "table": None}
@classmethod
def step(cls):
if cls._profiler is not None:
cls._profiler.step()
@classmethod
def is_active(cls) -> bool:
return cls._profiler is not None
@classmethod
def get_step_context(cls):
return nullcontext()
@@ -15,6 +15,7 @@ from collections.abc import Iterable
from contextlib import nullcontext
import torch
from torch.profiler import record_function
from vllm.config import LoadConfig
from vllm.logger import init_logger
from vllm.utils.mem_utils import DeviceMemoryProfiler, GiB_bytes
@@ -160,6 +161,7 @@ class GPUDiffusionModelRunner:
self.cache_backend.refresh(self.pipeline, req.num_inference_steps)
with set_forward_context(vllm_config=self.vllm_config, omni_diffusion_config=self.od_config):
output = self.pipeline.forward(req)
with record_function("pipeline_forward"):
output = self.pipeline.forward(req)
return output
@@ -28,6 +28,7 @@ from vllm_omni.diffusion.distributed.parallel_state import (
initialize_model_parallel,
)
from vllm_omni.diffusion.forward_context import set_forward_context
from vllm_omni.diffusion.profiler import CurrentProfiler
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.diffusion.worker.gpu_diffusion_model_runner import GPUDiffusionModelRunner
@@ -115,6 +116,16 @@ class GPUDiffusionWorker:
"""Generate output for the given requests."""
return self.execute_model(requests, self.od_config)
@classmethod
def start_profile(cls, trace_path_template: str) -> str:
"""Start profiling for this GPU worker."""
return CurrentProfiler.start(trace_path_template)
@classmethod
def stop_profile(cls) -> dict | None:
"""Stop profiling and return the result dictionary."""
return CurrentProfiler.stop()
def execute_model(self, reqs: list[OmniDiffusionRequest], od_config: OmniDiffusionConfig) -> DiffusionOutput:
"""Execute a forward pass by delegating to the model runner."""
assert self.model_runner is not None, "Model runner not initialized"