# Copyright 2026 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from dataclasses import dataclass, field
from typing import Optional
from omegaconf import MISSING
from verl.base_config import BaseConfig
from verl.utils.profiler import ProfilerConfig
from verl.workers.config.disaggregation import DisaggregationConfig
from verl.workers.config.model import MtpConfig
from verl.workers.config.rollout import (
AgentLoopConfig,
CheckpointEngineConfig,
MultiTurnConfig,
PrometheusConfig,
)
__all__ = [
"DiffusionARConfig",
"DiffusionRolloutAlgoConfig",
"DiffusionPipelineConfig",
"DiffusionSamplingConfig",
"DiffusionRolloutConfig",
]
[docs]
@dataclass
class DiffusionRolloutAlgoConfig(BaseConfig):
"""Algorithm configuration for the SDE-based diffusion rollout."""
noise_level: float = 1.0
sde_type: str = "sde"
sde_window_size: Optional[int] = None
sde_window_range: Optional[list[int]] = None
sde_contiguous: bool = True
# MixGRPO-only configs
sample_strategy: str = "random"
iters_per_group: int = 1
sde_window_seed: int = 0
def __post_init__(self):
if self.sample_strategy not in ("random", "progressive"):
raise ValueError(f"Unknown sample_strategy: {self.sample_strategy!r}")
if self.sample_strategy == "progressive" and self.iters_per_group <= 0:
raise ValueError(f"iters_per_group must be positive, got {self.iters_per_group}.")
[docs]
@dataclass
class DiffusionPipelineConfig(BaseConfig):
# for pipeline specific sampling parameters
height: int = 512
width: int = 512
num_inference_steps: int = 10
output_type: str = "image"
# Additional named artifacts required by rewards/logging, including previews with a latent primary.
requested_outputs: Optional[list[str]] = None
true_cfg_scale: float = 1.0
max_sequence_length: int = 512
guidance_scale: Optional[float] = None
# CFG for the frozen pretrained anchor in forward-process training.
reference_guidance_scale: float = 4.5
reference_image_short_edge: Optional[int] = None
# Wan2.2 video generation: number of frames (81 = ~3s at 24fps)
num_frames: int = 1
# Audio-video generation frame rate.
frame_rate: float = 24.0
# Task label forwarded to the pipeline request contract, read by vLLM-Omni as
# the request `task`; values are pipeline-specific (e.g. t2va / fl2va / ref2va).
task: Optional[str] = None
# Frame indices (e.g. keyframe positions) for pipelines that condition on them.
frame_indices: Optional[list[int]] = None
# Named canvas aspect ratio for pipelines that accept one (e.g. 16:9);
# the set of supported ratios is pipeline-specific.
aspect_ratio: Optional[str] = None
# Flow-matching sigma-schedule shift for the video stream (maps to vllm-omni's flow_shift)
video_flow_shift: float = 12.0
@dataclass
class DiffusionARConfig(BaseConfig):
# AR part sampling config
# text generation when needed
temperature: float = 1.0
top_k: int = 0
top_p: float = 1.0
repetition_penalty: float = 1.0
response_length: int = 1024
[docs]
@dataclass
class DiffusionSamplingConfig(BaseConfig):
# for validation only
n: int = 1
m: int = 1 # Optional. AR stage 1, number of samples per prompt
seed: int = 42
pipeline: DiffusionPipelineConfig = field(default_factory=DiffusionPipelineConfig)
algo: DiffusionRolloutAlgoConfig = field(default_factory=DiffusionRolloutAlgoConfig)
ar: DiffusionARConfig = field(default_factory=DiffusionARConfig)
[docs]
@dataclass
class DiffusionRolloutConfig(BaseConfig):
_mutable_fields = {
"max_model_len",
"load_format",
"engine_kwargs",
"prompt_length",
"expert_parallel_size",
"full_determinism",
"seed",
"max_num_seqs",
}
name: Optional[str] = MISSING
mode: str = "async"
nnodes: int = 0
n_gpus_per_node: int = 8
n: int = 1
m: int = 1 # Optional. AR stage 1, number of samples per prompt
# Base seed for deterministic training rollout RNG. Per-step base is
# ``seed + global_step - 1``. null disables rollout seeding.
seed: Optional[int] = 42
full_determinism: bool = False
prompt_length: int = 512
# Final prompt-embedding sequence length after combining all text encoders.
# Falls back to pipeline.max_sequence_length for single-encoder models.
max_prompt_embed_length: Optional[int] = None
dtype: str = "bfloat16"
gpu_memory_utilization: float = 0.5
# Budget for standalone rollout replicas on dedicated GPUs; None keeps
# gpu_memory_utilization.
standalone_gpu_memory_utilization: Optional[float] = None
enforce_eager: bool = False
cudagraph_capture_sizes: Optional[list] = None
# vLLM-omni diffusion attention backend.
# Default FLASH_ATTN_3_HUB pairs with actor attn_backend=_flash_3_varlen_hub.
rollout_attn_backend: str = "FLASH_ATTN_3_HUB"
free_cache_engine: bool = True
data_parallel_size: int = 1
expert_parallel_size: int = 1
tensor_model_parallel_size: int = 2
# Ulysses and Ring multiply the DiT tensor-parallel footprint.
ulysses_degree: int = 1
ring_degree: int = 1
# Text-encoder TP reuses the DiT group: 1 or its full size.
text_encoder_tp_size: int = 1
# VAE parallelism reuses the DiT ranks rather than allocating extra GPUs.
vae_patch_parallel_size: int = 1
vae_parallel_mode: str = "tile"
vae_use_tiling: bool = False
pipeline_model_parallel_size: int = 1
max_num_batched_tokens: int = 8192
logprobs_mode: Optional[str] = "processed_logprobs"
scheduling_policy: Optional[str] = "fcfs"
val_kwargs: DiffusionSamplingConfig = field(default_factory=DiffusionSamplingConfig)
max_model_len: Optional[int] = None
max_num_seqs: int = 1024
# Ray max_concurrency of the rollout server actor.
ray_actor_max_concurrency: int = 1024
# When True, the vLLM-Omni engine runs the registered pipeline in
# step-execution mode.
step_execution: bool = False
enable_prompt_embed_cache: bool = False
prompt_embed_cache_size: int = 32
enable_prompt_embed_cache_routing_affinity: bool = False
# note that the logprob computation should belong to the actor
log_prob_micro_batch_size_per_gpu: Optional[int] = None
log_prob_use_dynamic_bsz: bool = False
log_prob_max_token_len_per_gpu: int = 16384
disable_log_stats: bool = True
engine_kwargs: dict = field(default_factory=dict)
pipeline: DiffusionPipelineConfig = field(default_factory=DiffusionPipelineConfig)
calculate_log_probs: bool = False
ar_calculate_log_probs: bool = False
rollout_adapter: str = "default"
agent: AgentLoopConfig = field(default_factory=AgentLoopConfig)
multi_turn: MultiTurnConfig = field(default_factory=MultiTurnConfig)
# Use Prometheus to collect and monitor rollout statistics
prometheus: PrometheusConfig = field(default_factory=PrometheusConfig)
# Checkpoint Engine config for update weights from trainer to rollout
checkpoint_engine: CheckpointEngineConfig = field(default_factory=CheckpointEngineConfig)
enable_chunked_prefill: bool = True
# Diffusion models generate latents without autoregressive token prefix caching; keep False.
enable_prefix_caching: bool = False
load_format: str = "dummy"
layered_summon: bool = False
skip_tokenizer_init: bool = True
quantization: Optional[str] = None
enable_rollout_routing_replay: bool = False
enable_sleep_mode: bool = True
mtp: Optional[MtpConfig] = field(default_factory=MtpConfig)
profiler: Optional[ProfilerConfig] = None
algo: Optional[DiffusionRolloutAlgoConfig] = field(default_factory=DiffusionRolloutAlgoConfig)
disaggregation: DisaggregationConfig = field(default_factory=DisaggregationConfig)
external_lib: Optional[str] = None
# For multi-stage generation (e.g, text rewriting -> image generation)
ar: Optional[DiffusionARConfig] = field(default_factory=DiffusionARConfig)
[docs]
def to_vllm_omni_attention_config(self) -> dict:
"""Convert the rollout backend to vLLM-Omni's canonical config form."""
return {"default": {"backend": self.rollout_attn_backend}}
def __post_init__(self):
"""Validate the diffusion rollout config"""
if self.max_prompt_embed_length is not None and self.max_prompt_embed_length <= 0:
raise ValueError(f"max_prompt_embed_length must be positive when set, got {self.max_prompt_embed_length}.")
if self.mode == "sync":
raise ValueError(
"Rollout mode 'sync' has been removed. Please set "
"`actor_rollout_ref.rollout.mode=async` or remove the mode setting entirely."
)
if self.rollout_adapter not in ("default", "old"):
raise ValueError(
f"Invalid diffusion rollout rollout_adapter: {self.rollout_adapter}. Must be one of ['default', 'old']."
)
if self.prompt_embed_cache_size <= 0:
raise ValueError(f"prompt_embed_cache_size must be positive, got {self.prompt_embed_cache_size}.")
if self.pipeline_model_parallel_size > 1:
if self.name == "vllm_omni":
raise NotImplementedError(
f"Current rollout {self.name=} not implemented pipeline_model_parallel_size > 1 yet."
)
for name in ("ulysses_degree", "ring_degree", "vae_patch_parallel_size", "text_encoder_tp_size"):
value = getattr(self, name)
if type(value) is not int or value < 1:
raise ValueError(f"{name} must be >= 1 and an integer, got {value!r}.")
if self.vae_parallel_mode not in {"tile", "spatial_shard_height", "spatial_shard_width"}:
raise ValueError(f"Invalid vae_parallel_mode: {self.vae_parallel_mode!r}.")
dit_world_size = self.tensor_model_parallel_size * self.ulysses_degree * self.ring_degree
if self.text_encoder_tp_size not in (1, dit_world_size):
raise ValueError(
"text_encoder_tp_size must be either 1 or equal to the DiT group size "
f"(tensor_model_parallel_size * ulysses_degree * ring_degree = {dit_world_size}), "
f"got {self.text_encoder_tp_size}."
)
if self.ulysses_degree * self.ring_degree > 1:
omni_kwargs = (self.engine_kwargs or {}).get("vllm_omni", {}) or {}
if (
self.name != "vllm_omni"
or self.data_parallel_size != 1
or self.pipeline_model_parallel_size != 1
or omni_kwargs.get("output_mode") == "ar"
or (self.disaggregation and self.disaggregation.get("enabled", False))
):
raise ValueError("Rollout sequence parallelism requires vllm_omni diffusion with DP=PP=1 and no PD.")