[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:
1 parent
3fc4f988ea
commit
a1c37cc6e3
13 files changed
+610
-68
No files matched your search
@@ -374,36 +374,71 @@ class OmniBase:
|
||||
e,
|
||||
)
|
||||
|
||||
def stop_profile(self, stages: list[int] | None = None) -> None:
|
||||
"""Stop profiling for specified stages.
|
||||
|
||||
Sends stop_profile command to stage workers to finalize and save traces.
|
||||
|
||||
Args:
|
||||
stages: List of stage IDs to stop profiling. If None, stops
|
||||
profiling for all stages.
|
||||
|
||||
Example:
|
||||
>>> omni.start_profile()
|
||||
>>> outputs = omni.generate(prompts, sampling_params)
|
||||
>>> omni.stop_profile()
|
||||
>>> # Traces saved to VLLM_TORCH_PROFILER_DIR/stage_X_<model_stage>/
|
||||
def stop_profile(self, stages: list[int] | None = None) -> dict:
|
||||
"""
|
||||
Synchronously stop profiling for specified stages and collect
|
||||
the file paths for traces and tables.
|
||||
"""
|
||||
if stages is None:
|
||||
stages = list(range(len(self.stage_list)))
|
||||
|
||||
all_results = {"traces": [], "tables": []}
|
||||
|
||||
for stage_id in stages:
|
||||
if stage_id < len(self.stage_list):
|
||||
try:
|
||||
self.stage_list[stage_id].submit({"type": OmniStageTaskType.PROFILER_STOP})
|
||||
logger.info("[%s] Sent stop_profile to stage-%s", self._name, stage_id)
|
||||
except Exception as e:
|
||||
stage = self.stage_list[stage_id]
|
||||
|
||||
# Check if the stage object has our new bridge method
|
||||
if hasattr(stage, "stop_profile"):
|
||||
logger.info("[%s] Requesting profile data collection from stage-%s", self._name, stage_id)
|
||||
|
||||
# This is the blocking call that triggers the RPC chain
|
||||
stage_data = stage.stop_profile()
|
||||
|
||||
if isinstance(stage_data, dict):
|
||||
# FIX: Handle both single key and list key formats
|
||||
traces = stage_data.get("trace") or stage_data.get("traces")
|
||||
tables = stage_data.get("table") or stage_data.get("tables")
|
||||
|
||||
# Debug logging
|
||||
logger.debug(f"[{self._name}] Stage-{stage_id} returned: {stage_data.keys()}")
|
||||
if traces:
|
||||
logger.debug(f"[{self._name}] Stage-{stage_id} traces type: {type(traces)}")
|
||||
if tables:
|
||||
logger.debug(f"[{self._name}] Stage-{stage_id} tables type: {type(tables)}")
|
||||
|
||||
# Handle single strings
|
||||
if traces:
|
||||
if isinstance(traces, str):
|
||||
all_results["traces"].append(traces)
|
||||
elif isinstance(traces, list):
|
||||
all_results["traces"].extend(traces)
|
||||
|
||||
# Handle single strings
|
||||
if tables:
|
||||
if isinstance(tables, str):
|
||||
all_results["tables"].append(tables)
|
||||
elif isinstance(tables, list):
|
||||
all_results["tables"].extend(tables)
|
||||
else:
|
||||
logger.warning(f"[{self._name}] Stage-{stage_id} returned no table data")
|
||||
else:
|
||||
logger.warning(f"[{self._name}] Stage-{stage_id} returned non-dict data: {type(stage_data)}")
|
||||
else:
|
||||
# Fallback for non-diffusion stages
|
||||
logger.warning(
|
||||
"[%s] Failed to send stop_profile to stage-%s: %s",
|
||||
"[%s] Stage-%s does not support synchronous stop_profile. Falling back to async.",
|
||||
self._name,
|
||||
stage_id,
|
||||
e,
|
||||
)
|
||||
stage.submit({"type": OmniStageTaskType.PROFILER_STOP})
|
||||
|
||||
# Final debug output
|
||||
logger.info(
|
||||
f"[{self._name}] Collected {len(all_results['traces'])} trace(s) and {len(all_results['tables'])} table(s)"
|
||||
)
|
||||
|
||||
return all_results
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close all stage processes and clean up resources."""
|
||||
@@ -518,7 +553,6 @@ class Omni(OmniBase):
|
||||
return self._run_generation_with_generator(prompts, sampling_params_list)
|
||||
else:
|
||||
outputs = list(self._run_generation(prompts, sampling_params_list))
|
||||
self.close()
|
||||
return outputs
|
||||
except Exception as e:
|
||||
logger.exception("[Orchestrator] Failed to run generation: %s", e)
|
||||
|
||||
@@ -126,3 +126,26 @@ class OmniDiffusion:
|
||||
self.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def start_profile(self, trace_filename: str | None = None) -> None:
|
||||
"""Start profiling for the diffusion model.
|
||||
|
||||
Args:
|
||||
trace_filename: Optional base filename for trace files.
|
||||
If None, a timestamp-based name will be generated.
|
||||
"""
|
||||
if hasattr(self, "engine") and self.engine:
|
||||
self.engine.start_profile(trace_filename)
|
||||
else:
|
||||
raise RuntimeError("Diffusion engine not initialized")
|
||||
|
||||
def stop_profile(self) -> dict:
|
||||
"""Stop profiling and return profiling results.
|
||||
|
||||
Returns:
|
||||
Dictionary containing paths to trace and table files.
|
||||
"""
|
||||
if hasattr(self, "engine") and self.engine:
|
||||
return self.engine.stop_profile()
|
||||
else:
|
||||
raise RuntimeError("Diffusion engine not initialized")
|
||||
@@ -13,6 +13,7 @@ import multiprocessing as mp
|
||||
import os
|
||||
import queue
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from dataclasses import fields
|
||||
from typing import Any
|
||||
@@ -211,6 +212,38 @@ class OmniStage:
|
||||
self._in_q = in_q
|
||||
self._out_q = out_q
|
||||
|
||||
def stop_profile(self) -> dict:
|
||||
"""Stop profiling by sending a signal to worker and waiting for response."""
|
||||
if self._in_q is None or self._out_q is None:
|
||||
logger.warning(f"[Stage-{self.stage_id}] Queues not initialized, cannot stop profile.")
|
||||
return {}
|
||||
|
||||
logger.info(f"[Stage-{self.stage_id}] Sending PROFILER_STOP to worker...")
|
||||
self.submit({"type": OmniStageTaskType.PROFILER_STOP})
|
||||
|
||||
# Wait for result from worker
|
||||
try:
|
||||
# Profiling stop might take time to flush files, give it 180s
|
||||
response = self._out_q.get(timeout=60000)
|
||||
|
||||
if isinstance(response, dict):
|
||||
if response.get("type") == "profiler_result":
|
||||
return response.get("data", {})
|
||||
elif "error" in response:
|
||||
logger.error(f"[Stage-{self.stage_id}] Profiler error: {response['error']}")
|
||||
return {}
|
||||
|
||||
# If we got something else (e.g. late generation result), we might lose it here,
|
||||
# but usually profiling stop is called when generation is done.
|
||||
logger.warning(
|
||||
f"[Stage-{self.stage_id}] Received unexpected message while waiting for profiler: {response}"
|
||||
)
|
||||
return {}
|
||||
|
||||
except queue.Empty:
|
||||
logger.error(f"[Stage-{self.stage_id}] Timeout waiting for profiler results.")
|
||||
return {}
|
||||
|
||||
def init_stage_worker(
|
||||
self,
|
||||
model: str,
|
||||
@@ -620,33 +653,6 @@ def _stage_worker(
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
logger.debug("Engine initialized")
|
||||
|
||||
# Check if stage engine supports profiling (via vLLM's built-in profiler)
|
||||
has_profiler = hasattr(stage_engine, "start_profile") and hasattr(stage_engine, "stop_profile")
|
||||
if has_profiler:
|
||||
logger.info(
|
||||
"[Stage-%s] vLLM profiler support detected (model_stage=%s)",
|
||||
stage_id,
|
||||
engine_args.get("model_stage", None),
|
||||
)
|
||||
|
||||
def handle_profiler_task(task_type: OmniStageTaskType) -> None:
|
||||
"""Handle profiler task."""
|
||||
if task_type == OmniStageTaskType.PROFILER_START:
|
||||
if has_profiler:
|
||||
try:
|
||||
stage_engine.start_profile()
|
||||
logger.info("[Stage-%s] Profiler started via vLLM engine", stage_id)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to start profiler: %s", stage_id, e)
|
||||
elif task_type == OmniStageTaskType.PROFILER_STOP:
|
||||
if has_profiler:
|
||||
try:
|
||||
stage_engine.stop_profile()
|
||||
logger.info("[Stage-%s] Profiler stopped via vLLM engine", stage_id)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to stop profiler: %s", stage_id, e)
|
||||
|
||||
# Initialize OmniConnectors if configured
|
||||
connectors = {}
|
||||
if connectors_config:
|
||||
@@ -667,6 +673,45 @@ def _stage_worker(
|
||||
max_batch_size = int(runtime_cfg.get("max_batch_size", 1) or 1)
|
||||
logger.info(f"Max batch size: {max_batch_size}")
|
||||
|
||||
def handle_profiler_task_local(task_type: OmniStageTaskType) -> dict:
|
||||
"""Handle profiler task locally in the worker process."""
|
||||
if task_type == OmniStageTaskType.PROFILER_START:
|
||||
if stage_type == "diffusion":
|
||||
try:
|
||||
profile_dir = _os.environ.get("VLLM_TORCH_PROFILER_DIR", "./profiles")
|
||||
_os.makedirs(profile_dir, exist_ok=True)
|
||||
trace_filename = f"stage_{stage_id}_diffusion_{int(_time.time())}"
|
||||
stage_engine.start_profile(trace_filename=trace_filename)
|
||||
logger.info("[Stage-%s] Diffusion Torch profiler started", stage_id)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to start diffusion profiler: %s", stage_id, e)
|
||||
else:
|
||||
try:
|
||||
stage_engine.start_profile()
|
||||
logger.info("[Stage-%s] vLLM profiler started", stage_id)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to start vLLM profiler: %s", stage_id, e)
|
||||
return {}
|
||||
|
||||
elif task_type == OmniStageTaskType.PROFILER_STOP:
|
||||
if stage_type == "diffusion":
|
||||
try:
|
||||
# CRITICAL: Capture return value
|
||||
result_data = stage_engine.stop_profile()
|
||||
logger.info("[Stage-%s] Diffusion Torch profiler stopped", stage_id)
|
||||
return result_data
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to stop diffusion profiler: %s", stage_id, e)
|
||||
return {}
|
||||
else:
|
||||
try:
|
||||
stage_engine.stop_profile()
|
||||
logger.info("[Stage-%s] vLLM profiler stopped", stage_id)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to stop vLLM profiler: %s", stage_id, e)
|
||||
return {}
|
||||
return {}
|
||||
|
||||
# Batch processing loop
|
||||
while True:
|
||||
task = in_q.get()
|
||||
@@ -679,7 +724,10 @@ def _stage_worker(
|
||||
|
||||
# Handle profiler control commands
|
||||
if is_profiler_task(task_type):
|
||||
handle_profiler_task(task_type)
|
||||
profiler_data = handle_profiler_task_local(task_type)
|
||||
# If it was a STOP command, we must reply to the Orchestrator
|
||||
if task_type == OmniStageTaskType.PROFILER_STOP:
|
||||
out_q.put({"type": "profiler_result", "data": profiler_data})
|
||||
continue
|
||||
|
||||
batch_tasks: list[dict[str, Any]] = [task]
|
||||
@@ -694,8 +742,10 @@ def _stage_worker(
|
||||
# Handle profiler commands that arrive during batching
|
||||
extra_type = extra.get("type") if isinstance(extra, dict) else None
|
||||
if is_profiler_task(extra_type):
|
||||
handle_profiler_task(extra_type)
|
||||
continue # Don't add to batch_tasks
|
||||
p_data = handle_profiler_task_local(extra_type)
|
||||
if extra_type == OmniStageTaskType.PROFILER_STOP:
|
||||
out_q.put({"type": "profiler_result", "data": p_data})
|
||||
continue
|
||||
batch_tasks.append(extra)
|
||||
end_time = _time.time()
|
||||
duration = end_time - start_time
|
||||
@@ -1141,31 +1191,41 @@ async def _stage_worker_async(
|
||||
await stage_engine.reset_mm_cache()
|
||||
logger.debug("[Stage-%s] Engine initialized", stage_id)
|
||||
|
||||
# Check if stage engine supports profiling (via vLLM's built-in profiler)
|
||||
has_profiler = hasattr(stage_engine, "start_profile") and hasattr(stage_engine, "stop_profile")
|
||||
if has_profiler:
|
||||
logger.info(
|
||||
"[Stage-%s] vLLM profiler support detected for async stage (model_stage=%s)",
|
||||
stage_id,
|
||||
engine_args.get("model_stage", None),
|
||||
)
|
||||
|
||||
async def handle_profiler_task_async(task_type: OmniStageTaskType) -> None:
|
||||
"""Handle profiler task asynchronously."""
|
||||
"""Handle profiler task asynchronously for both LLM and diffusion stages."""
|
||||
if task_type == OmniStageTaskType.PROFILER_START:
|
||||
if has_profiler:
|
||||
if stage_type == "diffusion":
|
||||
try:
|
||||
# Sync call is safe here — diffusion profiling is lightweight
|
||||
profile_dir = os.environ.get("VLLM_TORCH_PROFILER_DIR", "./profiles")
|
||||
os.makedirs(profile_dir, exist_ok=True)
|
||||
trace_filename = f"stage_{stage_id}_diffusion_{int(time.time())}"
|
||||
stage_engine.start_profile(trace_filename=trace_filename)
|
||||
logger.info("[Stage-%s] Diffusion Torch profiler started", stage_id)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to start diffusion profiler: %s", stage_id, e)
|
||||
else:
|
||||
try:
|
||||
await stage_engine.start_profile()
|
||||
logger.info("[Stage-%s] Profiler started via vLLM engine", stage_id)
|
||||
logger.info("[Stage-%s] vLLM profiler started", stage_id)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to start profiler: %s", stage_id, e)
|
||||
logger.warning("[Stage-%s] Failed to start vLLM profiler: %s", stage_id, e)
|
||||
|
||||
elif task_type == OmniStageTaskType.PROFILER_STOP:
|
||||
if has_profiler:
|
||||
if stage_type == "diffusion":
|
||||
try:
|
||||
trace_files = stage_engine.stop_profile()
|
||||
logger.info("[Stage-%s] Diffusion Torch profiler stopped", stage_id)
|
||||
if trace_files:
|
||||
logger.info("Diffusion trace files: %s", trace_files)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to stop diffusion profiler: %s", stage_id, e)
|
||||
else:
|
||||
try:
|
||||
await stage_engine.stop_profile()
|
||||
logger.info("[Stage-%s] Profiler stopped via vLLM engine", stage_id)
|
||||
logger.info("[Stage-%s] vLLM profiler stopped", stage_id)
|
||||
except Exception as e:
|
||||
logger.warning("[Stage-%s] Failed to stop profiler: %s", stage_id, e)
|
||||
logger.warning("[Stage-%s] Failed to stop vLLM profiler: %s", stage_id, e)
|
||||
|
||||
# Signal readiness to orchestrator and send vllm_config back to main process
|
||||
try:
|
||||
|
||||
Reference in new issue
Block a user