[Model] Add TP and CFG parallelism to SANA-Video 2B (#5861)
Signed-off-by: cr-gao <gaochenrui@sjtu.edu.cn>
This commit is contained in:
18 files changed
+1621
-116
No files matched your search
@@ -230,6 +230,11 @@ class DiffusersAdapterPipeline(nn.Module, DiffusionPipelineProfilerMixin):
|
||||
def _raise_unsupported_features(self) -> None:
|
||||
"""Raise an error for incompatible feature switches."""
|
||||
pc = self.od_config.parallel_config
|
||||
if pc.tensor_parallel_size > 1:
|
||||
raise NotImplementedError(
|
||||
"Tensor parallel is not supported with the diffusers backend. "
|
||||
"It requires model-specific layer sharding; use a native pipeline for TP."
|
||||
)
|
||||
if pc.cfg_parallel_size > 1:
|
||||
raise NotImplementedError(
|
||||
"CFG parallel is not supported with the diffusers backend. "
|
||||
|
||||
@@ -37,6 +37,11 @@ from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_ltx2 import (
|
||||
DistributedAutoencoderKLLTX2Video,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import DistributedAutoencoderKLWan
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin, _wrap
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
get_classifier_free_guidance_world_size,
|
||||
model_parallel_is_initialized,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch, prefetch_subfolders
|
||||
@@ -49,7 +54,7 @@ from vllm_omni.diffusion.request import resolve_video_num_frames
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
|
||||
from .pipeline_output import SanaVideoPipelineOutput
|
||||
from .transformer_sana_video import SanaVideoTransformer3DModel
|
||||
from .transformer_sana_video import SanaVideoTransformer3DModel, validate_sana_video_parallel_config
|
||||
|
||||
|
||||
def _resolve_vae_class_and_dtype(
|
||||
@@ -269,6 +274,7 @@ def retrieve_timesteps(
|
||||
|
||||
class SanaVideoPipeline(
|
||||
nn.Module,
|
||||
CFGParallelMixin,
|
||||
ProgressBarMixin,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
SupportsComponentDiscovery,
|
||||
@@ -308,6 +314,9 @@ class SanaVideoPipeline(
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
if od_config is not None:
|
||||
validate_sana_video_parallel_config(od_config.parallel_config)
|
||||
|
||||
self.od_config = od_config
|
||||
self.device = get_local_device()
|
||||
self.weights_sources: list[DiffusersPipelineLoader.ComponentSource] = []
|
||||
@@ -724,6 +733,105 @@ class SanaVideoPipeline(
|
||||
def interrupt(self):
|
||||
return self._interrupt
|
||||
|
||||
def predict_noise(self, *args, **kwargs) -> torch.Tensor:
|
||||
# return_dict=False: the dataclass output is not subscriptable.
|
||||
return self.transformer(*args, **kwargs, return_dict=False)[0]
|
||||
|
||||
def combine_cfg_noise(
|
||||
self,
|
||||
positive_noise_pred,
|
||||
negative_noise_pred,
|
||||
true_cfg_scale,
|
||||
cfg_normalize=False,
|
||||
kwargs=None,
|
||||
):
|
||||
# fp32 combine so the bf16 all-gather path matches CFG1 bit-for-bit.
|
||||
return super().combine_cfg_noise(
|
||||
tuple(p.float() for p in _wrap(positive_noise_pred)),
|
||||
tuple(n.float() for n in _wrap(negative_noise_pred)),
|
||||
true_cfg_scale,
|
||||
cfg_normalize,
|
||||
kwargs,
|
||||
)
|
||||
|
||||
def diffuse(
|
||||
self,
|
||||
latents: torch.Tensor,
|
||||
timesteps: torch.Tensor,
|
||||
prompt_embeds: torch.Tensor,
|
||||
prompt_attention_mask: torch.Tensor,
|
||||
negative_prompt_embeds: torch.Tensor | None,
|
||||
negative_prompt_attention_mask: torch.Tensor | None,
|
||||
guidance_scale: float,
|
||||
extra_step_kwargs: dict,
|
||||
dtype: torch.dtype,
|
||||
output_slice: int | None,
|
||||
) -> torch.Tensor:
|
||||
do_true_cfg = self.do_classifier_free_guidance
|
||||
# Single-process runs never initialize the parallel groups.
|
||||
cfg_parallel = model_parallel_is_initialized() and get_classifier_free_guidance_world_size() > 1
|
||||
if cfg_parallel:
|
||||
self.check_cfg_parallel_validity(guidance_scale, negative_prompt_embeds is not None)
|
||||
|
||||
if do_true_cfg and not cfg_parallel:
|
||||
# Concatenate neg/pos for a single batch-2 forward.
|
||||
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
||||
prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
|
||||
|
||||
with self.progress_bar(total=len(timesteps)) as progress_bar:
|
||||
for t in timesteps:
|
||||
if self.interrupt:
|
||||
continue
|
||||
|
||||
if cfg_parallel:
|
||||
timestep = t.expand(latents.shape[0])
|
||||
latent_model_input = latents.to(dtype)
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"encoder_hidden_states": prompt_embeds.to(dtype),
|
||||
"encoder_attention_mask": prompt_attention_mask,
|
||||
"timestep": timestep,
|
||||
}
|
||||
negative_kwargs = (
|
||||
{
|
||||
"hidden_states": latent_model_input,
|
||||
"encoder_hidden_states": negative_prompt_embeds.to(dtype),
|
||||
"encoder_attention_mask": negative_prompt_attention_mask,
|
||||
"timestep": timestep,
|
||||
}
|
||||
if do_true_cfg
|
||||
else None
|
||||
)
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
output_slice=output_slice,
|
||||
).float()
|
||||
else:
|
||||
latent_model_input = torch.cat([latents] * 2) if do_true_cfg else latents
|
||||
timestep = t.expand(latent_model_input.shape[0])
|
||||
noise_pred = self.transformer(
|
||||
latent_model_input.to(dtype),
|
||||
encoder_hidden_states=prompt_embeds.to(dtype),
|
||||
encoder_attention_mask=prompt_attention_mask,
|
||||
timestep=timestep,
|
||||
return_dict=False,
|
||||
)[0]
|
||||
noise_pred = noise_pred.float()
|
||||
if do_true_cfg:
|
||||
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
||||
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
||||
if output_slice is not None:
|
||||
noise_pred = noise_pred[:, :output_slice]
|
||||
|
||||
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
||||
progress_bar.update()
|
||||
|
||||
return latents
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
transformer_weights = (
|
||||
(name.removeprefix("transformer."), tensor) for name, tensor in weights if name.startswith("transformer.")
|
||||
@@ -947,10 +1055,6 @@ class SanaVideoPipeline(
|
||||
max_sequence_length=max_sequence_length,
|
||||
complex_human_instruction=complex_human_instruction,
|
||||
)
|
||||
if self.do_classifier_free_guidance:
|
||||
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
||||
prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
|
||||
|
||||
# 4. Prepare timesteps
|
||||
timesteps, num_inference_steps = retrieve_timesteps(
|
||||
self.scheduler, num_inference_steps, device, timesteps, sigmas
|
||||
@@ -974,44 +1078,21 @@ class SanaVideoPipeline(
|
||||
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
||||
|
||||
# 7. Denoising loop
|
||||
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
||||
self._num_timesteps = len(timesteps)
|
||||
|
||||
transformer_dtype = self.transformer.dtype
|
||||
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
||||
for i, t in enumerate(timesteps):
|
||||
if self.interrupt:
|
||||
continue
|
||||
|
||||
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
||||
|
||||
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
||||
timestep = t.expand(latent_model_input.shape[0])
|
||||
|
||||
# predict noise model_output
|
||||
noise_pred = self.transformer(
|
||||
latent_model_input.to(dtype=transformer_dtype),
|
||||
encoder_hidden_states=prompt_embeds.to(dtype=transformer_dtype),
|
||||
encoder_attention_mask=prompt_attention_mask,
|
||||
timestep=timestep,
|
||||
return_dict=False,
|
||||
)[0]
|
||||
noise_pred = noise_pred.float()
|
||||
|
||||
# perform guidance
|
||||
if self.do_classifier_free_guidance:
|
||||
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
||||
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
||||
|
||||
# learned sigma
|
||||
if self.transformer.config.out_channels // 2 == latent_channels:
|
||||
noise_pred = noise_pred.chunk(2, dim=1)[0]
|
||||
|
||||
# compute previous image: x_t -> x_t-1
|
||||
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
||||
|
||||
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
||||
progress_bar.update()
|
||||
# learned sigma: transformer predicts 2x latent channels; keep the first half.
|
||||
output_slice = latent_channels if self.transformer.config.out_channels // 2 == latent_channels else None
|
||||
latents = self.diffuse(
|
||||
latents=latents,
|
||||
timesteps=timesteps,
|
||||
prompt_embeds=prompt_embeds,
|
||||
prompt_attention_mask=prompt_attention_mask,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
negative_prompt_attention_mask=negative_prompt_attention_mask,
|
||||
guidance_scale=guidance_scale,
|
||||
extra_step_kwargs=extra_step_kwargs,
|
||||
dtype=self.transformer.dtype,
|
||||
output_slice=output_slice,
|
||||
)
|
||||
|
||||
if output_type == "latent":
|
||||
video = latents
|
||||
|
||||
@@ -16,6 +16,10 @@ from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_ltx2 import (
|
||||
DistributedAutoencoderKLLTX2Video,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import DistributedAutoencoderKLWan
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
get_classifier_free_guidance_world_size,
|
||||
model_parallel_is_initialized,
|
||||
)
|
||||
from vllm_omni.diffusion.models.interface import SupportImageInput
|
||||
from vllm_omni.diffusion.models.sana_video.pipeline_sana_video import (
|
||||
ASPECT_RATIO_480_BIN,
|
||||
@@ -225,6 +229,91 @@ class SanaImageToVideoPipeline(SanaVideoPipeline, SupportImageInput):
|
||||
)
|
||||
return DiffusionOutput(output=video)
|
||||
|
||||
def diffuse(
|
||||
self,
|
||||
latents: torch.Tensor,
|
||||
timesteps: torch.Tensor,
|
||||
prompt_embeds: torch.Tensor,
|
||||
prompt_attention_mask: torch.Tensor,
|
||||
negative_prompt_embeds: torch.Tensor | None,
|
||||
negative_prompt_attention_mask: torch.Tensor | None,
|
||||
guidance_scale: float,
|
||||
conditioning_mask: torch.Tensor,
|
||||
extra_step_kwargs: dict,
|
||||
dtype: torch.dtype,
|
||||
output_slice: int | None,
|
||||
) -> torch.Tensor:
|
||||
do_true_cfg = self.do_classifier_free_guidance
|
||||
# Single-process runs never initialize the parallel groups.
|
||||
cfg_parallel = model_parallel_is_initialized() and get_classifier_free_guidance_world_size() > 1
|
||||
if cfg_parallel:
|
||||
self.check_cfg_parallel_validity(guidance_scale, negative_prompt_embeds is not None)
|
||||
|
||||
if do_true_cfg and not cfg_parallel:
|
||||
# Concatenate neg/pos and the mask for a single batch-2 forward.
|
||||
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
||||
prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask])
|
||||
conditioning_mask = torch.cat([conditioning_mask, conditioning_mask])
|
||||
|
||||
with self.progress_bar(total=len(timesteps)) as progress_bar:
|
||||
for timestep_value in timesteps:
|
||||
# Conditioning frames keep timestep 0 so they are not denoised.
|
||||
timestep = timestep_value.expand(conditioning_mask.shape) * (1 - conditioning_mask)
|
||||
|
||||
if cfg_parallel:
|
||||
latent_model_input = latents.to(dtype)
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"encoder_hidden_states": prompt_embeds.to(dtype),
|
||||
"encoder_attention_mask": prompt_attention_mask,
|
||||
"timestep": timestep,
|
||||
}
|
||||
negative_kwargs = (
|
||||
{
|
||||
"hidden_states": latent_model_input,
|
||||
"encoder_hidden_states": negative_prompt_embeds.to(dtype),
|
||||
"encoder_attention_mask": negative_prompt_attention_mask,
|
||||
"timestep": timestep,
|
||||
}
|
||||
if do_true_cfg
|
||||
else None
|
||||
)
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
output_slice=output_slice,
|
||||
).float()
|
||||
else:
|
||||
latent_input = torch.cat([latents, latents]) if do_true_cfg else latents
|
||||
noise_pred = self.transformer(
|
||||
latent_input.to(dtype),
|
||||
encoder_hidden_states=prompt_embeds.to(dtype),
|
||||
encoder_attention_mask=prompt_attention_mask,
|
||||
timestep=timestep,
|
||||
return_dict=False,
|
||||
)[0].float()
|
||||
if do_true_cfg:
|
||||
uncond, cond = noise_pred.chunk(2)
|
||||
noise_pred = uncond + guidance_scale * (cond - uncond)
|
||||
if output_slice is not None:
|
||||
noise_pred = noise_pred[:, :output_slice]
|
||||
|
||||
# Only the non-conditioning frames are denoised; the first frame is carried through.
|
||||
denoised = self.scheduler.step(
|
||||
noise_pred[:, :, 1:],
|
||||
timestep_value,
|
||||
latents[:, :, 1:],
|
||||
**extra_step_kwargs,
|
||||
return_dict=False,
|
||||
)[0]
|
||||
latents = torch.cat([latents[:, :, :1], denoised], dim=2)
|
||||
progress_bar.update()
|
||||
|
||||
return latents
|
||||
|
||||
@torch.no_grad()
|
||||
def _generate_i2v(
|
||||
self,
|
||||
@@ -282,10 +371,6 @@ class SanaImageToVideoPipeline(SanaVideoPipeline, SupportImageInput):
|
||||
max_sequence_length=max_sequence_length,
|
||||
complex_human_instruction=complex_human_instruction,
|
||||
)
|
||||
if self.do_classifier_free_guidance:
|
||||
prompt_embeds = torch.cat([negative_embeds, prompt_embeds])
|
||||
prompt_mask = torch.cat([negative_mask, prompt_mask])
|
||||
|
||||
timesteps, num_inference_steps = retrieve_timesteps(
|
||||
self.scheduler,
|
||||
num_inference_steps=num_inference_steps,
|
||||
@@ -319,39 +404,24 @@ class SanaImageToVideoPipeline(SanaVideoPipeline, SupportImageInput):
|
||||
latents.shape[4] // patch_w,
|
||||
)
|
||||
conditioning_mask[:, :, 0] = 1
|
||||
if self.do_classifier_free_guidance:
|
||||
conditioning_mask = torch.cat([conditioning_mask, conditioning_mask])
|
||||
|
||||
self._num_timesteps = len(timesteps)
|
||||
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
||||
transformer_dtype = self.transformer.dtype
|
||||
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
||||
for index, timestep_value in enumerate(timesteps):
|
||||
latent_input = torch.cat([latents, latents]) if self.do_classifier_free_guidance else latents
|
||||
timestep = timestep_value.expand(conditioning_mask.shape) * (1 - conditioning_mask)
|
||||
noise_pred = self.transformer(
|
||||
latent_input.to(transformer_dtype),
|
||||
encoder_hidden_states=prompt_embeds.to(transformer_dtype),
|
||||
encoder_attention_mask=prompt_mask,
|
||||
timestep=timestep,
|
||||
return_dict=False,
|
||||
)[0].float()
|
||||
if self.do_classifier_free_guidance:
|
||||
uncond, cond = noise_pred.chunk(2)
|
||||
noise_pred = uncond + guidance_scale * (cond - uncond)
|
||||
if self.transformer.config.out_channels // 2 == latent_channels:
|
||||
noise_pred = noise_pred.chunk(2, dim=1)[0]
|
||||
|
||||
denoised = self.scheduler.step(
|
||||
noise_pred[:, :, 1:],
|
||||
timestep_value,
|
||||
latents[:, :, 1:],
|
||||
**extra_step_kwargs,
|
||||
return_dict=False,
|
||||
)[0]
|
||||
latents = torch.cat([latents[:, :, :1], denoised], dim=2)
|
||||
if index == len(timesteps) - 1 or (index + 1) % self.scheduler.order == 0:
|
||||
progress_bar.update()
|
||||
# learned sigma: transformer predicts 2x latent channels; keep the first half.
|
||||
output_slice = latent_channels if self.transformer.config.out_channels // 2 == latent_channels else None
|
||||
latents = self.diffuse(
|
||||
latents=latents,
|
||||
timesteps=timesteps,
|
||||
prompt_embeds=prompt_embeds,
|
||||
prompt_attention_mask=prompt_mask,
|
||||
negative_prompt_embeds=negative_embeds,
|
||||
negative_prompt_attention_mask=negative_mask,
|
||||
guidance_scale=guidance_scale,
|
||||
conditioning_mask=conditioning_mask,
|
||||
extra_step_kwargs=extra_step_kwargs,
|
||||
dtype=self.transformer.dtype,
|
||||
output_slice=output_slice,
|
||||
)
|
||||
|
||||
if output_type == "latent":
|
||||
return latents
|
||||
|
||||
@@ -19,12 +19,48 @@ from dataclasses import dataclass, fields
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
tensor_model_parallel_all_reduce,
|
||||
)
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear, RowParallelLinear
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
from vllm.model_executor.utils import set_weight_attrs
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.layer import Attention as OmniAttention
|
||||
|
||||
|
||||
def validate_sana_video_parallel_config(parallel_config) -> None:
|
||||
"""Reject unsupported SANA-Video parallel topologies before weights load."""
|
||||
tp_size = parallel_config.tensor_parallel_size
|
||||
if tp_size not in (1, 2):
|
||||
raise NotImplementedError(
|
||||
f"SANA-Video supports tensor_parallel_size 1 or 2, got {tp_size}. Set --tensor-parallel-size to 1 or 2."
|
||||
)
|
||||
cfg_size = parallel_config.cfg_parallel_size
|
||||
if cfg_size not in (1, 2):
|
||||
raise NotImplementedError(
|
||||
f"SANA-Video supports cfg_parallel_size 1 or 2, got {cfg_size}. Set --cfg-parallel-size to 1 or 2."
|
||||
)
|
||||
sp_size = parallel_config.sequence_parallel_size
|
||||
if sp_size is not None and sp_size > 1:
|
||||
raise NotImplementedError(
|
||||
"Sequence parallel is not supported for SANA-Video: its linear attention and "
|
||||
"GLUMB temporal conv have no SANA-specific SP implementation. Use tensor and/or "
|
||||
"CFG parallel instead."
|
||||
)
|
||||
if parallel_config.pipeline_parallel_size > 1:
|
||||
raise NotImplementedError("SANA-Video does not support pipeline parallel. Set --pipeline-parallel-size to 1.")
|
||||
if parallel_config.use_hsdp:
|
||||
raise NotImplementedError("SANA-Video does not support HSDP. Remove --use-hsdp.")
|
||||
if parallel_config.text_encoder_tp_size > 1:
|
||||
raise NotImplementedError(
|
||||
"SANA-Video does not support text encoder tensor parallel. Set text_encoder_tp_size to 1."
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SanaVideoTransformerConfig:
|
||||
in_channels: int = 16
|
||||
@@ -109,6 +145,54 @@ class SanaRMSNorm(nn.Module):
|
||||
return hidden_states
|
||||
|
||||
|
||||
class SanaDistributedRMSNorm(nn.Module):
|
||||
"""RMSNorm that computes global RMS across tensor parallel ranks."""
|
||||
|
||||
def __init__(self, hidden_size: int, eps: float = 1e-6):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
set_weight_attrs(self.weight, {"weight_loader": self.weight_loader})
|
||||
|
||||
def weight_loader(self, param: torch.Tensor, loaded_weight: torch.Tensor) -> None:
|
||||
if param.shape == loaded_weight.shape:
|
||||
param.data.copy_(loaded_weight)
|
||||
return
|
||||
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
if loaded_weight.shape[0] % tp_size != 0:
|
||||
raise ValueError(
|
||||
f"Cannot shard RMSNorm weight of shape {tuple(loaded_weight.shape)} across tp_size={tp_size}."
|
||||
)
|
||||
|
||||
shard_size = loaded_weight.shape[0] // tp_size
|
||||
start_idx = get_tensor_model_parallel_rank() * shard_size
|
||||
shard = loaded_weight.narrow(0, start_idx, shard_size)
|
||||
if param.shape != shard.shape:
|
||||
raise ValueError(f"RMSNorm shard shape mismatch: param={tuple(param.shape)}, shard={tuple(shard.shape)}.")
|
||||
param.data.copy_(shard)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
x_float = x.float()
|
||||
sum_sq = x_float.pow(2).sum(dim=-1, keepdim=True)
|
||||
count = x.shape[-1]
|
||||
|
||||
if tp_size > 1:
|
||||
# Use vLLM's collective (custom all-reduce / symmetric-mem fast path
|
||||
# for small tensors) instead of raw torch.distributed.all_reduce, and
|
||||
# take the return value so the custom-AR path (which may return a new
|
||||
# buffer) is handled correctly. No .clone() needed.
|
||||
sum_sq = tensor_model_parallel_all_reduce(sum_sq)
|
||||
count = count * tp_size
|
||||
|
||||
hidden_states = x_float * torch.rsqrt(sum_sq / count + self.eps)
|
||||
# Only cast to the weight dtype for fp16/bf16 weights; keep fp32 otherwise.
|
||||
if self.weight.dtype in (torch.float16, torch.bfloat16):
|
||||
hidden_states = hidden_states.to(self.weight.dtype)
|
||||
return hidden_states * self.weight
|
||||
|
||||
|
||||
def _get_timestep_embedding(
|
||||
timesteps: torch.Tensor,
|
||||
embedding_dim: int,
|
||||
@@ -378,11 +462,22 @@ class GLUMBTempConv(nn.Module):
|
||||
hidden_channels = int(expand_ratio * in_channels)
|
||||
self.norm_type = norm_type
|
||||
self.residual_connection = residual_connection
|
||||
self.hidden_channels = hidden_channels
|
||||
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
local_hidden_channels = hidden_channels // tp_size
|
||||
|
||||
self.nonlinearity = nn.SiLU()
|
||||
self.conv_inverted = nn.Conv2d(in_channels, hidden_channels * 2, 1, 1, 0)
|
||||
self.conv_depth = nn.Conv2d(hidden_channels * 2, hidden_channels * 2, 3, 1, 1, groups=hidden_channels * 2)
|
||||
self.conv_point = nn.Conv2d(hidden_channels, out_channels, 1, 1, 0, bias=False)
|
||||
self.conv_inverted = nn.Conv2d(in_channels, 2 * local_hidden_channels, 1, 1, 0)
|
||||
self.conv_depth = nn.Conv2d(
|
||||
2 * local_hidden_channels, 2 * local_hidden_channels, 3, 1, 1, groups=2 * local_hidden_channels
|
||||
)
|
||||
self.conv_point = nn.Conv2d(local_hidden_channels, out_channels, 1, 1, 0, bias=False)
|
||||
# conv_inverted/conv_depth carry [value(h), gate(h)]; each rank must hold a
|
||||
# slice of both segments so the local chunk(2) still splits value from gate.
|
||||
for param in (self.conv_inverted.weight, self.conv_inverted.bias, self.conv_depth.weight, self.conv_depth.bias):
|
||||
set_weight_attrs(param, {"weight_loader": self._segment_weight_loader})
|
||||
set_weight_attrs(self.conv_point.weight, {"weight_loader": self._point_weight_loader})
|
||||
|
||||
self.norm = None
|
||||
if norm_type == "rms_norm":
|
||||
@@ -390,6 +485,19 @@ class GLUMBTempConv(nn.Module):
|
||||
|
||||
self.conv_temp = nn.Conv2d(out_channels, out_channels, kernel_size=(3, 1), stride=1, padding=(1, 0), bias=False)
|
||||
|
||||
def _segment_weight_loader(self, param: torch.Tensor, loaded_weight: torch.Tensor) -> None:
|
||||
h = self.hidden_channels
|
||||
local = h // get_tensor_model_parallel_world_size()
|
||||
start = get_tensor_model_parallel_rank() * local
|
||||
value = loaded_weight.narrow(0, start, local)
|
||||
gate = loaded_weight.narrow(0, h + start, local)
|
||||
param.data.copy_(torch.cat([value, gate], dim=0))
|
||||
|
||||
def _point_weight_loader(self, param: torch.Tensor, loaded_weight: torch.Tensor) -> None:
|
||||
local = self.hidden_channels // get_tensor_model_parallel_world_size()
|
||||
start = get_tensor_model_parallel_rank() * local
|
||||
param.data.copy_(loaded_weight.narrow(1, start, local))
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
if self.residual_connection:
|
||||
residual = hidden_states
|
||||
@@ -404,6 +512,8 @@ class GLUMBTempConv(nn.Module):
|
||||
hidden_states = hidden_states * self.nonlinearity(gate)
|
||||
|
||||
hidden_states = self.conv_point(hidden_states)
|
||||
if get_tensor_model_parallel_world_size() > 1:
|
||||
hidden_states = tensor_model_parallel_all_reduce(hidden_states)
|
||||
|
||||
# Temporal aggregation
|
||||
hidden_states_temporal = hidden_states.view(batch_size, num_frames, num_channels, height * width).permute(
|
||||
@@ -440,13 +550,20 @@ class SanaLinearAttention(nn.Module):
|
||||
) -> None:
|
||||
super().__init__()
|
||||
inner_dim = num_heads * head_dim
|
||||
self.heads = num_heads
|
||||
self.to_q = nn.Linear(dim, inner_dim, bias=bias)
|
||||
self.to_k = nn.Linear(dim, inner_dim, bias=bias)
|
||||
self.to_v = nn.Linear(dim, inner_dim, bias=bias)
|
||||
self.norm_q = SanaRMSNorm(inner_dim, eps=1e-5, elementwise_affine=True) if qk_norm is not None else None
|
||||
self.norm_k = SanaRMSNorm(inner_dim, eps=1e-5, elementwise_affine=True) if qk_norm is not None else None
|
||||
self.to_out = nn.ModuleList([nn.Linear(inner_dim, dim, bias=True), nn.Dropout(dropout)])
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
self.heads = num_heads // tp_size
|
||||
local_inner_dim = inner_dim // tp_size
|
||||
self.to_q = ColumnParallelLinear(dim, inner_dim, bias=bias, gather_output=False, return_bias=False)
|
||||
self.to_k = ColumnParallelLinear(dim, inner_dim, bias=bias, gather_output=False, return_bias=False)
|
||||
self.to_v = ColumnParallelLinear(dim, inner_dim, bias=bias, gather_output=False, return_bias=False)
|
||||
self.norm_q = SanaDistributedRMSNorm(local_inner_dim, eps=1e-5) if qk_norm is not None else None
|
||||
self.norm_k = SanaDistributedRMSNorm(local_inner_dim, eps=1e-5) if qk_norm is not None else None
|
||||
self.to_out = nn.ModuleList(
|
||||
[
|
||||
RowParallelLinear(inner_dim, dim, bias=True, input_is_parallel=True, return_bias=False),
|
||||
nn.Dropout(dropout),
|
||||
]
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -632,18 +749,29 @@ class SanaCrossAttention(nn.Module):
|
||||
) -> None:
|
||||
super().__init__()
|
||||
inner_dim = num_heads * head_dim
|
||||
self.heads = num_heads
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
self.heads = num_heads // tp_size
|
||||
self.head_dim = head_dim
|
||||
self.to_q = nn.Linear(dim, inner_dim, bias=bias)
|
||||
self.to_k = nn.Linear(cross_attention_dim, inner_dim, bias=bias)
|
||||
self.to_v = nn.Linear(cross_attention_dim, inner_dim, bias=bias)
|
||||
self.norm_q = SanaRMSNorm(inner_dim, eps=1e-5, elementwise_affine=True) if qk_norm is not None else None
|
||||
self.norm_k = SanaRMSNorm(inner_dim, eps=1e-5, elementwise_affine=True) if qk_norm is not None else None
|
||||
self.to_out = nn.ModuleList([nn.Linear(inner_dim, dim, bias=out_bias), nn.Dropout(dropout)])
|
||||
local_inner_dim = inner_dim // tp_size
|
||||
self.to_q = ColumnParallelLinear(dim, inner_dim, bias=bias, gather_output=False, return_bias=False)
|
||||
self.to_k = ColumnParallelLinear(
|
||||
cross_attention_dim, inner_dim, bias=bias, gather_output=False, return_bias=False
|
||||
)
|
||||
self.to_v = ColumnParallelLinear(
|
||||
cross_attention_dim, inner_dim, bias=bias, gather_output=False, return_bias=False
|
||||
)
|
||||
self.norm_q = SanaDistributedRMSNorm(local_inner_dim, eps=1e-5) if qk_norm is not None else None
|
||||
self.norm_k = SanaDistributedRMSNorm(local_inner_dim, eps=1e-5) if qk_norm is not None else None
|
||||
self.to_out = nn.ModuleList(
|
||||
[
|
||||
RowParallelLinear(inner_dim, dim, bias=out_bias, input_is_parallel=True, return_bias=False),
|
||||
nn.Dropout(dropout),
|
||||
]
|
||||
)
|
||||
self.attn = OmniAttention(
|
||||
num_heads=num_heads,
|
||||
num_heads=self.heads,
|
||||
head_size=head_dim,
|
||||
num_kv_heads=num_heads,
|
||||
num_kv_heads=self.heads,
|
||||
softmax_scale=1.0 / (head_dim**0.5),
|
||||
causal=False,
|
||||
role="cross",
|
||||
|
||||
Reference in new issue
Block a user