Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions python/sglang/multimodal_gen/configs/pipeline_configs/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,19 @@ def calculate_condition_image_size(self, image, width, height) -> tuple[int, int
def prepare_sigmas(self, sigmas, num_inference_steps):
return sigmas

def get_classifier_free_guidance_scale(self, batch, guidance_scale: float) -> float:
return guidance_scale

def postprocess_cfg_noise(
self,
batch,
noise_pred: torch.Tensor,
noise_pred_cond: torch.Tensor,
) -> torch.Tensor:
# Model-specific CFG variants can override this hook
# e.g. Qwen-Image's true-CFG norm matching.
return noise_pred

## For ImageVAEEncodingStage
def preprocess_condition_image(
self, image, target_width, target_height, _vae_image_processor
Expand Down Expand Up @@ -314,6 +327,9 @@ def prepare_latent_shape(self, batch, batch_size, num_frames):

return shape

def get_latent_dtype(self, prompt_dtype: torch.dtype) -> torch.dtype:
return prompt_dtype

def allow_set_num_frames(self):
return False

Expand Down Expand Up @@ -348,6 +364,15 @@ def gather_latents_for_sp(self, latents):
latents = sequence_model_parallel_all_gather(latents, dim=2)
return latents

def gather_noise_pred_for_sp(self, batch, noise_pred):
noise_pred = self.gather_latents_for_sp(noise_pred)
raw_latent_shape = getattr(batch, "raw_latent_shape", None)
if raw_latent_shape is not None and noise_pred.dim() == 3:
orig_s = raw_latent_shape[1]
if noise_pred.shape[1] > orig_s:
noise_pred = noise_pred[:, :orig_s, :]
return noise_pred

def preprocess_vae_image(self, batch, vae_image_processor):
pass

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,32 @@ def _resolve_qwen_edit_per_prompt_images(prompt_list, image_list):
return [[image] for image in image_list]


def _shard_qwen_edit_img_cache_for_sp(
img_cache: torch.Tensor, noisy_img_seq_len: int, device: torch.device
) -> torch.Tensor:
noisy_img_cache = shard_rotary_emb_for_sp(img_cache[:noisy_img_seq_len, :])
condition_img_cache = shard_rotary_emb_for_sp(img_cache[noisy_img_seq_len:, :])
return torch.cat([noisy_img_cache, condition_img_cache], dim=0).to(device=device)


def _shard_qwen_edit_freqs_cis_for_sp(freqs_cis, noisy_img_seq_len, device):
if isinstance(freqs_cis[0], torch.Tensor) and freqs_cis[0].dim() == 2:
img_cache, txt_cache = freqs_cis
return (
_shard_qwen_edit_img_cache_for_sp(img_cache, noisy_img_seq_len, device),
txt_cache,
)

(img_cos, img_sin), (txt_cos, txt_sin) = freqs_cis
return (
(
_shard_qwen_edit_img_cache_for_sp(img_cos, noisy_img_seq_len, device),
_shard_qwen_edit_img_cache_for_sp(img_sin, noisy_img_seq_len, device),
),
(txt_cos, txt_sin),
)


# Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._pack_latents
def _pack_latents(latents, batch_size, num_channels_latents, height, width):
latents = latents.view(
Expand Down Expand Up @@ -144,12 +170,40 @@ class QwenImagePipelineConfig(ImagePipelineConfig):
def prepare_sigmas(self, sigmas, num_inference_steps):
return self._prepare_sigmas(sigmas, num_inference_steps)

def get_classifier_free_guidance_scale(self, batch, guidance_scale: float) -> float:
if batch.true_cfg_scale is not None:
return batch.true_cfg_scale
return guidance_scale

def postprocess_cfg_noise(
self,
batch,
noise_pred: torch.Tensor,
noise_pred_cond: torch.Tensor,
) -> torch.Tensor:
# Qwen-Image follows the official diffusers true-CFG behavior:
# after combining cond/uncond with true_cfg_scale, match the per-token norm
# back to the conditional branch.
if (
batch.true_cfg_scale is None
or batch.true_cfg_scale <= 1.0
or not batch.do_classifier_free_guidance
):
return noise_pred

cond_norm = torch.norm(noise_pred_cond, dim=-1, keepdim=True)
noise_norm = torch.norm(noise_pred, dim=-1, keepdim=True).clamp_min(1e-12)
return noise_pred * (cond_norm / noise_norm)

def prepare_image_processor_kwargs(self, batch, neg=False):
prompt = batch.prompt if not neg else batch.negative_prompt
if prompt:
prompt_template_encode = "<|im_start|>system\nDescribe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>{}<|im_end|>\n<|im_start|>assistant\n"
txt = prompt_template_encode.format(batch.prompt)
return dict(text=[txt], padding=True)
prompt_list = _normalize_prompt_list(prompt)
txt = [
prompt_template_encode.format(cur_prompt) for cur_prompt in prompt_list
]
return dict(text=txt, padding=True)
else:
return {}

Expand Down Expand Up @@ -310,11 +364,9 @@ def _prepare_edit_cond_kwargs(
1 * (height // vae_scale_factor // 2) * (width // vae_scale_factor // 2)
)

img_cache, txt_cache = freqs_cis
noisy_img_cache = shard_rotary_emb_for_sp(img_cache[:noisy_img_seq_len, :])
img_cache = torch.cat(
[noisy_img_cache, img_cache[noisy_img_seq_len:, :]], dim=0
).to(device=device)
img_cache, txt_cache = _shard_qwen_edit_freqs_cis_for_sp(
freqs_cis, noisy_img_seq_len, device
)
return {
"txt_seq_lens": txt_seq_lens,
"freqs_cis": (img_cache, txt_cache),
Expand Down Expand Up @@ -500,33 +552,11 @@ def _prepare_edit_cond_kwargs(
1 * (height // vae_scale_factor // 2) * (width // vae_scale_factor // 2)
)

if isinstance(freqs_cis[0], torch.Tensor) and freqs_cis[0].dim() == 2:
img_cache, txt_cache = freqs_cis
noisy_img_cache = shard_rotary_emb_for_sp(img_cache[:noisy_img_seq_len, :])
img_cache = torch.cat(
[noisy_img_cache, img_cache[noisy_img_seq_len:, :]], dim=0
).to(device=device)
return {
"txt_seq_lens": txt_seq_lens,
"freqs_cis": (img_cache, txt_cache),
"img_shapes": img_shapes,
}

(img_cos, img_sin), (txt_cos, txt_sin) = freqs_cis
noisy_img_cos = shard_rotary_emb_for_sp(img_cos[:noisy_img_seq_len, :])
noisy_img_sin = shard_rotary_emb_for_sp(img_sin[:noisy_img_seq_len, :])

# concat back the img_cos for input image (since it is not sp-shared later)
img_cos = torch.cat([noisy_img_cos, img_cos[noisy_img_seq_len:, :]], dim=0).to(
device=device
)
img_sin = torch.cat([noisy_img_sin, img_sin[noisy_img_seq_len:, :]], dim=0).to(
device=device
)

return {
"txt_seq_lens": txt_seq_lens,
"freqs_cis": ((img_cos, img_sin), (txt_cos, txt_sin)),
"freqs_cis": _shard_qwen_edit_freqs_cis_for_sp(
freqs_cis, noisy_img_seq_len, device
),
"img_shapes": img_shapes,
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,11 @@ def prepare_neg_cond_kwargs(self, batch, device, rotary_emb, dtype):

def post_denoising_loop(self, latents, batch):
return latents

def shard_latents_for_sp(self, batch, latents):
# Sana's DiT uses local attention kernels and does not preserve semantics
# when spatial latents are sequence-sharded.
return latents, False

def gather_latents_for_sp(self, latents):
return latents
87 changes: 41 additions & 46 deletions python/sglang/multimodal_gen/configs/pipeline_configs/zimage.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class ZImagePipelineConfig(ImagePipelineConfig):
task_type: ModelTaskType = ModelTaskType.T2I
dit_config: DiTConfig = field(default_factory=ZImageDitConfig)
vae_config: VAEConfig = field(default_factory=FluxVAEConfig)
text_encoder_precisions: tuple[str, ...] = field(default_factory=lambda: ("bf16",))
text_encoder_configs: tuple[EncoderConfig, ...] = field(
default_factory=lambda: (Qwen3TextConfig(),)
)
Expand All @@ -62,19 +63,22 @@ class ZImagePipelineConfig(ImagePipelineConfig):
F_PATCH_SIZE: int = 1

def tokenize_prompt(self, prompts: list[str], tokenizer, tok_kwargs) -> dict:
# flatten to 1-d list
inputs = tokenizer.apply_chat_template(
prompts,
tokenize=True,
add_generation_prompt=True,
enable_thinking=True,
rendered_prompts = [
tokenizer.apply_chat_template(
prompt,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True,
)
for prompt in prompts
]
return tokenizer(
rendered_prompts,
padding="max_length",
max_length=512, # TODO (yhyang201): set max length according to config
truncation=True,
return_tensors="pt",
return_dict=True,
)
return inputs

@staticmethod
def _ceil_to_multiple(x: int, m: int) -> int:
Expand All @@ -83,7 +87,7 @@ def _ceil_to_multiple(x: int, m: int) -> int:
return int(math.ceil(x / m) * m)

def _build_zimage_sp_plan(self, batch) -> dict:
"""Build a minimal SP plan on batch for zimage (spatial sharding + cap sharding)."""
"""Build a minimal SP plan on batch for zimage spatial sharding."""
sp_size = get_sp_world_size()
rank = get_sp_parallel_rank()

Expand Down Expand Up @@ -112,16 +116,6 @@ def _build_zimage_sp_plan(self, batch) -> dict:
H_tok_local = H_tok_pad // sp_size
h0_tok = rank * H_tok_local

# Cap/text sharding: avoid duplicating cap tokens across ranks.
cap_len = (
int(batch.prompt_embeds[0].size(0))
if getattr(batch, "prompt_embeds", None)
else 0
)
cap_total = self._ceil_to_multiple(cap_len, self.SEQ_LEN_MULTIPLE * sp_size)
cap_local = cap_total // sp_size
cap_start = rank * cap_local

plan = {
"sp_size": sp_size,
"rank": rank,
Expand All @@ -135,9 +129,6 @@ def _build_zimage_sp_plan(self, batch) -> dict:
"H_tok_pad": H_tok_pad,
"H_tok_local": H_tok_local,
"h0_tok": h0_tok,
"cap_total": cap_total,
"cap_local": cap_local,
"cap_start": cap_start,
}
batch._zimage_sp_plan = plan
return plan
Expand All @@ -149,25 +140,13 @@ def _get_zimage_sp_plan(self, batch) -> dict:
plan = self._build_zimage_sp_plan(batch)
return plan

def _shard_cap(self, cap: torch.Tensor, plan: dict) -> torch.Tensor:
"""cap: [L, D] -> [cap_local, D], padded by repeating last token."""
if plan["sp_size"] <= 1:
return cap
# print(f"cap shape: {cap.shape}") # [L, 2560] for zimage-turbo
L = cap.size(0)
cap_total = plan["cap_total"]
if cap_total > L:
cap = torch.cat([cap, cap[-1:].repeat(cap_total - L, 1)], dim=0)
start = plan["cap_start"]
local = plan["cap_local"]
return cap[start : start + local]

def get_pos_prompt_embeds(self, batch):
# Keep ZImage model signature: encoder_hidden_states is List[Tensor]
if get_sp_world_size() <= 1:
return batch.prompt_embeds
plan = self._get_zimage_sp_plan(batch)
return [self._shard_cap(batch.prompt_embeds[0], plan)]
return batch.prompt_embeds

def get_latent_dtype(self, prompt_dtype: torch.dtype) -> torch.dtype:
# Match the official diffusers Z-Image pipeline, which samples latents in fp32
# and keeps scheduler state in fp32.
return torch.float32

def shard_latents_for_sp(self, batch, latents):
sp_size = get_sp_world_size()
Expand Down Expand Up @@ -203,6 +182,19 @@ def gather_latents_for_sp(self, latents):
return latents
return sequence_model_parallel_all_gather(latents, dim=3)

def gather_noise_pred_for_sp(self, batch, noise_pred):
# Z-Image shards 5D latents on the effective-H axis, but ComfyUI noise_pred is 4D [B, C, H_local, W].
noise_pred = self.gather_latents_for_sp(noise_pred)
if noise_pred.dim() == 4:
# reconstruct the full spatial tensor
noise_pred = sequence_model_parallel_all_gather(
noise_pred.contiguous(), dim=2
)
# restore the original H/W orientation
if getattr(batch, "_zimage_sp_swap_hw", False):
noise_pred = noise_pred.transpose(2, 3).contiguous()
return noise_pred

def post_denoising_loop(self, latents, batch):
# Restore swapped H/W and crop padded spatial dims before final reshape.
if latents.dim() == 5 and getattr(batch, "_zimage_sp_swap_hw", False):
Expand Down Expand Up @@ -233,24 +225,27 @@ def create_coordinate_grid(size, start=None, device=None):

sp_size = get_sp_world_size()
if sp_size > 1:
# SP path: build local-only freqs_cis matching local cap/x.
# SP path: keep caption replicated on every rank and build local-only
# image freqs_cis matching the spatial shard.
plan = self._get_zimage_sp_plan(batch)
cap_ori_len = prompt_embeds.size(0)
cap_padding_len = (-cap_ori_len) % self.SEQ_LEN_MULTIPLE

# cap (local)
# caption (replicated prefix)
cap_pos_ids = create_coordinate_grid(
size=(plan["cap_local"], 1, 1),
start=(1 + plan["cap_start"], 0, 0),
size=(cap_ori_len + cap_padding_len, 1, 1),
start=(1, 0, 0),
device=device,
).flatten(0, 2)
cap_freqs_cis = rotary_emb(cap_pos_ids)

# image (local, effective H-shard). Use cap_total for a stable offset across ranks/passes.
# image (local, effective H-shard), offset after the full caption.
F_tokens = 1
H_tokens_local = plan["H_tok_local"]
W_tokens = plan["W_tok"]
img_pos_ids = create_coordinate_grid(
size=(F_tokens, H_tokens_local, W_tokens),
start=(plan["cap_total"] + 1, plan["h0_tok"], 0),
start=(cap_ori_len + cap_padding_len + 1, plan["h0_tok"], 0),
device=device,
).flatten(0, 2)
img_pad_len = (-img_pos_ids.shape[0]) % self.SEQ_LEN_MULTIPLE
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ def add_argument(*name_or_flags, **kwargs):
add_argument(
"--prompt-path",
type=str,
help="Path to a text file containing the prompt",
help="Path to a text file containing prompts (one per line)",
)
add_argument(
"--output-file-name",
Expand Down Expand Up @@ -744,6 +744,12 @@ def add_argument(*name_or_flags, **kwargs):
dest="guidance_scale_2",
help="Secondary guidance scale for dual-guidance models (e.g., Wan low-noise expert)",
)
add_argument(
"--true-cfg-scale",
type=float,
dest="true_cfg_scale",
help="True CFG scale for models that distinguish distilled guidance from standard CFG (e.g., Qwen-Image)",
)
add_argument(
"--guidance-rescale",
type=float,
Expand Down
Loading
Loading