Skip to content

Commit 4696256

Browse files
committed
reformatted
1 parent 6fc89be commit 4696256

6 files changed

Lines changed: 154 additions & 170 deletions

File tree

src/maxdiffusion/models/attention_flax.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1919,7 +1919,7 @@ def __call__(
19191919

19201920
qkv_proj = self.qkv(hidden_states)
19211921
qkv_proj = checkpoint_name(qkv_proj, "img_qkv_proj")
1922-
1922+
19231923
qkv_proj = qkv_proj.reshape(B, L, 3, H, D)
19241924
query_proj, key_proj, value_proj = jnp.split(qkv_proj, 3, axis=2)
19251925
query_proj = query_proj.squeeze(2)

src/maxdiffusion/models/flux/transformers/transformer_flux_flax.py

Lines changed: 80 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@
3030
from ....common_types import BlockSizes
3131
from ....utils import BaseOutput
3232
from ...gradient_checkpoint import GradientCheckpointType, SKIP_GRADIENT_CHECKPOINT_KEY
33-
from jax import checkpoint_policies as cp
3433
from jax.ad_checkpoint import checkpoint_name
3534

3635
AxisNames = common_types.AxisNames
@@ -83,9 +82,7 @@ def setup(self):
8382
def __call__(self, x, attn_output, gate, residual):
8483
mlp = self.lin_mlp(x)
8584
attn_mlp = jnp.concatenate([attn_output, self.mlp_act(mlp)], axis=2)
86-
attn_mlp = nn.with_logical_constraint(
87-
attn_mlp, ("activation_batch", None, "mlp")
88-
)
85+
attn_mlp = nn.with_logical_constraint(attn_mlp, ("activation_batch", None, "mlp"))
8986
hidden_states = self.linear2(attn_mlp)
9087
hidden_states = checkpoint_name(hidden_states, "lin2_hidden_states")
9188
hidden_states = gate * hidden_states
@@ -160,21 +157,19 @@ def setup(self):
160157

161158
def __call__(self, hidden_states, temb, image_rotary_emb=None):
162159
residual = hidden_states
163-
160+
164161
# FIX: Constrain inputs using valid config parameters (None skips sequence length axis parsing)
165-
hidden_states = nn.with_logical_constraint(
166-
hidden_states, ("activation_batch", None, "mlp")
167-
)
168-
162+
hidden_states = nn.with_logical_constraint(hidden_states, ("activation_batch", None, "mlp"))
163+
169164
norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
170-
165+
171166
qkv = self.lin_qkv(norm_hidden_states)
172167
qkv = checkpoint_name(qkv, "lin1_norm_hidden_states")
173168
qkv = nn.with_logical_constraint(qkv, ("activation_batch", None, "mlp"))
174-
169+
175170
B, L = hidden_states.shape[:2]
176171
H, D, K = self.num_attention_heads, qkv.shape[-1] // (self.num_attention_heads * 3), 3
177-
172+
178173
qkv_proj = qkv.reshape(B, L, K, H, D)
179174
q, k, v = jnp.split(qkv_proj, 3, axis=2)
180175
q = q.squeeze(2).swapaxes(1, 2)
@@ -196,7 +191,7 @@ def __call__(self, hidden_states, temb, image_rotary_emb=None):
196191
attn_output = checkpoint_name(attn_output, "attn_output")
197192

198193
hidden_states = self.mlp_and_out(norm_hidden_states, attn_output, gate, residual)
199-
194+
200195
if hidden_states.dtype == jnp.float16:
201196
hidden_states = jnp.clip(hidden_states, -65504, 65504)
202197

@@ -308,12 +303,12 @@ def __call__(self, hidden_states, encoder_hidden_states, temb, image_rotary_emb=
308303
# --- IMAGE STREAM OPTIMIZATION (img_norm2) ---
309304
attn_output = gate_msa * attn_output
310305
hidden_states = hidden_states + attn_output
311-
306+
312307
# Fully fused LayerNorm + scale_mlp + shift_mlp compilation block
313308
img_mean = jnp.mean(hidden_states, axis=-1, keepdims=True)
314309
img_var = jnp.mean(jnp.square(hidden_states - img_mean), axis=-1, keepdims=True)
315310
img_inv_std = jax.lax.rsqrt(img_var + self.eps)
316-
311+
317312
norm_hidden_states = (hidden_states - img_mean) * img_inv_std * (1 + scale_mlp) + shift_mlp
318313
norm_hidden_states = nn.with_logical_constraint(norm_hidden_states, ("activation_batch", None, "mlp"))
319314

@@ -334,48 +329,46 @@ def __call__(self, hidden_states, encoder_hidden_states, temb, image_rotary_emb=
334329

335330
context_ff_output = self.txt_mlp(norm_encoder_hidden_states)
336331
encoder_hidden_states = encoder_hidden_states + c_gate_mlp * context_ff_output
337-
332+
338333
# Safe numerical clipping limits for half precision math execution
339334
if encoder_hidden_states.dtype == jnp.float16 or encoder_hidden_states.dtype == jnp.bfloat16:
340335
encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
341336
hidden_states = hidden_states.clip(-65504, 65504)
342337

343338
return hidden_states, encoder_hidden_states
344339

340+
345341
class ScannedDoubleBlockWrapper(nn.Module):
346-
block_kwargs: dict
347-
348-
@nn.compact
349-
def __call__(self, carry, _):
350-
hidden_states, encoder_hidden_states, temb, image_rotary_emb = carry
351-
352-
# Instantiate the pure block (no remat here)
353-
block = FluxTransformerBlock(**self.block_kwargs)
354-
355-
h_out, e_out = block(
356-
hidden_states=hidden_states,
357-
encoder_hidden_states=encoder_hidden_states,
358-
temb=temb,
359-
image_rotary_emb=image_rotary_emb,
360-
)
361-
return (h_out, e_out, temb, image_rotary_emb), None
342+
block_kwargs: dict
343+
344+
@nn.compact
345+
def __call__(self, carry, _):
346+
hidden_states, encoder_hidden_states, temb, image_rotary_emb = carry
347+
348+
# Instantiate the pure block (no remat here)
349+
block = FluxTransformerBlock(**self.block_kwargs)
350+
351+
h_out, e_out = block(
352+
hidden_states=hidden_states,
353+
encoder_hidden_states=encoder_hidden_states,
354+
temb=temb,
355+
image_rotary_emb=image_rotary_emb,
356+
)
357+
return (h_out, e_out, temb, image_rotary_emb), None
362358

363359

364360
class ScannedSingleBlockWrapper(nn.Module):
365-
block_kwargs: dict
366-
367-
@nn.compact
368-
def __call__(self, carry, _):
369-
hidden_states, temb, image_rotary_emb = carry
370-
371-
# Instantiate the pure block
372-
block = FluxSingleTransformerBlock(**self.block_kwargs)
373-
h_out = block(
374-
hidden_states=hidden_states,
375-
temb=temb,
376-
image_rotary_emb=image_rotary_emb
377-
)
378-
return (h_out, temb, image_rotary_emb), None
361+
block_kwargs: dict
362+
363+
@nn.compact
364+
def __call__(self, carry, _):
365+
hidden_states, temb, image_rotary_emb = carry
366+
367+
# Instantiate the pure block
368+
block = FluxSingleTransformerBlock(**self.block_kwargs)
369+
h_out = block(hidden_states=hidden_states, temb=temb, image_rotary_emb=image_rotary_emb)
370+
return (h_out, temb, image_rotary_emb), None
371+
379372

380373
@flax_register_to_config
381374
class FluxTransformer2DModel(nn.Module, FlaxModelMixin, ConfigMixin):
@@ -446,25 +439,25 @@ def setup(self):
446439
self.gradient_checkpoint = GradientCheckpointType.from_str(self.remat_policy)
447440

448441
# 2. Apply the policy to the Module classes
449-
#RematDoubleBlock = self.gradient_checkpoint.apply_linen(FluxTransformerBlock)
450-
#RematSingleBlock = self.gradient_checkpoint.apply_linen(FluxSingleTransformerBlock)
442+
# RematDoubleBlock = self.gradient_checkpoint.apply_linen(FluxTransformerBlock)
443+
# RematSingleBlock = self.gradient_checkpoint.apply_linen(FluxSingleTransformerBlock)
451444

452445
# 1. Prepare the kwargs for the double blocks
453446
double_kwargs = {
454-
'dim': self.inner_dim,
455-
'num_attention_heads': self.num_attention_heads,
456-
'attention_head_dim': self.attention_head_dim,
457-
'attention_kernel': self.attention_kernel,
458-
'flash_min_seq_length': self.flash_min_seq_length,
459-
'flash_block_sizes': self.flash_block_sizes,
460-
'mesh': self.mesh,
461-
'dtype': self.dtype,
462-
'weights_dtype': self.weights_dtype,
463-
'precision': self.precision,
464-
'mlp_ratio': self.mlp_ratio,
465-
'qkv_bias': self.qkv_bias,
466-
'use_base2_exp': self.use_base2_exp,
467-
'use_experimental_scheduler': self.use_experimental_scheduler,
447+
"dim": self.inner_dim,
448+
"num_attention_heads": self.num_attention_heads,
449+
"attention_head_dim": self.attention_head_dim,
450+
"attention_kernel": self.attention_kernel,
451+
"flash_min_seq_length": self.flash_min_seq_length,
452+
"flash_block_sizes": self.flash_block_sizes,
453+
"mesh": self.mesh,
454+
"dtype": self.dtype,
455+
"weights_dtype": self.weights_dtype,
456+
"precision": self.precision,
457+
"mlp_ratio": self.mlp_ratio,
458+
"qkv_bias": self.qkv_bias,
459+
"use_base2_exp": self.use_base2_exp,
460+
"use_experimental_scheduler": self.use_experimental_scheduler,
468461
}
469462

470463
double_policy = self.gradient_checkpoint.to_jax_policy(
@@ -480,27 +473,27 @@ def setup(self):
480473

481474
self.scanned_double_blocks = nn.scan(
482475
RemattedDoubleWrapper,
483-
variable_axes={'params': 0},
484-
split_rngs={'params': True, 'dropout': True},
476+
variable_axes={"params": 0},
477+
split_rngs={"params": True, "dropout": True},
485478
length=self.num_layers,
486-
metadata_params={'partition_name': None}
479+
metadata_params={"partition_name": None},
487480
)(block_kwargs=double_kwargs)
488481

489482
# 3. Define pure kwargs for single blocks
490483
single_kwargs = {
491-
'dim': self.inner_dim,
492-
'num_attention_heads': self.num_attention_heads,
493-
'attention_head_dim': self.attention_head_dim,
494-
'attention_kernel': self.attention_kernel,
495-
'flash_min_seq_length': self.flash_min_seq_length,
496-
'flash_block_sizes': self.flash_block_sizes,
497-
'mesh': self.mesh,
498-
'dtype': self.dtype,
499-
'weights_dtype': self.weights_dtype,
500-
'precision': self.precision,
501-
'mlp_ratio': self.mlp_ratio,
502-
'use_base2_exp': self.use_base2_exp,
503-
'use_experimental_scheduler': self.use_experimental_scheduler,
484+
"dim": self.inner_dim,
485+
"num_attention_heads": self.num_attention_heads,
486+
"attention_head_dim": self.attention_head_dim,
487+
"attention_kernel": self.attention_kernel,
488+
"flash_min_seq_length": self.flash_min_seq_length,
489+
"flash_block_sizes": self.flash_block_sizes,
490+
"mesh": self.mesh,
491+
"dtype": self.dtype,
492+
"weights_dtype": self.weights_dtype,
493+
"precision": self.precision,
494+
"mlp_ratio": self.mlp_ratio,
495+
"use_base2_exp": self.use_base2_exp,
496+
"use_experimental_scheduler": self.use_experimental_scheduler,
504497
}
505498

506499
# 4. Force strict checkpointing on the Single Wrapper
@@ -517,10 +510,10 @@ def setup(self):
517510

518511
self.scanned_single_blocks = nn.scan(
519512
RemattedSingleWrapper,
520-
variable_axes={'params': 0},
521-
split_rngs={'params': True, 'dropout': True},
513+
variable_axes={"params": 0},
514+
split_rngs={"params": True, "dropout": True},
522515
length=self.num_single_layers,
523-
metadata_params={'partition_name': None}
516+
metadata_params={"partition_name": None},
524517
)(block_kwargs=single_kwargs)
525518

526519
self.norm_out = AdaLayerNormContinuous(
@@ -617,7 +610,7 @@ def __call__(
617610

618611
hidden_states = jnp.concatenate([encoder_hidden_states, hidden_states], axis=1)
619612
hidden_states = nn.with_logical_constraint(hidden_states, ("activation_batch", "activation_length", "activation_embed"))
620-
613+
621614
# Execute the 38 Single Blocks
622615
carry = (hidden_states, temb, image_rotary_emb)
623616
carry, _ = self.scanned_single_blocks(carry, None)
@@ -640,23 +633,23 @@ def init_weights(self, rngs, max_sequence_length, eval_only=True):
640633
batch_size = 1 * num_devices
641634
batch_image_shape = (
642635
batch_size,
643-
16,
636+
16,
644637
2 * resolution // scale_factor,
645638
2 * resolution // scale_factor,
646639
)
647640
text_shape = (
648641
batch_size,
649642
max_sequence_length,
650-
4096,
643+
4096,
651644
)
652645
text_ids_shape = (
653646
batch_size,
654647
max_sequence_length,
655-
3,
648+
3,
656649
)
657650
vec_shape = (
658651
batch_size,
659-
768,
652+
768,
660653
)
661654
img = jnp.zeros(batch_image_shape, dtype=self.dtype)
662655
bs, _, h, w = img.shape
@@ -694,4 +687,4 @@ def init_weights(self, rngs, max_sequence_length, eval_only=True):
694687
pooled_projections=vec,
695688
timestep=t_vec,
696689
guidance=guidance_vec,
697-
)["params"]
690+
)["params"]

src/maxdiffusion/models/flux/util.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -204,8 +204,12 @@ def load_flow_model(name: str, eval_shapes: dict, device: str, hf_download: bool
204204
qkv_pt_key = renamed_pt_key.replace("linear1", "lin_qkv")
205205
mlp_pt_key = renamed_pt_key.replace("linear1", "mlp_and_out.lin_mlp")
206206

207-
flax_key_qkv, flax_tensor_qkv = rename_key_and_reshape_tensor(tuple(qkv_pt_key.split(".")), qkv_tensor, eval_shapes, scan_layers=True)
208-
flax_key_mlp, flax_tensor_mlp = rename_key_and_reshape_tensor(tuple(mlp_pt_key.split(".")), mlp_tensor, eval_shapes, scan_layers=True)
207+
flax_key_qkv, flax_tensor_qkv = rename_key_and_reshape_tensor(
208+
tuple(qkv_pt_key.split(".")), qkv_tensor, eval_shapes, scan_layers=True
209+
)
210+
flax_key_mlp, flax_tensor_mlp = rename_key_and_reshape_tensor(
211+
tuple(mlp_pt_key.split(".")), mlp_tensor, eval_shapes, scan_layers=True
212+
)
209213

210214
if flax_key_qkv not in single_blocks_tensors:
211215
single_blocks_tensors[flax_key_qkv] = {}

src/maxdiffusion/models/gradient_checkpoint.py

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -126,30 +126,25 @@ def apply(
126126
return nnx.remat(module, prevent_cse=prevent_cse, policy=policy, static_argnums=static_argnums) # pylint: disable=invalid-name
127127

128128
def apply_linen(
129-
self,
130-
module_class: type[linen_nn.Module],
131-
names_which_can_be_saved: list = [],
132-
names_which_can_be_offloaded: list = [],
133-
static_argnums=(),
134-
prevent_cse: bool = False,
135-
) -> type[linen_nn.Module]:
136-
"""
137-
Applies a gradient checkpoint policy to a Linen module class.
138-
If no policy is needed, it will return the module class as is.
139-
140-
Args:
141-
module_class: the Linen Module class to apply the policy to
142-
143-
Returns:
144-
The rematerialized Module class (or the original if no policy).
145-
"""
146-
policy = self.to_jax_policy(names_which_can_be_saved, names_which_can_be_offloaded)
147-
if policy == SKIP_GRADIENT_CHECKPOINT_KEY:
148-
return module_class
149-
150-
return linen_nn.remat(
151-
module_class,
152-
prevent_cse=prevent_cse,
153-
policy=policy,
154-
static_argnums=static_argnums
155-
)
129+
self,
130+
module_class: type[linen_nn.Module],
131+
names_which_can_be_saved: list = [],
132+
names_which_can_be_offloaded: list = [],
133+
static_argnums=(),
134+
prevent_cse: bool = False,
135+
) -> type[linen_nn.Module]:
136+
"""
137+
Applies a gradient checkpoint policy to a Linen module class.
138+
If no policy is needed, it will return the module class as is.
139+
140+
Args:
141+
module_class: the Linen Module class to apply the policy to
142+
143+
Returns:
144+
The rematerialized Module class (or the original if no policy).
145+
"""
146+
policy = self.to_jax_policy(names_which_can_be_saved, names_which_can_be_offloaded)
147+
if policy == SKIP_GRADIENT_CHECKPOINT_KEY:
148+
return module_class
149+
150+
return linen_nn.remat(module_class, prevent_cse=prevent_cse, policy=policy, static_argnums=static_argnums)

0 commit comments

Comments
 (0)