|
| 1 | +import functools |
| 2 | + |
| 3 | +import torch |
| 4 | +from diffusers.models.attention import BasicTransformerBlock |
| 5 | +from diffusers.utils.import_utils import is_xformers_available |
| 6 | + |
| 7 | +from .lora import LoraInjectedLinear |
| 8 | + |
| 9 | +if is_xformers_available(): |
| 10 | + import xformers |
| 11 | + import xformers.ops |
| 12 | +else: |
| 13 | + xformers = None |
| 14 | + |
| 15 | + |
| 16 | +@functools.cache |
| 17 | +def test_xformers_backwards(size): |
| 18 | + @torch.enable_grad() |
| 19 | + def _grad(size): |
| 20 | + q = torch.randn((1, 4, size), device="cuda") |
| 21 | + k = torch.randn((1, 4, size), device="cuda") |
| 22 | + v = torch.randn((1, 4, size), device="cuda") |
| 23 | + |
| 24 | + q = q.detach().requires_grad_() |
| 25 | + k = k.detach().requires_grad_() |
| 26 | + v = v.detach().requires_grad_() |
| 27 | + |
| 28 | + out = xformers.ops.memory_efficient_attention(q, k, v) |
| 29 | + loss = out.sum(2).mean(0).sum() |
| 30 | + |
| 31 | + return torch.autograd.grad(loss, v) |
| 32 | + |
| 33 | + try: |
| 34 | + _grad(size) |
| 35 | + print(size, "pass") |
| 36 | + return True |
| 37 | + except Exception as e: |
| 38 | + print(size, "fail") |
| 39 | + return False |
| 40 | + |
| 41 | + |
| 42 | +def set_use_memory_efficient_attention_xformers( |
| 43 | + module: torch.nn.Module, valid: bool |
| 44 | +) -> None: |
| 45 | + def fn_test_dim_head(module: torch.nn.Module): |
| 46 | + if isinstance(module, BasicTransformerBlock): |
| 47 | + # dim_head isn't stored anywhere, so back-calculate |
| 48 | + source = module.attn1.to_v |
| 49 | + if isinstance(source, LoraInjectedLinear): |
| 50 | + source = source.linear |
| 51 | + |
| 52 | + dim_head = source.out_features // module.attn1.heads |
| 53 | + |
| 54 | + result = test_xformers_backwards(dim_head) |
| 55 | + |
| 56 | + # If dim_head > dim_head_max, turn xformers off |
| 57 | + if not result: |
| 58 | + module.set_use_memory_efficient_attention_xformers(False) |
| 59 | + |
| 60 | + for child in module.children(): |
| 61 | + fn_test_dim_head(child) |
| 62 | + |
| 63 | + if not is_xformers_available() and valid: |
| 64 | + print("XFormers is not available. Skipping.") |
| 65 | + return |
| 66 | + |
| 67 | + module.set_use_memory_efficient_attention_xformers(valid) |
| 68 | + |
| 69 | + if valid: |
| 70 | + fn_test_dim_head(module) |
0 commit comments