MCPcopy Create free account
hub / github.com/MotrixLab/ViMoGen / flash_attention

Function flash_attention

models/transformer/wan/modules/t2m_model.py:29–140  ·  view source on GitHub ↗

q: [B, Lq, Nq, C1]. k: [B, Lk, Nk, C1]. v: [B, Lk, Nk, C2]. Nq must be divisible by Nk. q_lens: [B]. k_lens: [B]. dropout_p: float. Dropout probability. softmax_scale: float. The scaling of QK^T before applying

(
    q,
    k,
    v,
    q_lens=None,
    k_lens=None,
    dropout_p=0.,
    softmax_scale=None,
    q_scale=None,
    causal=False,
    window_size=(-1, -1),
    deterministic=False,
    dtype=torch.bfloat16,
    version=None,
)

Source from the content-addressed store, hash-verified

27
28
29def flash_attention(
30 q,
31 k,
32 v,
33 q_lens=None,
34 k_lens=None,
35 dropout_p=0.,
36 softmax_scale=None,
37 q_scale=None,
38 causal=False,
39 window_size=(-1, -1),
40 deterministic=False,
41 dtype=torch.bfloat16,
42 version=None,
43):
44 """
45 q: [B, Lq, Nq, C1].
46 k: [B, Lk, Nk, C1].
47 v: [B, Lk, Nk, C2]. Nq must be divisible by Nk.
48 q_lens: [B].
49 k_lens: [B].
50 dropout_p: float. Dropout probability.
51 softmax_scale: float. The scaling of QK^T before applying softmax.
52 causal: bool. Whether to apply causal attention mask.
53 window_size: (left right). If not (-1, -1), apply sliding window local attention.
54 deterministic: bool. If True, slightly slower and uses more memory.
55 dtype: torch.dtype. Apply when dtype of q/k/v is not float16/bfloat16.
56 """
57 half_dtypes = (torch.float16, torch.bfloat16)
58 assert dtype in half_dtypes
59 assert q.device.type == 'cuda' and q.size(-1) <= 256
60
61 # params
62 b, lq, lk, out_dtype = q.size(0), q.size(1), k.size(1), q.dtype
63
64 def half(x):
65 return x if x.dtype in half_dtypes else x.to(dtype)
66
67 # preprocess query
68 if q_lens is None:
69 q = half(q.flatten(0, 1))
70 q_lens = torch.tensor(
71 [lq] * b, dtype=torch.int32).to(
72 device=q.device, non_blocking=True)
73 else:
74 q = half(torch.cat([u[:v] for u, v in zip(q, q_lens)]))
75
76 # preprocess key, value
77 if k_lens is None:
78 k = half(k.flatten(0, 1))
79 v = half(v.flatten(0, 1))
80 k_lens = torch.tensor(
81 [lk] * b, dtype=torch.int32).to(
82 device=k.device, non_blocking=True)
83 else:
84 k = half(torch.cat([u[:v] for u, v in zip(k, k_lens)]))
85 v = half(torch.cat([u[:v] for u, v in zip(v, k_lens)]))
86

Callers 4

attentionFunction · 0.70
forwardMethod · 0.70
forwardMethod · 0.70
forwardMethod · 0.70

Calls 1

halfFunction · 0.70

Tested by

no test coverage detected