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

Function flash_attention

models/transformer/wan/modules/tm2m_model.py:30–141  ·  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

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

Callers 3

attentionFunction · 0.70
forwardMethod · 0.70
forwardMethod · 0.70

Calls 1

halfFunction · 0.70

Tested by

no test coverage detected