Skip to content

Commit 9187e56

Browse files
committed
make linter happy
1 parent 24d65c9 commit 9187e56

5 files changed

Lines changed: 170 additions & 166 deletions

File tree

nunchaku/caching/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-

nunchaku/caching/diffusers_adapters/__init__.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,14 @@
2525
2626
# Load any supported pipeline
2727
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev")
28-
28+
2929
# Apply caching automatically based on pipeline type
3030
cached_pipe = apply_cache_on_pipe(
31-
pipe,
31+
pipe,
3232
residual_diff_threshold=0.1,
3333
use_double_fb_cache=True
3434
)
35-
35+
3636
# Use the cached pipeline normally
3737
image = cached_pipe(prompt="A beautiful landscape")
3838
@@ -48,12 +48,12 @@
4848
def apply_cache_on_pipe(pipe: DiffusionPipeline, *args, **kwargs):
4949
"""
5050
Apply caching to a diffusers pipeline with automatic type detection.
51-
51+
5252
This function serves as a unified interface for applying Nunchaku caching
5353
to different types of diffusion pipelines. It automatically detects the
5454
pipeline type based on the class name and delegates to the appropriate
5555
caching implementation.
56-
56+
5757
Args:
5858
pipe (DiffusionPipeline): The diffusers pipeline to apply caching to
5959
*args: Variable positional arguments passed to the specific caching function
@@ -63,34 +63,34 @@ def apply_cache_on_pipe(pipe: DiffusionPipeline, *args, **kwargs):
6363
- use_double_fb_cache (bool): Whether to use double first-block caching
6464
- shallow_patch (bool): Whether to use shallow patching only
6565
- verbose (bool): Whether to enable verbose caching messages
66-
66+
6767
Returns:
6868
DiffusionPipeline: The same pipeline instance with caching applied
69-
69+
7070
Raises:
7171
ValueError: If the pipeline type is not supported (doesn't start with "Flux" or "Sana")
7272
AssertionError: If the input is not a DiffusionPipeline instance
73-
73+
7474
Example:
7575
With a Flux pipeline::
76-
76+
7777
from diffusers import FluxPipeline
7878
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev")
7979
cached_pipe = apply_cache_on_pipe(
80-
pipe,
80+
pipe,
8181
residual_diff_threshold=0.12,
8282
use_double_fb_cache=True
8383
)
84-
84+
8585
With a SANA pipeline::
86-
86+
8787
from diffusers import SanaPipeline
8888
pipe = SanaPipeline.from_pretrained("Efficient-Large-Model/Sana_600M_512px")
8989
cached_pipe = apply_cache_on_pipe(
9090
pipe,
9191
residual_diff_threshold=0.1
9292
)
93-
93+
9494
Note:
9595
The function modifies the pipeline in-place and returns the same instance.
9696
Currently supported pipeline types are those with class names starting

nunchaku/caching/diffusers_adapters/flux.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -71,11 +71,11 @@ def apply_cache_on_transformer(
7171
):
7272
"""
7373
Apply caching to a Flux transformer model.
74-
74+
7575
This function modifies a FluxTransformer2DModel to use cached transformer blocks
7676
for improved inference performance. It supports both single and double first-block
7777
caching strategies with configurable similarity thresholds.
78-
78+
7979
Args:
8080
transformer (FluxTransformer2DModel): The Flux transformer model to apply caching to
8181
use_double_fb_cache (bool, optional): Whether to use double first-block caching.
@@ -86,29 +86,29 @@ def apply_cache_on_transformer(
8686
attention blocks. If None, uses residual_diff_threshold. Defaults to None.
8787
residual_diff_threshold_single (float, optional): Similarity threshold for single-head
8888
attention blocks. Defaults to 0.1.
89-
89+
9090
Returns:
9191
FluxTransformer2DModel: The same transformer instance with caching applied
92-
92+
9393
Example:
9494
Basic caching setup::
95-
95+
9696
transformer = FluxTransformer2DModel.from_pretrained("model_name")
9797
cached_transformer = apply_cache_on_transformer(
9898
transformer,
9999
use_double_fb_cache=True,
100100
residual_diff_threshold=0.12
101101
)
102-
102+
103103
Advanced configuration::
104-
104+
105105
cached_transformer = apply_cache_on_transformer(
106106
transformer,
107107
use_double_fb_cache=True,
108108
residual_diff_threshold_multi=0.15,
109109
residual_diff_threshold_single=0.08
110110
)
111-
111+
112112
Note:
113113
If the transformer is already cached, the function updates the thresholds
114114
instead of reapplying caching. The caching only activates when a cache
@@ -161,11 +161,11 @@ def new_forward(self, *args, **kwargs):
161161
def apply_cache_on_pipe(pipe: DiffusionPipeline, *, shallow_patch: bool = False, **kwargs):
162162
"""
163163
Apply caching to a complete Flux diffusion pipeline.
164-
164+
165165
This function modifies a Flux diffusion pipeline to use caching during inference.
166166
It wraps the pipeline's __call__ method to automatically create and manage cache
167167
contexts, and optionally applies transformer-level caching.
168-
168+
169169
Args:
170170
pipe (DiffusionPipeline): The Flux diffusion pipeline to apply caching to
171171
shallow_patch (bool, optional): If True, only applies pipeline-level caching
@@ -176,33 +176,33 @@ def apply_cache_on_pipe(pipe: DiffusionPipeline, *, shallow_patch: bool = False,
176176
- residual_diff_threshold (float): Similarity threshold for caching
177177
- residual_diff_threshold_multi (float): Multi-head attention threshold
178178
- residual_diff_threshold_single (float): Single-head attention threshold
179-
179+
180180
Returns:
181181
DiffusionPipeline: The same pipeline instance with caching applied
182-
182+
183183
Example:
184184
Basic usage::
185-
185+
186186
from diffusers import FluxPipeline
187187
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev")
188188
cached_pipe = apply_cache_on_pipe(pipe)
189-
189+
190190
# Use normally - caching is transparent
191191
image = cached_pipe(prompt="A beautiful landscape")
192-
192+
193193
Advanced configuration::
194-
194+
195195
cached_pipe = apply_cache_on_pipe(
196196
pipe,
197197
use_double_fb_cache=True,
198198
residual_diff_threshold=0.1,
199199
residual_diff_threshold_single=0.05
200200
)
201-
201+
202202
Shallow patching for testing::
203-
203+
204204
cached_pipe = apply_cache_on_pipe(pipe, shallow_patch=True)
205-
205+
206206
Note:
207207
The function modifies the pipeline class's __call__ method, affecting all
208208
instances of the same pipeline class. If the pipeline is already cached,

nunchaku/caching/teacache.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
from diffusers import FluxTransformer2DModel
2929
3030
model = FluxTransformer2DModel.from_pretrained("black-forest-labs/FLUX.1-dev")
31-
31+
3232
with TeaCache(model, num_steps=50, rel_l1_thresh=0.6, skip_steps=10):
3333
# Model forward passes will use temporal caching
3434
for step in range(50):
@@ -59,33 +59,34 @@
5959
def make_teacache_forward(num_steps: int = 50, rel_l1_thresh: float = 0.6, skip_steps: int = 0) -> Callable:
6060
"""
6161
Create a cached forward method for Flux transformers using TeaCache.
62-
62+
6363
This factory function creates a modified forward method that implements temporal
6464
caching based on the relative L1 distance of modulated inputs. The caching
6565
decision is made by analyzing the first transformer block's modulated input
6666
and comparing it to the previous timestep.
67-
67+
6868
Args:
6969
num_steps (int, optional): Total number of inference steps. Used to determine
7070
when to reset the counter. Defaults to 50.
7171
rel_l1_thresh (float, optional): Relative L1 distance threshold for caching.
7272
Lower values mean more aggressive caching. Defaults to 0.6.
7373
skip_steps (int, optional): Number of initial steps to skip caching.
7474
Useful for allowing the model to stabilize. Defaults to 0.
75-
75+
7676
Returns:
7777
Callable: A cached forward method that can be bound to a transformer model
78-
78+
7979
Example:
8080
>>> model = FluxTransformer2DModel.from_pretrained("model_name")
8181
>>> cached_forward = make_teacache_forward(num_steps=50, rel_l1_thresh=0.6)
8282
>>> model.forward = cached_forward.__get__(model, type(model))
83-
83+
8484
Note:
8585
The rescaling function uses polynomial coefficients optimized for Flux models.
8686
The accumulated distance is reset when it exceeds the threshold or at the
8787
beginning/end of the inference sequence.
8888
"""
89+
8990
def teacache_forward(
9091
self: Union[FluxTransformer2DModel, NunchakuFluxTransformer2dModel],
9192
hidden_states: torch.Tensor,
@@ -405,14 +406,14 @@ def custom_forward(*inputs): # type: ignore
405406
class TeaCache:
406407
"""
407408
Context manager for applying TeaCache temporal caching to transformer models.
408-
409+
409410
This class provides a context manager that temporarily modifies a Flux transformer
410411
model to use TeaCache temporal caching. When entering the context, the model's
411412
forward method is replaced with a cached version that tracks temporal changes
412413
and skips computation when appropriate.
413-
414+
414415
Args:
415-
model (Union[FluxTransformer2DModel, NunchakuFluxTransformer2dModel]):
416+
model (Union[FluxTransformer2DModel, NunchakuFluxTransformer2dModel]):
416417
The transformer model to apply caching to
417418
num_steps (int, optional): Total number of inference steps. Defaults to 50.
418419
rel_l1_thresh (float, optional): Relative L1 distance threshold for caching.
@@ -421,32 +422,33 @@ class TeaCache:
421422
Useful for model stabilization. Defaults to 0.
422423
enabled (bool, optional): Whether caching is enabled. If False, the model
423424
behaves normally. Defaults to True.
424-
425+
425426
Attributes:
426427
model: Reference to the transformer model
427428
num_steps (int): Total number of inference steps
428429
rel_l1_thresh (float): Caching threshold
429430
skip_steps (int): Number of steps to skip caching
430431
enabled (bool): Caching enabled flag
431432
previous_model_forward: Original forward method (for restoration)
432-
433+
433434
Example:
434435
Basic usage::
435-
436+
436437
with TeaCache(model, num_steps=50, rel_l1_thresh=0.6):
437438
for step in range(50):
438439
output = model(inputs[step])
439-
440+
440441
Disabling caching conditionally::
441-
442+
442443
with TeaCache(model, enabled=use_caching):
443444
# Model will use caching only if use_caching is True
444445
output = model(inputs)
445-
446+
446447
Note:
447448
The context manager automatically restores the original forward method
448449
when exiting, ensuring the model can be used normally afterward.
449450
"""
451+
450452
def __init__(
451453
self,
452454
model: Union[FluxTransformer2DModel, NunchakuFluxTransformer2dModel],
@@ -465,14 +467,14 @@ def __init__(
465467
def __enter__(self) -> "TeaCache":
466468
"""
467469
Enter the TeaCache context and apply caching to the model.
468-
470+
469471
This method is called when entering the 'with' block. It replaces the
470472
model's forward method with a cached version and initializes the
471473
necessary state variables for tracking temporal changes.
472-
474+
473475
Returns:
474476
TeaCache: Self reference for context manager protocol
475-
477+
476478
Note:
477479
If caching is disabled (enabled=False), the model is left unchanged.
478480
"""
@@ -490,16 +492,16 @@ def __enter__(self) -> "TeaCache":
490492
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
491493
"""
492494
Exit the TeaCache context and restore the original model.
493-
495+
494496
This method is called when exiting the 'with' block. It restores the
495497
model's original forward method and cleans up the state variables
496498
that were added for caching.
497-
499+
498500
Args:
499501
exc_type: Exception type (if any occurred)
500-
exc_value: Exception value (if any occurred)
502+
exc_value: Exception value (if any occurred)
501503
traceback: Exception traceback (if any occurred)
502-
504+
503505
Note:
504506
If caching was disabled (enabled=False), no cleanup is performed.
505507
"""

0 commit comments

Comments
 (0)