[perf] Add configurable diffusion compile granularity (#4603)

Signed-off-by: TaffyOfficial <2324465096@qq.com>
Co-authored-by: TaffyOfficial <2324465096@qq.com>
This commit is contained in:
TaffyOfficialandTaffyOfficial authored and GitHub committed 2026-07-24 15:22:06 +00:00
1 parent 84bbd57e4d
commit 93786c9cd3
15 files changed
+359 -15

No files matched your search

+14 -8
View File
@@ -53,23 +53,29 @@ def regionally_compile(
repeated_block_attrs = getattr(model, "_layerwise_offload_blocks_attrs", [])
# Check if we have modules with the specified class names
has_compiled_region = False
compiled_region_count = 0
# Build all compiled callables before mutating the model. This keeps setup
# failures atomic: callers can safely continue with the uncompiled model if
# torch.compile raises synchronously for any repeated block.
compiled_forwards: list[tuple[nn.Module, Any]] = []
for name, submod in model.named_modules():
if _matches_repeated_block(name, submod, repeated_blocks, repeated_block_attrs):
# Compile the block compute while keeping nn.Module.__call__ hooks
# outside the compiled graph.
submod.forward = torch.compile(submod.forward, *compile_args, **compile_kwargs)
has_compiled_region = True
compiled_region_count += 1
compiled_forwards.append(
(
submod,
torch.compile(submod.forward, *compile_args, **compile_kwargs),
)
)
if not has_compiled_region:
if not compiled_forwards:
logger.warning(f"Regional compilation skipped because {repeated_blocks} classes are not found in the model.")
else:
for submod, compiled_forward in compiled_forwards:
submod.forward = compiled_forward
logger.info(
"Regional compilation applied to %d module(s) for repeated blocks %s.",
compiled_region_count,
len(compiled_forwards),
repeated_blocks,
)
+28
View File
@@ -684,6 +684,10 @@ class OmniDiffusionConfig:
# Compilation
enforce_eager: bool = False
# Controls the generic compilation path used when a pipeline does not
# provide its own setup_compile() implementation.
diffusion_compile_granularity: str = "regional"
diffusion_compile_dynamic: bool = True
# Parallel weight loading (for faster diffusion model startup)
enable_multithread_weight_load: bool = True
@@ -880,6 +884,13 @@ class OmniDiffusionConfig:
)
def __post_init__(self):
if self.diffusion_compile_granularity not in {"regional", "full"}:
raise ValueError(
"diffusion_compile_granularity must be 'regional' or 'full', "
f"got {self.diffusion_compile_granularity!r}"
)
if not isinstance(self.diffusion_compile_dynamic, bool):
raise TypeError(f"diffusion_compile_dynamic must be a bool, got {type(self.diffusion_compile_dynamic)!r}")
self.master_port = self._resolve_master_port()
self.request_batch_max_wait_ms = float(self.request_batch_max_wait_ms or 0.0)
if self.request_batch_max_wait_ms < 0:
@@ -915,6 +926,23 @@ class OmniDiffusionConfig:
f"num_gpus ({self.num_gpus}) < parallel_config.world_size ({self.parallel_config.world_size})"
)
if self.diffusion_compile_granularity == "full":
incompatible_features = []
if self.parallel_config.use_hsdp:
incompatible_features.append("HSDP")
if self.parallel_config.sequence_parallel_size > 1:
incompatible_features.append("sequence parallelism")
if self.enable_cpu_offload:
incompatible_features.append("CPU offload")
if self.enable_layerwise_offload:
incompatible_features.append("layerwise offload")
if incompatible_features:
features = ", ".join(incompatible_features)
raise ValueError(
"diffusion_compile_granularity='full' is incompatible with "
f"{features}; use 'regional' compilation instead"
)
# Convert string dtype to torch.dtype if needed
if isinstance(self.dtype, str):
dtype_map = {
@@ -151,15 +151,33 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
if model is None:
return
compile_granularity = self.od_config.diffusion_compile_granularity
compile_dynamic = self.od_config.diffusion_compile_dynamic
try:
setattr(self.pipeline, attr_name, regionally_compile(model, dynamic=True))
logger.info("Model runner: %s compiled with torch.compile.", attr_name)
if compile_granularity == "full":
model.compile(dynamic=compile_dynamic)
compiled_model = model
else:
compiled_model = regionally_compile(model, dynamic=compile_dynamic)
setattr(self.pipeline, attr_name, compiled_model)
except Exception as e:
logger.warning(
"Model runner: torch.compile for %s failed: %s. Using eager mode.",
"Model runner: %s torch.compile setup for %s failed before activation: %s. "
"Continuing with the uncompiled model; lazy compilation errors can still "
"surface on the first request.",
compile_granularity,
attr_name,
e,
)
return
logger.info(
"Model runner: %s configured for lazy %s torch.compile with dynamic=%s; "
"compilation errors may surface on the first request.",
attr_name,
compile_granularity,
compile_dynamic,
)
def load_model(
self,