22import itertools
33from typing import Any , Dict , List , Optional , Tuple , Union
44
5+ import numpy as np
6+
57import torch
68import torch .nn as nn
79
2022from .block_lumina2 import LuminaLayerNormContinuous , LuminaRMSNormZero , LuminaFeedForward , Lumina2CombinedTimestepCaptionEmbedding
2123
2224from ...utils .import_utils import is_triton_available , is_flash_attn_available
25+ from ...utils .teacache_util import TeaCacheParams
2326
2427if is_triton_available ():
2528 from ...ops .triton .layer_norm import RMSNorm
2831
2932logger = logging .get_logger (__name__ )
3033
31-
3234class OmniGen2TransformerBlock (nn .Module ):
3335 """
3436 Transformer block for OmniGen2 model.
@@ -342,6 +344,14 @@ def __init__(
342344
343345 self .initialize_weights ()
344346
347+ # TeaCache settings
348+ self .enable_teacache = False
349+ self .rel_l1_thresh = 0.05
350+ self .teacache_params = TeaCacheParams ()
351+
352+ coefficients = [- 5.48259225 , 11.48772289 , - 4.47407401 , 2.47730926 , - 0.03316487 ]
353+ self .rescale_func = np .poly1d (coefficients )
354+
345355 def initialize_weights (self ) -> None :
346356 """
347357 Initialize the weights of the model.
@@ -589,13 +599,46 @@ def forward(
589599
590600 hidden_states = joint_hidden_states
591601
592- for layer_idx , layer in enumerate (self .layers ):
593- if torch .is_grad_enabled () and self .gradient_checkpointing :
594- hidden_states = self ._gradient_checkpointing_func (
595- layer , hidden_states , attention_mask , rotary_emb , temb
602+ if self .enable_teacache :
603+ teacache_hidden_states = hidden_states .clone ()
604+ teacache_temb = temb .clone ()
605+ modulated_inp , _ , _ , _ = self .layers [0 ].norm1 (teacache_hidden_states , teacache_temb )
606+ if self .teacache_params .is_first_or_last_step :
607+ should_calc = True
608+ self .teacache_params .accumulated_rel_l1_distance = 0
609+ else :
610+ self .teacache_params .accumulated_rel_l1_distance += self .rescale_func (
611+ ((modulated_inp - self .teacache_params .previous_modulated_inp ).abs ().mean () \
612+ / self .teacache_params .previous_modulated_inp .abs ().mean ()).cpu ().item ()
596613 )
614+ if self .teacache_params .accumulated_rel_l1_distance < self .rel_l1_thresh :
615+ should_calc = False
616+ else :
617+ should_calc = True
618+ self .teacache_params .accumulated_rel_l1_distance = 0
619+ self .teacache_params .previous_modulated_inp = modulated_inp
620+
621+ if self .enable_teacache :
622+ if not should_calc :
623+ hidden_states += self .teacache_params .previous_residual
597624 else :
598- hidden_states = layer (hidden_states , attention_mask , rotary_emb , temb )
625+ ori_hidden_states = hidden_states .clone ()
626+ for layer_idx , layer in enumerate (self .layers ):
627+ if torch .is_grad_enabled () and self .gradient_checkpointing :
628+ hidden_states = self ._gradient_checkpointing_func (
629+ layer , hidden_states , attention_mask , rotary_emb , temb
630+ )
631+ else :
632+ hidden_states = layer (hidden_states , attention_mask , rotary_emb , temb )
633+ self .teacache_params .previous_residual = hidden_states - ori_hidden_states
634+ else :
635+ for layer_idx , layer in enumerate (self .layers ):
636+ if torch .is_grad_enabled () and self .gradient_checkpointing :
637+ hidden_states = self ._gradient_checkpointing_func (
638+ layer , hidden_states , attention_mask , rotary_emb , temb
639+ )
640+ else :
641+ hidden_states = layer (hidden_states , attention_mask , rotary_emb , temb )
599642
600643 # 4. Output norm & projection
601644 hidden_states = self .norm_out (hidden_states , temb )
@@ -614,4 +657,4 @@ def forward(
614657
615658 if not return_dict :
616659 return output
617- return Transformer2DModelOutput (sample = output )
660+ return Transformer2DModelOutput (sample = output )
0 commit comments