Upload extensions_built_in/diffusion_models/chroma/src/math.py with huggingface_hub
Browse files
extensions_built_in/diffusion_models/chroma/src/math.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from einops import rearrange
|
| 3 |
+
from torch import Tensor
|
| 4 |
+
|
| 5 |
+
# Flash-Attention 2 (optional)
|
| 6 |
+
try:
|
| 7 |
+
from flash_attn.flash_attn_interface import flash_attn_func # type: ignore
|
| 8 |
+
_HAS_FLASH = True
|
| 9 |
+
except (ImportError, ModuleNotFoundError):
|
| 10 |
+
_HAS_FLASH = False
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor, mask: Tensor) -> Tensor:
|
| 14 |
+
q, k = apply_rope(q, k, pe)
|
| 15 |
+
|
| 16 |
+
# mask should have shape [B, H, L, D]
|
| 17 |
+
if _HAS_FLASH and mask is None and q.is_cuda:
|
| 18 |
+
x = flash_attn_func(
|
| 19 |
+
rearrange(q, "B H L D -> B L H D").contiguous(),
|
| 20 |
+
rearrange(k, "B H L D -> B L H D").contiguous(),
|
| 21 |
+
rearrange(v, "B H L D -> B L H D").contiguous(),
|
| 22 |
+
dropout_p=0.0,
|
| 23 |
+
softmax_scale=None,
|
| 24 |
+
causal=False,
|
| 25 |
+
)
|
| 26 |
+
x = rearrange(x, "B L H D -> B H L D")
|
| 27 |
+
else:
|
| 28 |
+
x = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=mask)
|
| 29 |
+
|
| 30 |
+
x = rearrange(x, "B H L D -> B L (H D)")
|
| 31 |
+
return x
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def rope(pos: Tensor, dim: int, theta: int) -> Tensor:
|
| 35 |
+
assert dim % 2 == 0
|
| 36 |
+
scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
|
| 37 |
+
omega = 1.0 / (theta**scale)
|
| 38 |
+
out = torch.einsum("...n,d->...nd", pos, omega)
|
| 39 |
+
out = torch.stack(
|
| 40 |
+
[torch.cos(out), -torch.sin(out), torch.sin(out), torch.cos(out)], dim=-1
|
| 41 |
+
)
|
| 42 |
+
out = rearrange(out, "b n d (i j) -> b n d i j", i=2, j=2)
|
| 43 |
+
return out.float()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
|
| 47 |
+
xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
|
| 48 |
+
xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
|
| 49 |
+
xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
|
| 50 |
+
xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
|
| 51 |
+
return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
|