Skip to content
Open
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
126 changes: 22 additions & 104 deletions src/maxdiffusion/models/attention_flax.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
from ..kernels import custom_svg_attention_dispatch
from ..kernels import custom_svg_static_range_attention
from . import quantizations
from . import svg_attention
from .modeling_flax_utils import get_activation

LOG2E = math.log2(math.e)
Expand Down Expand Up @@ -2047,7 +2048,7 @@ def _apply_attention(


def _head_local_svg_attention(query, key, value, context):
from .wan.transformers import svg_attention, svg_head_local
from .wan.transformers import svg_head_local

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Now that svg_attention.py has been moved out of models/wan/transformers/ into models/svg_attention.py so LTX-2 does not depend on the wan package, _head_local_svg_attention still has an in-line import from .wan.transformers import svg_head_local (which is a 56-line model-agnostic helper containing only inference_only and exchange_local). Consider moving svg_head_local.py alongside models/svg_attention.py (or merging it into svg_attention.py) and importing it at module top-level.


cfg = context["spatiotemporal_config"]
grid = context["spatiotemporal_shape"]
Expand Down Expand Up @@ -2585,49 +2586,12 @@ def __init__(
"use_experimental_scheduler": False,
"ulysses_shards": -1,
"ulysses_attention_chunks": 1,
"use_svg_attention": False,
"svg_implementation": "official_svg",
"svg_spatial_density": 0.25,
"svg_sample_max_row": 10000,
"svg_profile_query_count": 64,
"svg_profile_seed": 0,
"svg_dense_layer_fraction": 0.0,
"svg_dense_timestep_fraction": 0.0,
"svg_active_start_step": -1,
"svg_active_end_step": -1,
"svg_active_start_layer": -1,
"svg_active_end_layer": -1,
"svg_num_train_timesteps": 1000,
"svg_num_layers": 40,
"svg_include_first_frame": True,
"svg_global_stride": 0,
"svg_global_offset": 0,
"svg_high_noise_density": -1.0,
"svg_low_noise_density": -1.0,
"svg_flash_block_sizes": None,
**(attention_config or {}),
}

self.use_svg_attention = attention_config["use_svg_attention"]
self.svg_implementation = attention_config["svg_implementation"]
self.svg_spatial_density = attention_config["svg_spatial_density"]
self.svg_sample_max_row = attention_config["svg_sample_max_row"]
self.svg_profile_query_count = attention_config["svg_profile_query_count"]
self.svg_profile_seed = attention_config["svg_profile_seed"]
self.svg_dense_layer_fraction = attention_config["svg_dense_layer_fraction"]
self.svg_dense_timestep_fraction = attention_config["svg_dense_timestep_fraction"]
self.svg_active_start_step = attention_config["svg_active_start_step"]
self.svg_active_end_step = attention_config["svg_active_end_step"]
self.svg_active_start_layer = attention_config["svg_active_start_layer"]
self.svg_active_end_layer = attention_config["svg_active_end_layer"]
self.svg_num_train_timesteps = attention_config["svg_num_train_timesteps"]
self.svg_num_layers = attention_config["svg_num_layers"]
self.svg_include_first_frame = attention_config["svg_include_first_frame"]
self.svg_global_stride = attention_config["svg_global_stride"]
self.svg_global_offset = attention_config["svg_global_offset"]
self.svg_high_noise_density = attention_config["svg_high_noise_density"]
self.svg_low_noise_density = attention_config["svg_low_noise_density"]
self.svg_flash_block_sizes = attention_config["svg_flash_block_sizes"]
svg_config = svg_attention.init_svg_config(attention_config, default_num_layers=40)
for name, value in svg_config.items():
setattr(self, name, value)
self.is_self_attention = is_self_attention

if attention_kernel in {"flash", "cudnn_flash_te"} and mesh is None:
Expand Down Expand Up @@ -2934,73 +2898,27 @@ def __call__(
key_proj = checkpoint_name(key_proj, "key_proj")
value_proj = checkpoint_name(value_proj, "value_proj")

if self.use_svg_attention and is_self_attention and spatiotemporal_shape is not None:
from .wan.transformers import svg_attention

is_active = svg_attention.is_svg_active(
step_index=svg_step_index,
layer_index=svg_layer_index,
timestep=svg_timestep,
start_step=self.svg_active_start_step,
end_step=self.svg_active_end_step,
start_layer=self.svg_active_start_layer,
end_layer=self.svg_active_end_layer,
dense_layer_fraction=self.svg_dense_layer_fraction,
dense_timestep_fraction=self.svg_dense_timestep_fraction,
num_train_timesteps=self.svg_num_train_timesteps,
num_layers=self.svg_num_layers,
def run_attention(**svg_kwargs):
return self.attention_op.apply_attention(
query_proj,
key_proj,
value_proj,
attention_mask=encoder_attention_mask,
**svg_kwargs,
)

def run_dense(_):
return self.attention_op.apply_attention(
query_proj,
key_proj,
value_proj,
attention_mask=encoder_attention_mask,
)

def run_sparse_svg(_):
execution_band_width = svg_attention.svg_execution_band_width(
spatiotemporal_shape,
self.svg_spatial_density,
)
sparse_config = {
"use_svg_attention": True,
"mask_type": "svg_spatial",
"band_width": execution_band_width,
"include_first_frame": self.svg_include_first_frame,
"global_stride": self.svg_global_stride,
"global_offset": self.svg_global_offset,
"profile_query_count": self.svg_profile_query_count,
"profile_seed": self.svg_profile_seed,
"sample_max_row": self.svg_sample_max_row,
"custom_flash_block_sizes": self.svg_flash_block_sizes,
"svg_step_index": svg_step_index,
"svg_layer_index": svg_layer_index,
"svg_timestep": svg_timestep,
}
return self.attention_op.apply_attention(
query_proj,
key_proj,
value_proj,
attention_mask=encoder_attention_mask,
spatiotemporal_shape=spatiotemporal_shape,
sparse_config_override=sparse_config,
)

with jax.named_scope("apply_attention"):
if isinstance(is_active, bool):
attn_output = run_sparse_svg(None) if is_active else run_dense(None)
else:
attn_output = jax.lax.cond(is_active, run_sparse_svg, run_dense, operand=None)
if self.use_svg_attention and is_self_attention:
attn_output = svg_attention.apply_svg_or_dense(
self,
run_attention,
spatiotemporal_shape,
svg_layer_index=svg_layer_index,
svg_step_index=svg_step_index,
svg_timestep=svg_timestep,
)
else:
with jax.named_scope("apply_attention"):
attn_output = self.attention_op.apply_attention(
query_proj,
key_proj,
value_proj,
attention_mask=encoder_attention_mask,
)
attn_output = run_attention()

else:
# NEW PATH for I2V CROSS-ATTENTION
Expand Down
40 changes: 38 additions & 2 deletions src/maxdiffusion/models/ltx2/attention_ltx2.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import jax.numpy as jnp
from ... import common_types
from ..attention_flax import NNXAttentionOp
from .. import svg_attention
from .logical_sharding_ltx2 import get_sharding_specs, LTX2DiTShardingSpecs

Array = common_types.Array
Expand Down Expand Up @@ -352,7 +353,14 @@ def __init__(
use_base2_exp: bool = False,
use_experimental_scheduler: bool = False,
enable_jax_named_scopes: bool = False,
attention_config: Optional[dict] = None,
):
svg_config = svg_attention.init_svg_config(attention_config, default_num_layers=48)
for name, value in svg_config.items():
setattr(self, name, value)
self.is_self_attention = context_dim is None
self.use_svg_attention = bool(self.use_svg_attention) and self.is_self_attention

self.heads = heads
self.rope_type = rope_type
self.dim_head = dim_head
Expand Down Expand Up @@ -542,10 +550,18 @@ def __call__(
k_rotary_emb: Optional[Tuple[Array, Array]] = None,
perturbation_mask: Optional[Array] = None,
cached_kv: Optional[Tuple[Array, Array]] = None,
spatiotemporal_shape: Optional[Tuple[int, int, int]] = None,
svg_layer_index: Optional[int | jax.Array] = None,
svg_timestep: Optional[int | float | jax.Array] = None,
svg_step_index: Optional[int | jax.Array] = None,
) -> Array:
# Determine context (Self or Cross)
is_self_attention = encoder_hidden_states is None
context = encoder_hidden_states if encoder_hidden_states is not None else hidden_states

if self.use_svg_attention and is_self_attention and spatiotemporal_shape is None:
raise ValueError("SVG attention requires spatiotemporal_shape.")

# 1. Project and Norm
with self.named_scope("QKV Projection"):
query = self.to_q(hidden_states)
Expand Down Expand Up @@ -586,8 +602,28 @@ def __call__(

with self.named_scope("Attention and Output Project"):
# 4. Attention
# NNXAttentionOp expects flattened input [B, S, InnerDim] for flash kernel
attn_output = self.attention_op.apply_attention(query=query, key=key, value=value, attention_mask=attention_mask)
def run_attention(**svg_kwargs):
return self.attention_op.apply_attention(
query=query,
key=key,
value=value,
attention_mask=attention_mask,
**svg_kwargs,
)

if self.use_svg_attention and is_self_attention:
attn_output = svg_attention.apply_svg_or_dense(
self,
run_attention,
spatiotemporal_shape,
svg_layer_index=svg_layer_index,
svg_step_index=svg_step_index,
svg_timestep=svg_timestep,
named_scope=self.named_scope,
)
else:
with self.named_scope("apply_attention"):
attn_output = run_attention()

if perturbation_mask is not None:
# value is [B, S, InnerDim]
Expand Down
Loading
Loading