kernels-bot commited on
Commit
8234084
·
verified ·
1 Parent(s): 24dbf71

Uploaded using `kernel-builder`.

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. build/torch211-cxx11-cu126-aarch64-linux/__init__.py +1 -20
  2. build/torch211-cxx11-cu126-aarch64-linux/{_flash_attn2_cuda_a511a4c.abi3.so → _flash_attn2_cuda_f12afc9.abi3.so} +2 -2
  3. build/torch211-cxx11-cu126-aarch64-linux/_ops.py +3 -3
  4. build/torch211-cxx11-cu126-aarch64-linux/flash_attn_interface.py +102 -133
  5. build/torch211-cxx11-cu126-aarch64-linux/layers/__init__.py +0 -0
  6. build/torch211-cxx11-cu126-aarch64-linux/layers/patch_embed.py +67 -0
  7. build/torch211-cxx11-cu126-aarch64-linux/layers/rotary.py +483 -0
  8. build/torch211-cxx11-cu126-aarch64-linux/metadata.json +20 -5
  9. build/torch211-cxx11-cu126-aarch64-linux/metadata.json.sigstore +1 -1
  10. build/torch211-cxx11-cu126-aarch64-linux/ops/__init__.py +0 -0
  11. build/torch211-cxx11-cu126-aarch64-linux/ops/activations.py +135 -0
  12. build/torch211-cxx11-cu126-aarch64-linux/ops/fused_dense.py +688 -0
  13. build/torch211-cxx11-cu126-aarch64-linux/ops/layer_norm.py +800 -0
  14. build/torch211-cxx11-cu126-aarch64-linux/ops/rms_norm.py +174 -0
  15. build/torch211-cxx11-cu126-aarch64-linux/ops/triton/__init__.py +1 -0
  16. build/torch211-cxx11-cu126-aarch64-linux/ops/triton/cross_entropy.py +330 -0
  17. build/torch211-cxx11-cu126-aarch64-linux/ops/triton/k_activations.py +162 -0
  18. build/torch211-cxx11-cu126-aarch64-linux/ops/triton/layer_norm.py +1254 -0
  19. build/torch211-cxx11-cu126-aarch64-linux/ops/triton/linear.py +594 -0
  20. build/torch211-cxx11-cu126-aarch64-linux/ops/triton/mlp.py +149 -0
  21. build/torch211-cxx11-cu126-aarch64-linux/ops/triton/rotary.py +186 -0
  22. build/torch211-cxx11-cu128-aarch64-linux/__init__.py +1 -20
  23. build/torch211-cxx11-cu128-aarch64-linux/{_flash_attn2_cuda_a511a4c.abi3.so → _flash_attn2_cuda_f12afc9.abi3.so} +2 -2
  24. build/torch211-cxx11-cu128-aarch64-linux/_ops.py +3 -3
  25. build/torch211-cxx11-cu128-aarch64-linux/flash_attn_interface.py +102 -133
  26. build/torch211-cxx11-cu128-aarch64-linux/layers/__init__.py +0 -0
  27. build/torch211-cxx11-cu128-aarch64-linux/layers/patch_embed.py +67 -0
  28. build/torch211-cxx11-cu128-aarch64-linux/layers/rotary.py +483 -0
  29. build/torch211-cxx11-cu128-aarch64-linux/metadata.json +20 -5
  30. build/torch211-cxx11-cu128-aarch64-linux/metadata.json.sigstore +1 -1
  31. build/torch211-cxx11-cu128-aarch64-linux/ops/__init__.py +0 -0
  32. build/torch211-cxx11-cu128-aarch64-linux/ops/activations.py +135 -0
  33. build/torch211-cxx11-cu128-aarch64-linux/ops/fused_dense.py +688 -0
  34. build/torch211-cxx11-cu128-aarch64-linux/ops/layer_norm.py +800 -0
  35. build/torch211-cxx11-cu128-aarch64-linux/ops/rms_norm.py +174 -0
  36. build/torch211-cxx11-cu128-aarch64-linux/ops/triton/__init__.py +1 -0
  37. build/torch211-cxx11-cu128-aarch64-linux/ops/triton/cross_entropy.py +330 -0
  38. build/torch211-cxx11-cu128-aarch64-linux/ops/triton/k_activations.py +162 -0
  39. build/torch211-cxx11-cu128-aarch64-linux/ops/triton/layer_norm.py +1254 -0
  40. build/torch211-cxx11-cu128-aarch64-linux/ops/triton/linear.py +594 -0
  41. build/torch211-cxx11-cu128-aarch64-linux/ops/triton/mlp.py +149 -0
  42. build/torch211-cxx11-cu128-aarch64-linux/ops/triton/rotary.py +186 -0
  43. build/torch211-cxx11-cu130-aarch64-linux/__init__.py +1 -20
  44. build/torch211-cxx11-cu130-aarch64-linux/{_flash_attn2_cuda_a511a4c.abi3.so → _flash_attn2_cuda_f12afc9.abi3.so} +2 -2
  45. build/torch211-cxx11-cu130-aarch64-linux/_ops.py +3 -3
  46. build/torch211-cxx11-cu130-aarch64-linux/flash_attn_interface.py +102 -133
  47. build/torch211-cxx11-cu130-aarch64-linux/layers/__init__.py +0 -0
  48. build/torch211-cxx11-cu130-aarch64-linux/layers/patch_embed.py +67 -0
  49. build/torch211-cxx11-cu130-aarch64-linux/layers/rotary.py +483 -0
  50. build/torch211-cxx11-cu130-aarch64-linux/metadata.json +20 -5
build/torch211-cxx11-cu126-aarch64-linux/__init__.py CHANGED
@@ -1,7 +1,5 @@
1
- from typing import List, Optional
2
-
3
  import torch
4
-
5
  from ._ops import ops as flash_attn_ops
6
  from .flash_attn_interface import (
7
  flash_attn_func,
@@ -13,23 +11,6 @@ from .flash_attn_interface import (
13
  flash_attn_with_kvcache,
14
  )
15
 
16
- __all__ = [
17
- # High-level API (with autograd support)
18
- "flash_attn_func",
19
- "flash_attn_kvpacked_func",
20
- "flash_attn_qkvpacked_func",
21
- "flash_attn_varlen_func",
22
- "flash_attn_varlen_kvpacked_func",
23
- "flash_attn_varlen_qkvpacked_func",
24
- "flash_attn_with_kvcache",
25
- # Low-level ops (no autograd)
26
- "fwd",
27
- "varlen_fwd",
28
- "bwd",
29
- "varlen_bwd",
30
- "fwd_kvcache",
31
- ]
32
-
33
 
34
  def fwd(
35
  q: torch.Tensor,
 
1
+ from typing import Optional, List
 
2
  import torch
 
3
  from ._ops import ops as flash_attn_ops
4
  from .flash_attn_interface import (
5
  flash_attn_func,
 
11
  flash_attn_with_kvcache,
12
  )
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  def fwd(
16
  q: torch.Tensor,
build/torch211-cxx11-cu126-aarch64-linux/{_flash_attn2_cuda_a511a4c.abi3.so → _flash_attn2_cuda_f12afc9.abi3.so} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:61f802416c0c37133b3eb961e3b6b5f08478d5c21a3aa89d606ad89443df8fcb
3
- size 448605160
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9723af07fc19a183a32c259c203d6062379babf1070527da5674be1660a062d
3
+ size 446583112
build/torch211-cxx11-cu126-aarch64-linux/_ops.py CHANGED
@@ -1,9 +1,9 @@
1
  import torch
2
- from . import _flash_attn2_cuda_a511a4c
3
- ops = torch.ops._flash_attn2_cuda_a511a4c
4
 
5
  def add_op_namespace_prefix(op_name: str):
6
  """
7
  Prefix op by namespace.
8
  """
9
- return f"_flash_attn2_cuda_a511a4c::{op_name}"
 
1
  import torch
2
+ from . import _flash_attn2_cuda_f12afc9
3
+ ops = torch.ops._flash_attn2_cuda_f12afc9
4
 
5
  def add_op_namespace_prefix(op_name: str):
6
  """
7
  Prefix op by namespace.
8
  """
9
+ return f"_flash_attn2_cuda_f12afc9::{op_name}"
build/torch211-cxx11-cu126-aarch64-linux/flash_attn_interface.py CHANGED
@@ -15,12 +15,12 @@ import os
15
  # import flash_attn_2_cuda as flash_attn
16
 
17
 
 
18
  from ._ops import ops as flash_attn
19
  from ._ops import add_op_namespace_prefix
20
 
21
  # # isort: on
22
 
23
-
24
  def maybe_contiguous(x):
25
  return x.contiguous() if x is not None and x.stride(-1) != 1 else x
26
 
@@ -49,9 +49,7 @@ def _get_block_size_n(device, head_dim, is_dropout, is_causal):
49
 
50
  # This should match the block sizes in the CUDA kernel
51
  major, minor = torch.cuda.get_device_capability(device)
52
- is_sm8x = (
53
- major == 8 and minor > 0
54
- ) # Only include sm86 and sm89, exclude sm80 (A100)
55
  is_sm80 = major == 8 and minor == 0
56
  is_sm90 = major == 9 and minor == 0
57
  if head_dim <= 32:
@@ -77,11 +75,30 @@ def round_multiple(x, m):
77
  return (x + m - 1) // m * m
78
 
79
 
80
- @torch.library.custom_op(
81
- add_op_namespace_prefix("_flash_attn_forward"),
82
- mutates_args=(),
83
- device_types=_get_device(),
84
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  def _flash_attn_forward(
86
  q: torch.Tensor,
87
  k: torch.Tensor,
@@ -93,7 +110,7 @@ def _flash_attn_forward(
93
  window_size_right: int,
94
  softcap: float,
95
  alibi_slopes: Optional[torch.Tensor],
96
- return_softmax: bool,
97
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
98
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
99
  out, softmax_lse, S_dmask, rng_state = flash_attn.fwd(
@@ -114,7 +131,7 @@ def _flash_attn_forward(
114
  return out, softmax_lse, S_dmask, rng_state
115
 
116
 
117
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_forward"))
118
  def _flash_attn_forward_fake(
119
  q: torch.Tensor,
120
  k: torch.Tensor,
@@ -126,41 +143,28 @@ def _flash_attn_forward_fake(
126
  window_size_right: int,
127
  softcap: float,
128
  alibi_slopes: Optional[torch.Tensor],
129
- return_softmax: bool,
130
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
131
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
132
  batch_size, seqlen_q, num_heads, head_size = q.shape
133
  seqlen_k = k.shape[1]
134
  out = torch.empty_like(q)
135
- softmax_lse = torch.empty(
136
- (batch_size, num_heads, seqlen_q),
137
- dtype=torch.float32,
138
- device=q.device,
139
- layout=q.layout,
140
- )
141
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
142
  if return_softmax:
143
- p = torch.empty(
144
- (
145
- batch_size,
146
- num_heads,
147
- round_multiple(seqlen_q, 128),
148
- round_multiple(seqlen_k, 128),
149
- ),
150
- dtype=q.dtype,
151
- device=q.device,
152
- layout=q.layout,
153
- )
154
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
155
 
156
  return out, softmax_lse, p, rng_state
157
 
158
 
159
- @torch.library.custom_op(
160
- add_op_namespace_prefix("_flash_attn_varlen_forward"),
161
- mutates_args=(),
162
- device_types=_get_device(),
163
- )
 
 
164
  def _flash_attn_varlen_forward(
165
  q: torch.Tensor,
166
  k: torch.Tensor,
@@ -211,7 +215,7 @@ def _flash_attn_varlen_forward(
211
  return out, softmax_lse, S_dmask, rng_state
212
 
213
 
214
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_varlen_forward"))
215
  def _flash_attn_varlen_forward_fake(
216
  q: torch.Tensor,
217
  k: torch.Tensor,
@@ -237,30 +241,25 @@ def _flash_attn_varlen_forward_fake(
237
  paged_kv = block_table is not None
238
  batch_size = cu_seqlens_q.numel() - 1
239
  total_q, num_heads, _ = q.shape
240
-
241
  out = torch.empty_like(q)
242
- softmax_lse = torch.empty(
243
- (num_heads, total_q), dtype=torch.float32, device=q.device, layout=q.layout
244
- )
245
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
246
  seqlen_q_rounded = round_multiple(max_seqlen_q, 128)
247
  seqlen_k_rounded = round_multiple(max_seqlen_k, 128)
248
  if return_softmax:
249
- p = torch.empty(
250
- (batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded),
251
- dtype=q.dtype,
252
- device=q.device,
253
- layout=q.layout,
254
- )
255
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
256
  return out, softmax_lse, p, rng_state
257
 
258
 
259
- @torch.library.custom_op(
260
- add_op_namespace_prefix("_flash_attn_backward"),
261
- mutates_args=("dq", "dk", "dv"),
262
- device_types=_get_device(),
263
- )
 
 
264
  def _flash_attn_backward(
265
  dout: torch.Tensor,
266
  q: torch.Tensor,
@@ -312,7 +311,7 @@ def _flash_attn_backward(
312
  return softmax_d
313
 
314
 
315
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_backward"))
316
  def _flash_attn_backward_fake(
317
  dout: torch.Tensor,
318
  q: torch.Tensor,
@@ -341,20 +340,18 @@ def _flash_attn_backward_fake(
341
  if dv is None:
342
  dv = torch.empty_like(v)
343
  batch_size, seqlen_q, num_heads, _ = q.shape
344
- softmax_d = torch.empty(
345
- (batch_size, num_heads, round_multiple(seqlen_q, 128)),
346
- device=q.device,
347
- dtype=torch.float32,
348
- )
349
-
350
  return softmax_d
351
 
352
 
353
- @torch.library.custom_op(
354
- add_op_namespace_prefix("_flash_attn_varlen_backward"),
355
- mutates_args=("dq", "dk", "dv"),
356
- device_types=_get_device(),
357
- )
 
 
358
  def _flash_attn_varlen_backward(
359
  dout: torch.Tensor,
360
  q: torch.Tensor,
@@ -418,7 +415,7 @@ def _flash_attn_varlen_backward(
418
  return softmax_d
419
 
420
 
421
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_varlen_backward"))
422
  def _flash_attn_varlen_backward_fake(
423
  dout: torch.Tensor,
424
  q: torch.Tensor,
@@ -454,13 +451,17 @@ def _flash_attn_varlen_backward_fake(
454
  dk = torch.empty_like(k)
455
  if dv is None:
456
  dv = torch.empty_like(v)
457
- softmax_d = torch.empty(
458
- (num_heads, total_q + 128 * batch_size), device=q.device, dtype=torch.float32
459
- )
460
-
461
  return softmax_d
462
 
463
 
 
 
 
 
 
 
464
  class FlashAttnQKVPackedFunc(torch.autograd.Function):
465
  @staticmethod
466
  def forward(
@@ -485,7 +486,7 @@ class FlashAttnQKVPackedFunc(torch.autograd.Function):
485
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
486
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
487
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
488
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_forward(
489
  q,
490
  k,
491
  v,
@@ -519,7 +520,7 @@ class FlashAttnQKVPackedFunc(torch.autograd.Function):
519
  dout_padded = dout
520
  if head_size_og % 8 != 0:
521
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
522
- _flash_attn_backward(
523
  dout_padded,
524
  q,
525
  k,
@@ -569,7 +570,7 @@ class FlashAttnVarlenQKVPackedFunc(torch.autograd.Function):
569
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
570
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
571
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
572
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_varlen_forward(
573
  q,
574
  k,
575
  v,
@@ -588,9 +589,7 @@ class FlashAttnVarlenQKVPackedFunc(torch.autograd.Function):
588
  block_table=None,
589
  )
590
  if is_grad:
591
- ctx.save_for_backward(
592
- q, k, v, out_padded, softmax_lse, cu_seqlens, rng_state
593
- )
594
  ctx.dropout_p = dropout_p
595
  ctx.max_seqlen = max_seqlen
596
  ctx.softmax_scale = softmax_scale
@@ -611,7 +610,7 @@ class FlashAttnVarlenQKVPackedFunc(torch.autograd.Function):
611
  dout_padded = dout
612
  if head_size_og % 8 != 0:
613
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
614
- _flash_attn_varlen_backward(
615
  dout_padded,
616
  q,
617
  k,
@@ -655,7 +654,9 @@ class FlashAttnKVPackedFunc(torch.autograd.Function):
655
  return_softmax,
656
  is_grad_enabled,
657
  ):
658
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, kv])
 
 
659
  if softmax_scale is None:
660
  softmax_scale = q.shape[-1] ** (-0.5)
661
  k, v = kv[:, :, 0].detach(), kv[:, :, 1].detach()
@@ -664,7 +665,7 @@ class FlashAttnKVPackedFunc(torch.autograd.Function):
664
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
665
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
666
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
667
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_forward(
668
  q,
669
  k,
670
  v,
@@ -699,7 +700,7 @@ class FlashAttnKVPackedFunc(torch.autograd.Function):
699
  dout_padded = dout
700
  if head_size_og % 8 != 0:
701
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
702
- _flash_attn_backward(
703
  dout_padded,
704
  q,
705
  k,
@@ -744,7 +745,9 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
744
  return_softmax,
745
  is_grad_enabled,
746
  ):
747
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, kv])
 
 
748
  if softmax_scale is None:
749
  softmax_scale = q.shape[-1] ** (-0.5)
750
  k, v = kv[:, 0].detach(), kv[:, 1].detach()
@@ -753,7 +756,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
753
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
754
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
755
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
756
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_varlen_forward(
757
  q,
758
  k,
759
  v,
@@ -789,9 +792,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
789
 
790
  @staticmethod
791
  def backward(ctx, dout, *args):
792
- q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = (
793
- ctx.saved_tensors
794
- )
795
  dq = torch.empty_like(q)
796
  kv_shape = k.shape[:-2] + (2, *k.shape[-2:])
797
  dkv = torch.empty(kv_shape, dtype=k.dtype, device=k.device)
@@ -799,7 +800,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
799
  dout_padded = dout
800
  if head_size_og % 8 != 0:
801
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
802
- _flash_attn_varlen_backward(
803
  dout_padded,
804
  q,
805
  k,
@@ -825,23 +826,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
825
  )
826
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
827
  dkv = dkv[..., : dout.shape[-1]]
828
- return (
829
- dq,
830
- dkv,
831
- None,
832
- None,
833
- None,
834
- None,
835
- None,
836
- None,
837
- None,
838
- None,
839
- None,
840
- None,
841
- None,
842
- None,
843
- None,
844
- )
845
 
846
 
847
  class FlashAttnFunc(torch.autograd.Function):
@@ -861,7 +846,9 @@ class FlashAttnFunc(torch.autograd.Function):
861
  return_softmax,
862
  is_grad_enabled,
863
  ):
864
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, k, v])
 
 
865
  if softmax_scale is None:
866
  softmax_scale = q.shape[-1] ** (-0.5)
867
  head_size_og = q.size(3)
@@ -869,7 +856,7 @@ class FlashAttnFunc(torch.autograd.Function):
869
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
870
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
871
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
872
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_forward(
873
  q,
874
  k,
875
  v,
@@ -902,7 +889,7 @@ class FlashAttnFunc(torch.autograd.Function):
902
  dout_padded = dout
903
  if head_size_og % 8 != 0:
904
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
905
- _flash_attn_backward(
906
  dout_padded,
907
  q,
908
  k,
@@ -950,7 +937,9 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
950
  block_table,
951
  is_grad_enabled,
952
  ):
953
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, k, v])
 
 
954
  if softmax_scale is None:
955
  softmax_scale = q.shape[-1] ** (-0.5)
956
  head_size_og = q.size(2)
@@ -958,7 +947,7 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
958
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
959
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
960
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
961
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_varlen_forward(
962
  q,
963
  k,
964
  v,
@@ -995,15 +984,13 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
995
 
996
  @staticmethod
997
  def backward(ctx, dout, *args):
998
- q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = (
999
- ctx.saved_tensors
1000
- )
1001
  dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
1002
  head_size_og = dout.size(2)
1003
  dout_padded = dout
1004
  if head_size_og % 8 != 0:
1005
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
1006
- _flash_attn_varlen_backward(
1007
  dout_padded,
1008
  q,
1009
  k,
@@ -1030,25 +1017,7 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
1030
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
1031
  dk = dk[..., : dout.shape[-1]]
1032
  dv = dv[..., : dout.shape[-1]]
1033
- return (
1034
- dq,
1035
- dk,
1036
- dv,
1037
- None,
1038
- None,
1039
- None,
1040
- None,
1041
- None,
1042
- None,
1043
- None,
1044
- None,
1045
- None,
1046
- None,
1047
- None,
1048
- None,
1049
- None,
1050
- None,
1051
- )
1052
 
1053
 
1054
  def flash_attn_qkvpacked_func(
@@ -1196,7 +1165,7 @@ def flash_attn_func(
1196
  softmax_scale=None,
1197
  causal=False,
1198
  window_size=(-1, -1), # -1 means infinite context window
1199
- softcap=0.0, # 0.0 means deactivated
1200
  alibi_slopes=None,
1201
  deterministic=False,
1202
  return_attn_probs=False,
@@ -1273,7 +1242,7 @@ def flash_attn_varlen_qkvpacked_func(
1273
  softmax_scale=None,
1274
  causal=False,
1275
  window_size=(-1, -1), # -1 means infinite context window
1276
- softcap=0.0, # 0.0 means deactivated
1277
  alibi_slopes=None,
1278
  deterministic=False,
1279
  return_attn_probs=False,
@@ -1342,7 +1311,7 @@ def flash_attn_varlen_kvpacked_func(
1342
  softmax_scale=None,
1343
  causal=False,
1344
  window_size=(-1, -1), # -1 means infinite context window
1345
- softcap=0.0, # 0.0 means deactivated
1346
  alibi_slopes=None,
1347
  deterministic=False,
1348
  return_attn_probs=False,
@@ -1435,7 +1404,7 @@ def flash_attn_varlen_func(
1435
  softmax_scale=None,
1436
  causal=False,
1437
  window_size=(-1, -1), # -1 means infinite context window
1438
- softcap=0.0, # 0.0 means deactivated
1439
  alibi_slopes=None,
1440
  deterministic=False,
1441
  return_attn_probs=False,
@@ -1532,7 +1501,7 @@ def flash_attn_with_kvcache(
1532
  softmax_scale=None,
1533
  causal=False,
1534
  window_size=(-1, -1), # -1 means infinite context window
1535
- softcap=0.0, # 0.0 means deactivated
1536
  rotary_interleaved=True,
1537
  alibi_slopes=None,
1538
  num_splits=0,
 
15
  # import flash_attn_2_cuda as flash_attn
16
 
17
 
18
+ from . import _ops
19
  from ._ops import ops as flash_attn
20
  from ._ops import add_op_namespace_prefix
21
 
22
  # # isort: on
23
 
 
24
  def maybe_contiguous(x):
25
  return x.contiguous() if x is not None and x.stride(-1) != 1 else x
26
 
 
49
 
50
  # This should match the block sizes in the CUDA kernel
51
  major, minor = torch.cuda.get_device_capability(device)
52
+ is_sm8x = major == 8 and minor > 0 # Only include sm86 and sm89, exclude sm80 (A100)
 
 
53
  is_sm80 = major == 8 and minor == 0
54
  is_sm90 = major == 9 and minor == 0
55
  if head_dim <= 32:
 
75
  return (x + m - 1) // m * m
76
 
77
 
78
+ # torch.compile() support is only enabled for pytorch >= 2.4
79
+ # The reason for this is that we are using the new custom_op and register_fake
80
+ # APIs, which support inplace modification of inputs in the function itself
81
+ if torch.__version__ >= "2.4.0":
82
+ _torch_custom_op_wrapper = torch.library.custom_op
83
+ _torch_register_fake_wrapper = torch.library.register_fake
84
+ else:
85
+ def noop_custom_op_wrapper(name, fn=None, /, *, mutates_args, device_types=None, schema=None):
86
+ def wrap(func):
87
+ return func
88
+ if fn is None:
89
+ return wrap
90
+ return fn
91
+ def noop_register_fake_wrapper(op, fn=None, /, *, lib=None, _stacklevel=1):
92
+ def wrap(func):
93
+ return func
94
+ if fn is None:
95
+ return wrap
96
+ return fn
97
+ _torch_custom_op_wrapper = noop_custom_op_wrapper
98
+ _torch_register_fake_wrapper = noop_register_fake_wrapper
99
+
100
+
101
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_forward"), mutates_args=(), device_types=_get_device())
102
  def _flash_attn_forward(
103
  q: torch.Tensor,
104
  k: torch.Tensor,
 
110
  window_size_right: int,
111
  softcap: float,
112
  alibi_slopes: Optional[torch.Tensor],
113
+ return_softmax: bool
114
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
115
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
116
  out, softmax_lse, S_dmask, rng_state = flash_attn.fwd(
 
131
  return out, softmax_lse, S_dmask, rng_state
132
 
133
 
134
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_forward"))
135
  def _flash_attn_forward_fake(
136
  q: torch.Tensor,
137
  k: torch.Tensor,
 
143
  window_size_right: int,
144
  softcap: float,
145
  alibi_slopes: Optional[torch.Tensor],
146
+ return_softmax: bool
147
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
148
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
149
  batch_size, seqlen_q, num_heads, head_size = q.shape
150
  seqlen_k = k.shape[1]
151
  out = torch.empty_like(q)
152
+ softmax_lse = torch.empty((batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device, layout=q.layout)
 
 
 
 
 
153
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
154
  if return_softmax:
155
+ p = torch.empty((batch_size, num_heads, round_multiple(seqlen_q, 128), round_multiple(seqlen_k, 128)), dtype=q.dtype, device=q.device, layout=q.layout)
 
 
 
 
 
 
 
 
 
 
156
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
157
 
158
  return out, softmax_lse, p, rng_state
159
 
160
 
161
+ if torch.__version__ >= "2.4.0":
162
+ _wrapped_flash_attn_forward = _ops.ops._flash_attn_forward
163
+ else:
164
+ _wrapped_flash_attn_forward = _flash_attn_forward
165
+
166
+
167
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_varlen_forward"), mutates_args=(), device_types=_get_device())
168
  def _flash_attn_varlen_forward(
169
  q: torch.Tensor,
170
  k: torch.Tensor,
 
215
  return out, softmax_lse, S_dmask, rng_state
216
 
217
 
218
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_varlen_forward"))
219
  def _flash_attn_varlen_forward_fake(
220
  q: torch.Tensor,
221
  k: torch.Tensor,
 
241
  paged_kv = block_table is not None
242
  batch_size = cu_seqlens_q.numel() - 1
243
  total_q, num_heads, _ = q.shape
244
+
245
  out = torch.empty_like(q)
246
+ softmax_lse = torch.empty((num_heads, total_q), dtype=torch.float32, device=q.device, layout=q.layout)
 
 
247
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
248
  seqlen_q_rounded = round_multiple(max_seqlen_q, 128)
249
  seqlen_k_rounded = round_multiple(max_seqlen_k, 128)
250
  if return_softmax:
251
+ p = torch.empty((batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded), dtype=q.dtype, device=q.device, layout=q.layout)
 
 
 
 
 
252
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
253
  return out, softmax_lse, p, rng_state
254
 
255
 
256
+ if torch.__version__ >= "2.4.0":
257
+ _wrapped_flash_attn_varlen_forward = _ops.ops._flash_attn_varlen_forward
258
+ else:
259
+ _wrapped_flash_attn_varlen_forward = _flash_attn_varlen_forward
260
+
261
+
262
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_backward"), mutates_args=("dq", "dk", "dv"), device_types=_get_device())
263
  def _flash_attn_backward(
264
  dout: torch.Tensor,
265
  q: torch.Tensor,
 
311
  return softmax_d
312
 
313
 
314
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_backward"))
315
  def _flash_attn_backward_fake(
316
  dout: torch.Tensor,
317
  q: torch.Tensor,
 
340
  if dv is None:
341
  dv = torch.empty_like(v)
342
  batch_size, seqlen_q, num_heads, _ = q.shape
343
+ softmax_d = torch.empty((batch_size, num_heads, round_multiple(seqlen_q, 128)), device=q.device, dtype=torch.float32)
344
+
 
 
 
 
345
  return softmax_d
346
 
347
 
348
+ if torch.__version__ >= "2.4.0":
349
+ _wrapped_flash_attn_backward = _ops.ops._flash_attn_backward
350
+ else:
351
+ _wrapped_flash_attn_backward = _flash_attn_backward
352
+
353
+
354
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_varlen_backward"), mutates_args=("dq", "dk", "dv"), device_types=_get_device())
355
  def _flash_attn_varlen_backward(
356
  dout: torch.Tensor,
357
  q: torch.Tensor,
 
415
  return softmax_d
416
 
417
 
418
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_varlen_backward"))
419
  def _flash_attn_varlen_backward_fake(
420
  dout: torch.Tensor,
421
  q: torch.Tensor,
 
451
  dk = torch.empty_like(k)
452
  if dv is None:
453
  dv = torch.empty_like(v)
454
+ softmax_d = torch.empty((num_heads, total_q + 128 * batch_size), device=q.device, dtype=torch.float32)
455
+
 
 
456
  return softmax_d
457
 
458
 
459
+ if torch.__version__ >= "2.4.0":
460
+ _wrapped_flash_attn_varlen_backward = _ops.ops._flash_attn_varlen_backward
461
+ else:
462
+ _wrapped_flash_attn_varlen_backward = _flash_attn_varlen_backward
463
+
464
+
465
  class FlashAttnQKVPackedFunc(torch.autograd.Function):
466
  @staticmethod
467
  def forward(
 
486
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
487
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
488
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
489
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward(
490
  q,
491
  k,
492
  v,
 
520
  dout_padded = dout
521
  if head_size_og % 8 != 0:
522
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
523
+ _wrapped_flash_attn_backward(
524
  dout_padded,
525
  q,
526
  k,
 
570
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
571
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
572
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
573
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward(
574
  q,
575
  k,
576
  v,
 
589
  block_table=None,
590
  )
591
  if is_grad:
592
+ ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens, rng_state)
 
 
593
  ctx.dropout_p = dropout_p
594
  ctx.max_seqlen = max_seqlen
595
  ctx.softmax_scale = softmax_scale
 
610
  dout_padded = dout
611
  if head_size_og % 8 != 0:
612
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
613
+ _wrapped_flash_attn_varlen_backward(
614
  dout_padded,
615
  q,
616
  k,
 
654
  return_softmax,
655
  is_grad_enabled,
656
  ):
657
+ is_grad = is_grad_enabled and any(
658
+ x.requires_grad for x in [q, kv]
659
+ )
660
  if softmax_scale is None:
661
  softmax_scale = q.shape[-1] ** (-0.5)
662
  k, v = kv[:, :, 0].detach(), kv[:, :, 1].detach()
 
665
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
666
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
667
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
668
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward(
669
  q,
670
  k,
671
  v,
 
700
  dout_padded = dout
701
  if head_size_og % 8 != 0:
702
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
703
+ _wrapped_flash_attn_backward(
704
  dout_padded,
705
  q,
706
  k,
 
745
  return_softmax,
746
  is_grad_enabled,
747
  ):
748
+ is_grad = is_grad_enabled and any(
749
+ x.requires_grad for x in [q, kv]
750
+ )
751
  if softmax_scale is None:
752
  softmax_scale = q.shape[-1] ** (-0.5)
753
  k, v = kv[:, 0].detach(), kv[:, 1].detach()
 
756
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
757
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
758
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
759
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward(
760
  q,
761
  k,
762
  v,
 
792
 
793
  @staticmethod
794
  def backward(ctx, dout, *args):
795
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors
 
 
796
  dq = torch.empty_like(q)
797
  kv_shape = k.shape[:-2] + (2, *k.shape[-2:])
798
  dkv = torch.empty(kv_shape, dtype=k.dtype, device=k.device)
 
800
  dout_padded = dout
801
  if head_size_og % 8 != 0:
802
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
803
+ _wrapped_flash_attn_varlen_backward(
804
  dout_padded,
805
  q,
806
  k,
 
826
  )
827
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
828
  dkv = dkv[..., : dout.shape[-1]]
829
+ return dq, dkv, None, None, None, None, None, None, None, None, None, None, None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
830
 
831
 
832
  class FlashAttnFunc(torch.autograd.Function):
 
846
  return_softmax,
847
  is_grad_enabled,
848
  ):
849
+ is_grad = is_grad_enabled and any(
850
+ x.requires_grad for x in [q, k, v]
851
+ )
852
  if softmax_scale is None:
853
  softmax_scale = q.shape[-1] ** (-0.5)
854
  head_size_og = q.size(3)
 
856
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
857
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
858
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
859
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward(
860
  q,
861
  k,
862
  v,
 
889
  dout_padded = dout
890
  if head_size_og % 8 != 0:
891
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
892
+ _wrapped_flash_attn_backward(
893
  dout_padded,
894
  q,
895
  k,
 
937
  block_table,
938
  is_grad_enabled,
939
  ):
940
+ is_grad = is_grad_enabled and any(
941
+ x.requires_grad for x in [q, k, v]
942
+ )
943
  if softmax_scale is None:
944
  softmax_scale = q.shape[-1] ** (-0.5)
945
  head_size_og = q.size(2)
 
947
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
948
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
949
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
950
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward(
951
  q,
952
  k,
953
  v,
 
984
 
985
  @staticmethod
986
  def backward(ctx, dout, *args):
987
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors
 
 
988
  dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
989
  head_size_og = dout.size(2)
990
  dout_padded = dout
991
  if head_size_og % 8 != 0:
992
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
993
+ _wrapped_flash_attn_varlen_backward(
994
  dout_padded,
995
  q,
996
  k,
 
1017
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
1018
  dk = dk[..., : dout.shape[-1]]
1019
  dv = dv[..., : dout.shape[-1]]
1020
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1021
 
1022
 
1023
  def flash_attn_qkvpacked_func(
 
1165
  softmax_scale=None,
1166
  causal=False,
1167
  window_size=(-1, -1), # -1 means infinite context window
1168
+ softcap=0.0, # 0.0 means deactivated
1169
  alibi_slopes=None,
1170
  deterministic=False,
1171
  return_attn_probs=False,
 
1242
  softmax_scale=None,
1243
  causal=False,
1244
  window_size=(-1, -1), # -1 means infinite context window
1245
+ softcap=0.0, # 0.0 means deactivated
1246
  alibi_slopes=None,
1247
  deterministic=False,
1248
  return_attn_probs=False,
 
1311
  softmax_scale=None,
1312
  causal=False,
1313
  window_size=(-1, -1), # -1 means infinite context window
1314
+ softcap=0.0, # 0.0 means deactivated
1315
  alibi_slopes=None,
1316
  deterministic=False,
1317
  return_attn_probs=False,
 
1404
  softmax_scale=None,
1405
  causal=False,
1406
  window_size=(-1, -1), # -1 means infinite context window
1407
+ softcap=0.0, # 0.0 means deactivated
1408
  alibi_slopes=None,
1409
  deterministic=False,
1410
  return_attn_probs=False,
 
1501
  softmax_scale=None,
1502
  causal=False,
1503
  window_size=(-1, -1), # -1 means infinite context window
1504
+ softcap=0.0, # 0.0 means deactivated
1505
  rotary_interleaved=True,
1506
  alibi_slopes=None,
1507
  num_splits=0,
build/torch211-cxx11-cu126-aarch64-linux/layers/__init__.py ADDED
File without changes
build/torch211-cxx11-cu126-aarch64-linux/layers/patch_embed.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # We use the same API as https://github.com/rwightman/pytorch-image-models/blob/v0.6.11/timm/models/layers/patch_embed.py
2
+ # But we use nn.Linear instead of Conv2d and it's about 8x faster.
3
+
4
+ from functools import partial
5
+
6
+ import torch.nn as nn
7
+ from einops import rearrange
8
+ from torch import _assert
9
+ from torch.nn.modules.utils import _pair
10
+
11
+ try:
12
+ from flash_attn.ops.fused_dense import FusedDense
13
+ except ImportError:
14
+ FusedDense = None
15
+
16
+
17
+ class PatchEmbed(nn.Module):
18
+ """2D Image to Patch Embedding"""
19
+
20
+ def __init__(
21
+ self,
22
+ img_size=224,
23
+ patch_size=16,
24
+ in_chans=3,
25
+ embed_dim=768,
26
+ norm_layer=None,
27
+ flatten=True,
28
+ bias=True,
29
+ fused_bias_fc=False,
30
+ ):
31
+ super().__init__()
32
+ img_size = _pair(img_size)
33
+ patch_size = _pair(patch_size)
34
+ self.img_size = img_size
35
+ self.patch_size = patch_size
36
+ self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
37
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
38
+ self.flatten = flatten
39
+ if fused_bias_fc and FusedDense is None:
40
+ raise ImportError("fused_dense is not installed")
41
+
42
+ linear_cls = nn.Linear if not fused_bias_fc or not bias else FusedDense
43
+ self.proj = linear_cls(in_chans * patch_size[0] * patch_size[1], embed_dim, bias=bias)
44
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
45
+
46
+ def forward(self, x):
47
+ _, _, H, W = x.shape
48
+ _assert(
49
+ H == self.img_size[0],
50
+ f"Input image height ({H}) doesn't match model ({self.img_size[0]}).",
51
+ )
52
+ _assert(
53
+ W == self.img_size[1],
54
+ f"Input image width ({W}) doesn't match model ({self.img_size[1]}).",
55
+ )
56
+ x = self.proj(
57
+ rearrange(
58
+ x,
59
+ "b c (h p1) (w p2) -> b h w (c p1 p2)",
60
+ p1=self.patch_size[0],
61
+ p2=self.patch_size[1],
62
+ )
63
+ )
64
+ if self.flatten:
65
+ x = rearrange(x, "b h w c -> b (h w) c")
66
+ x = self.norm(x)
67
+ return x
build/torch211-cxx11-cu126-aarch64-linux/layers/rotary.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, Tri Dao
2
+
3
+ import math
4
+ from functools import partial
5
+ from typing import Optional, Tuple, Union
6
+
7
+ import torch
8
+ from torch import Tensor
9
+
10
+ from einops import rearrange, repeat
11
+ # from flash_attn.ops.triton.rotary import apply_rotary
12
+ from ..ops.triton.rotary import apply_rotary
13
+
14
+
15
+ def rotate_half(x, interleaved=False):
16
+ if not interleaved:
17
+ x1, x2 = x.chunk(2, dim=-1)
18
+ return torch.cat((-x2, x1), dim=-1)
19
+ else:
20
+ x1, x2 = x[..., ::2], x[..., 1::2]
21
+ return rearrange(torch.stack((-x2, x1), dim=-1), "... d two -> ... (d two)", two=2)
22
+
23
+
24
+ def apply_rotary_emb_torch(x, cos, sin, interleaved=False):
25
+ """
26
+ x: (batch_size, seqlen, nheads, headdim)
27
+ cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2)
28
+ """
29
+ ro_dim = cos.shape[-1] * 2
30
+ assert ro_dim <= x.shape[-1]
31
+ cos = repeat(cos, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
32
+ sin = repeat(sin, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
33
+ return torch.cat(
34
+ [x[..., :ro_dim] * cos + rotate_half(x[..., :ro_dim], interleaved) * sin, x[..., ro_dim:]],
35
+ dim=-1,
36
+ )
37
+
38
+
39
+ class ApplyRotaryEmb(torch.autograd.Function):
40
+ @staticmethod
41
+ def forward(
42
+ ctx,
43
+ x,
44
+ cos,
45
+ sin,
46
+ interleaved=False,
47
+ inplace=False,
48
+ seqlen_offsets: Union[int, Tensor] = 0,
49
+ cu_seqlens: Optional[Tensor] = None,
50
+ max_seqlen: Optional[int] = None,
51
+ ):
52
+ out = apply_rotary(
53
+ x,
54
+ cos,
55
+ sin,
56
+ seqlen_offsets=seqlen_offsets,
57
+ cu_seqlens=cu_seqlens,
58
+ max_seqlen=max_seqlen,
59
+ interleaved=interleaved,
60
+ inplace=inplace,
61
+ )
62
+ if isinstance(seqlen_offsets, int):
63
+ ctx.save_for_backward(cos, sin, cu_seqlens) # Can't save int with save_for_backward
64
+ ctx.seqlen_offsets = seqlen_offsets
65
+ else:
66
+ ctx.save_for_backward(cos, sin, cu_seqlens, seqlen_offsets)
67
+ ctx.seqlen_offsets = None
68
+ ctx.interleaved = interleaved
69
+ ctx.inplace = inplace
70
+ ctx.max_seqlen = max_seqlen
71
+ return out if not inplace else x
72
+
73
+ @staticmethod
74
+ def backward(ctx, do):
75
+ seqlen_offsets = ctx.seqlen_offsets
76
+ if seqlen_offsets is None:
77
+ cos, sin, cu_seqlens, seqlen_offsets = ctx.saved_tensors
78
+ else:
79
+ cos, sin, cu_seqlens = ctx.saved_tensors
80
+ dx = apply_rotary(
81
+ do,
82
+ cos,
83
+ sin,
84
+ seqlen_offsets=seqlen_offsets,
85
+ cu_seqlens=cu_seqlens,
86
+ max_seqlen=ctx.max_seqlen,
87
+ interleaved=ctx.interleaved,
88
+ inplace=ctx.inplace,
89
+ conjugate=True,
90
+ )
91
+ return dx, None, None, None, None, None, None, None
92
+
93
+
94
+ def apply_rotary_emb(
95
+ x,
96
+ cos,
97
+ sin,
98
+ interleaved=False,
99
+ inplace=False,
100
+ seqlen_offsets: Union[int, Tensor] = 0,
101
+ cu_seqlens: Optional[Tensor] = None,
102
+ max_seqlen: Optional[int] = None,
103
+ ):
104
+ """
105
+ Arguments:
106
+ x: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None
107
+ else (total_seqlen, nheads, headdim)
108
+ cos, sin: (seqlen_rotary, rotary_dim / 2)
109
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
110
+ of 1st half and 2nd half (GPT-NeoX style).
111
+ inplace: if True, apply rotary embedding in-place.
112
+ seqlen_offsets: (batch_size,) or int. Each sequence in x is shifted by this amount.
113
+ Most commonly used in inference when we have KV cache.
114
+ cu_seqlens: (batch + 1,) or None
115
+ max_seqlen: int
116
+ Return:
117
+ out: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None
118
+ else (total_seqlen, nheads, headdim)
119
+ rotary_dim must be <= headdim
120
+ Apply rotary embedding to the first rotary_dim of x.
121
+ """
122
+ return ApplyRotaryEmb.apply(
123
+ x, cos, sin, interleaved, inplace, seqlen_offsets, cu_seqlens, max_seqlen
124
+ )
125
+
126
+
127
+ # For backward compatibility
128
+ apply_rotary_emb_func = apply_rotary_emb
129
+
130
+
131
+ def _apply_rotary_emb_qkv(
132
+ qkv,
133
+ cos,
134
+ sin,
135
+ cos_k=None,
136
+ sin_k=None,
137
+ interleaved=False,
138
+ inplace=False,
139
+ conjugate=False,
140
+ seqlen_offsets: Union[int, Tensor] = 0,
141
+ num_heads_q: Optional[int] = None,
142
+ ):
143
+ apply_rotary_fn = partial(
144
+ apply_rotary,
145
+ interleaved=interleaved,
146
+ inplace=inplace,
147
+ conjugate=conjugate,
148
+ seqlen_offsets=seqlen_offsets
149
+ )
150
+ if cos_k is None and sin_k is None and qkv.is_contiguous():
151
+ # Call 1 kernel instead of 2 kernels
152
+ # We need qkv to be contiguous so that when we reshape to combine (3, nheads)
153
+ # dimensions, we get the same tensor
154
+ if qkv.dim() == 5:
155
+ batch, seqlen, three, nheads, headdim = qkv.shape
156
+ assert three == 3
157
+ # qk = rearrange(qkv[:, :, :2], "b s t h d -> b s (t h) d")
158
+ qk = qkv[:, :, :2].reshape(batch, seqlen, -1, headdim)
159
+ qk = apply_rotary_fn(qk, cos, sin)
160
+ else:
161
+ assert qkv.dim() == 4
162
+ assert num_heads_q is not None
163
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
164
+ assert qkv.shape[2] == num_heads_q + 2 * num_heads_k
165
+ qk = qkv[:, :, :num_heads_q + num_heads_k]
166
+ qk = apply_rotary_fn(qk, cos, sin)
167
+ if not inplace:
168
+ if qkv.dim() == 5:
169
+ qkv = torch.cat([rearrange(qk, "b s (t h) d -> b s t h d", t=2), qkv[:, :, 2:]], dim=2)
170
+ else:
171
+ qkv = torch.cat([qk, qkv[:, :, num_heads_q + num_heads_k :]], dim=2)
172
+ else:
173
+ cos_k = cos if cos_k is None else cos_k
174
+ sin_k = sin if sin_k is None else sin_k
175
+ if qkv.dim() == 5:
176
+ batch, seqlen, three, nheads, headdim = qkv.shape
177
+ assert three == 3
178
+ q, k = qkv[:, :, 0], qkv[:, :, 1]
179
+ else:
180
+ assert qkv.dim() == 4
181
+ assert num_heads_q is not None
182
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
183
+ assert qkv.shape[2] == num_heads_q + 2 * num_heads_k
184
+ q, k = qkv[:, :, :num_heads_q], qkv[:, :, num_heads_q : num_heads_q + num_heads_k]
185
+ q = apply_rotary_fn(q, cos, sin)
186
+ k = apply_rotary_fn(k, cos_k, sin_k)
187
+ if not inplace:
188
+ if qkv.dim() == 5:
189
+ qkv = torch.stack([q, k, qkv[:, :, 2]], dim=2)
190
+ else:
191
+ qkv = torch.cat([q, k, qkv[:, :, num_heads_q + num_heads_k:]], dim=2)
192
+ return qkv
193
+
194
+
195
+ class ApplyRotaryEmbQKV_(torch.autograd.Function):
196
+ @staticmethod
197
+ def forward(
198
+ ctx,
199
+ qkv,
200
+ cos,
201
+ sin,
202
+ cos_k=None,
203
+ sin_k=None,
204
+ interleaved=False,
205
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
206
+ num_heads_q: Optional[int] = None,
207
+ ):
208
+ # apply_rotary_emb_qkv_inplace(
209
+ qkv = _apply_rotary_emb_qkv(
210
+ qkv, cos, sin, cos_k, sin_k, interleaved=interleaved, inplace=True,
211
+ seqlen_offsets=seqlen_offsets, num_heads_q=num_heads_q,
212
+ )
213
+ if isinstance(seqlen_offsets, int):
214
+ ctx.save_for_backward(cos, sin, cos_k, sin_k)
215
+ ctx.seqlen_offsets = seqlen_offsets
216
+ else:
217
+ ctx.save_for_backward(cos, sin, cos_k, sin_k, seqlen_offsets)
218
+ ctx.seqlen_offsets = None
219
+ ctx.interleaved = interleaved
220
+ ctx.num_heads_q = num_heads_q
221
+ return qkv
222
+
223
+ @staticmethod
224
+ def backward(ctx, dqkv):
225
+ seqlen_offsets = ctx.seqlen_offsets
226
+ if seqlen_offsets is None:
227
+ cos, sin, cos_k, sin_k, seqlen_offsets = ctx.saved_tensors
228
+ else:
229
+ cos, sin, cos_k, sin_k = ctx.saved_tensors
230
+ dqkv = _apply_rotary_emb_qkv(
231
+ dqkv, cos, sin, cos_k, sin_k, interleaved=ctx.interleaved, inplace=True,
232
+ seqlen_offsets=seqlen_offsets, num_heads_q=ctx.num_heads_q, conjugate=True,
233
+ )
234
+ return dqkv, None, None, None, None, None, None, None
235
+
236
+
237
+ def apply_rotary_emb_qkv_(
238
+ qkv,
239
+ cos,
240
+ sin,
241
+ cos_k=None,
242
+ sin_k=None,
243
+ interleaved=False,
244
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
245
+ num_heads_q: Optional[int] = None,
246
+ ):
247
+ """
248
+ Arguments:
249
+ qkv: (batch_size, seqlen, 3, nheads, headdim) or (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim).
250
+ If qkv has shape (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim) (e.g. MQA / GQA),
251
+ then num_heads_q must be provided.
252
+ cos, sin: (seqlen, rotary_dim / 2)
253
+ cos_k, sin_k: (seqlen, rotary_dim / 2), optional
254
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of
255
+ 1st half and 2nd half (GPT-NeoX style).
256
+ seqlen_offsets: (batch_size,) or int. Each sequence in Q and K is shifted by this amount.
257
+ Most commonly used in inference when we have KV cache.
258
+ Return:
259
+ qkv: (batch_size, seqlen, 3, nheads, headdim) or (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim)
260
+ rotary_dim must be <= headdim
261
+ Apply rotary embedding *inplace* to the first rotary_dim of Q and K.
262
+ """
263
+ return ApplyRotaryEmbQKV_.apply(
264
+ qkv, cos, sin, cos_k, sin_k, interleaved, seqlen_offsets, num_heads_q
265
+ )
266
+
267
+
268
+ class ApplyRotaryEmbKV_(torch.autograd.Function):
269
+
270
+ @staticmethod
271
+ def forward(ctx, kv, cos, sin, interleaved=False, seqlen_offsets: Union[int, torch.Tensor] = 0):
272
+ batch, seqlen, two, nheads, headdim = kv.shape
273
+ assert two == 2
274
+ k = kv[:, :, 0]
275
+ apply_rotary(
276
+ k, cos, sin, seqlen_offsets=seqlen_offsets, interleaved=interleaved, inplace=True
277
+ )
278
+ if isinstance(seqlen_offsets, int):
279
+ ctx.save_for_backward(cos, sin) # Can't save int with save_for_backward
280
+ ctx.seqlen_offsets = seqlen_offsets
281
+ else:
282
+ ctx.save_for_backward(cos, sin, seqlen_offsets)
283
+ ctx.seqlen_offsets = None
284
+ ctx.interleaved = interleaved
285
+ return kv
286
+
287
+ @staticmethod
288
+ def backward(ctx, dkv):
289
+ seqlen_offsets = ctx.seqlen_offsets
290
+ if seqlen_offsets is None:
291
+ cos, sin, seqlen_offsets = ctx.saved_tensors
292
+ else:
293
+ cos, sin = ctx.saved_tensors
294
+ apply_rotary(
295
+ dkv[:, :, 0],
296
+ cos,
297
+ sin,
298
+ seqlen_offsets=seqlen_offsets,
299
+ interleaved=ctx.interleaved,
300
+ inplace=True,
301
+ conjugate=True,
302
+ )
303
+ return dkv, None, None, None, None
304
+
305
+
306
+ apply_rotary_emb_kv_ = ApplyRotaryEmbKV_.apply
307
+
308
+
309
+ def apply_rotary_emb_kv_(
310
+ kv,
311
+ cos,
312
+ sin,
313
+ interleaved=False,
314
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
315
+ ):
316
+ """
317
+ Arguments:
318
+ kv: (batch_size, seqlen, 2, nheads, headdim)
319
+ cos, sin: (seqlen, rotary_dim / 2)
320
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of
321
+ 1st half and 2nd half (GPT-NeoX style).
322
+ seqlen_offsets: (batch_size,) or int. Each sequence in Q and K is shifted by this amount.
323
+ Most commonly used in inference when we have KV cache.
324
+ Return:
325
+ kv: (batch_size, seqlen, 2, nheads, headdim)
326
+ rotary_dim must be <= headdim
327
+ Apply rotary embedding *inplace* to the first rotary_dim of K.
328
+ """
329
+ return ApplyRotaryEmbKV_.apply(kv, cos, sin, interleaved, seqlen_offsets)
330
+
331
+
332
+ class RotaryEmbedding(torch.nn.Module):
333
+ """
334
+ The rotary position embeddings from RoFormer_ (Su et. al).
335
+ A crucial insight from the method is that the query and keys are
336
+ transformed by rotation matrices which depend on the relative positions.
337
+
338
+ Other implementations are available in the Rotary Transformer repo_ and in
339
+ GPT-NeoX_, GPT-NeoX was an inspiration
340
+
341
+ .. _RoFormer: https://arxiv.org/abs/2104.09864
342
+ .. _repo: https://github.com/ZhuiyiTechnology/roformer
343
+ .. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox
344
+
345
+ If scale_base is not None, this implements XPos (Sun et al., https://arxiv.org/abs/2212.10554).
346
+ A recommended value for scale_base is 512: https://github.com/HazyResearch/flash-attention/issues/96
347
+ Reference: https://github.com/sunyt32/torchscale/blob/main/torchscale/component/xpos_relative_position.py
348
+ """
349
+
350
+ def __init__(
351
+ self,
352
+ dim: int,
353
+ base=10000.0,
354
+ interleaved=False,
355
+ scale_base=None,
356
+ device=None,
357
+ ):
358
+ """
359
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
360
+ of 1st half and 2nd half (GPT-NeoX style).
361
+ """
362
+ super().__init__()
363
+ self.dim = dim
364
+ self.base = float(base)
365
+ # Generate and save the inverse frequency buffer (non trainable)
366
+ inv_freq = self._compute_inv_freq(device)
367
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
368
+ self.interleaved = interleaved
369
+ self.scale_base = scale_base
370
+ scale = (
371
+ (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim)
372
+ if scale_base is not None
373
+ else None
374
+ )
375
+ self.register_buffer("scale", scale, persistent=False)
376
+
377
+ self._seq_len_cached = 0
378
+ self._cos_cached = None
379
+ self._sin_cached = None
380
+ self._cos_k_cached = None
381
+ self._sin_k_cached = None
382
+
383
+ def _compute_inv_freq(self, device=None):
384
+ return 1.0 / (
385
+ self.base
386
+ ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim)
387
+ )
388
+
389
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
390
+ # Reset the tables if the sequence length has changed,
391
+ # if we're on a new device (possibly due to tracing for instance),
392
+ # or if we're switching from inference mode to training
393
+ if (
394
+ seqlen > self._seq_len_cached
395
+ or self._cos_cached is None
396
+ or self._cos_cached.device != device
397
+ or self._cos_cached.dtype != dtype
398
+ or (self.training and self._cos_cached.is_inference())
399
+ ):
400
+ self._seq_len_cached = seqlen
401
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
402
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
403
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
404
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
405
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
406
+ # cos & sin output to change significantly.
407
+ # We want to recompute self.inv_freq if it was not loaded in fp32
408
+ if self.inv_freq.dtype != torch.float32:
409
+ inv_freq = self._compute_inv_freq(device=device)
410
+ else:
411
+ inv_freq = self.inv_freq
412
+ # Don't do einsum, it converts fp32 to bf16 under AMP
413
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
414
+ freqs = torch.outer(t, inv_freq)
415
+ if self.scale is None:
416
+ self._cos_cached = torch.cos(freqs).to(dtype)
417
+ self._sin_cached = torch.sin(freqs).to(dtype)
418
+ else:
419
+ power = (
420
+ torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device)
421
+ - seqlen // 2
422
+ ) / self.scale_base
423
+ scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
424
+ # We want the multiplication by scale to happen in fp32
425
+ self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
426
+ self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
427
+ self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
428
+ self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
429
+
430
+ def forward(
431
+ self,
432
+ qkv: torch.Tensor,
433
+ kv: Optional[torch.Tensor] = None,
434
+ seqlen_offset: Union[int, torch.Tensor] = 0,
435
+ max_seqlen: Optional[int] = None,
436
+ num_heads_q: Optional[int] = None,
437
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
438
+ """
439
+ qkv: (batch, seqlen, 3, nheads, headdim) or (batch, seqlen, num_heads_q + 2 * num_heads_k, headdim)
440
+ if kv is none, else it's just q of shape (batch, seqlen, nheads, headdim).
441
+ If qkv has shape (batch, seqlen, num_heads_q + 2 * num_heads_k, headdim) (e.g. MQA / GQA),
442
+ then num_heads_q must be provided.
443
+ kv: (batch, seqlen, 2, nheads, headdim)
444
+ seqlen_offset: (batch_size,) or int. Each sequence in x is shifted by this amount.
445
+ Most commonly used in inference when we have KV cache.
446
+ If it's a tensor of shape (batch_size,), then to update the cos / sin cache, one
447
+ should pass in max_seqlen, which will update the cos / sin cache up to that length.
448
+ Apply rotary embedding *inplace* to qkv and / or kv.
449
+ """
450
+ seqlen = qkv.shape[1]
451
+ if max_seqlen is not None:
452
+ self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype)
453
+ elif isinstance(seqlen_offset, int):
454
+ self._update_cos_sin_cache(seqlen + seqlen_offset, device=qkv.device, dtype=qkv.dtype)
455
+ if kv is None:
456
+ return apply_rotary_emb_qkv_(
457
+ qkv,
458
+ self._cos_cached,
459
+ self._sin_cached,
460
+ self._cos_k_cached if self.scale is not None else None,
461
+ self._sin_k_cached if self.scale is not None else None,
462
+ interleaved=self.interleaved,
463
+ seqlen_offsets=seqlen_offset,
464
+ num_heads_q=num_heads_q,
465
+ )
466
+ else:
467
+ q = qkv
468
+ q = apply_rotary_emb_func(
469
+ q,
470
+ self._cos_cached,
471
+ self._sin_cached,
472
+ interleaved=self.interleaved,
473
+ inplace=True,
474
+ seqlen_offsets=seqlen_offset,
475
+ )
476
+ kv = apply_rotary_emb_kv_(
477
+ kv,
478
+ self._cos_cached if self.scale is None else self._cos_k_cached,
479
+ self._sin_cached if self.scale is None else self._sin_k_cached,
480
+ interleaved=self.interleaved,
481
+ seqlen_offsets=seqlen_offset,
482
+ )
483
+ return q, kv
build/torch211-cxx11-cu126-aarch64-linux/metadata.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "name": "flash-attn2",
3
- "id": "_flash_attn2_cuda_a511a4c",
4
  "version": 1,
5
  "license": "BSD-3-Clause",
6
  "python-depends": [],
@@ -14,12 +14,27 @@
14
  "digest": {
15
  "algorithm": "sha256",
16
  "files": {
17
- "__init__.py": "pbZ3riEB3GTIymdTvC7023ydYDWalnxEy+Lq0DGeZoQ=",
18
- "_flash_attn2_cuda_a511a4c.abi3.so": "YfgCQWwMNxM7Prlh47a18IR41cIaOqidYGrYlEPfj8s=",
19
- "_ops.py": "ceg+0r4TQ9sSFsTUNrdsGNcrceyYp1uw3N5C3bS/Q/Y=",
20
  "bert_padding.py": "gF1EmsdJ+HpQ86MRQ4VxDw+Sb/RVISdQALdNnoByHlw=",
21
  "flash_attn2/__init__.py": "DFYPlrhXwYjEqCl/8n0SmWGZV8NFml5DPhMjKfv98GY=",
22
- "flash_attn_interface.py": "pJrnUxC+7qEqFh1C1YbjYggC9FfoG3dblU+XlwaJkEs="
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  }
24
  }
25
  }
 
1
  {
2
  "name": "flash-attn2",
3
+ "id": "_flash_attn2_cuda_f12afc9",
4
  "version": 1,
5
  "license": "BSD-3-Clause",
6
  "python-depends": [],
 
14
  "digest": {
15
  "algorithm": "sha256",
16
  "files": {
17
+ "__init__.py": "Cd9MEdd/WUYnBmfiQpC4SyPqAxrTilTjvsvswNju4zc=",
18
+ "_flash_attn2_cuda_f12afc9.abi3.so": "2XI68H/Bmhg6MsJZwgPWBiN5ur8QcFJ9pWdL4WYKBi0=",
19
+ "_ops.py": "GQbmTTeSOU+7Q2nI68Hz+1RvEogyfEFccx1ubUYw+2s=",
20
  "bert_padding.py": "gF1EmsdJ+HpQ86MRQ4VxDw+Sb/RVISdQALdNnoByHlw=",
21
  "flash_attn2/__init__.py": "DFYPlrhXwYjEqCl/8n0SmWGZV8NFml5DPhMjKfv98GY=",
22
+ "flash_attn_interface.py": "W7a9bHR2ly6QL3aKqsBqxWA7M7ZWYcZPmtsPJu6rAfY=",
23
+ "layers/__init__.py": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",
24
+ "layers/patch_embed.py": "H58CgME/qSOPTZLOG08wFgrQS1j34pvNwMPrkTj3Ek4=",
25
+ "layers/rotary.py": "rFIdNrZQFNawwLD6d7t5LE2m+M93wwDZ8EuExw+gfD8=",
26
+ "ops/__init__.py": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",
27
+ "ops/activations.py": "t5lzNg1In8LP6bKeTnyeMizwqjv27JGbJ6ylPdGvZYg=",
28
+ "ops/fused_dense.py": "BqT8VTSCGdLJAjh6WBMkCRFYrdVodPeoElWBvH6AIzA=",
29
+ "ops/layer_norm.py": "zr7NXIm+2mtEynTp1CS0fbFGI2Mqdp41dY4AfDWF6EQ=",
30
+ "ops/rms_norm.py": "XEnihcj0a4aSz4LO55m5iKGVn4HKTeKN8TIyHjuDgxI=",
31
+ "ops/triton/__init__.py": "AbpHGcgLb+kRsJGnwFEktk7uzpZOCcBY74+YBdrKVGs=",
32
+ "ops/triton/cross_entropy.py": "y56nmuOtpSNxM7sDZcUSgXKIsIEayfuvrU8bAVog/nw=",
33
+ "ops/triton/k_activations.py": "+Z3vIyO4JkqBMipKsPvhzmxljtBdIhJCsl/M+/ESqBo=",
34
+ "ops/triton/layer_norm.py": "BBQdJiqopbIS12viUqzx3SvOQCNbDSAYLJXhpyMGyC8=",
35
+ "ops/triton/linear.py": "OtRvKz8xdpl+7v3q/ZTaS9fdBt9XrzMyapgRr50uBbM=",
36
+ "ops/triton/mlp.py": "uWA+D7HyuRUsOT+4nhi3vvCDNZnNEXwYcHMQ02UREfQ=",
37
+ "ops/triton/rotary.py": "0YSrlbep0lJmzLpTiANs0slTFeGcQQqR+el6uzbSLvI="
38
  }
39
  }
40
  }
build/torch211-cxx11-cu126-aarch64-linux/metadata.json.sigstore CHANGED
@@ -1 +1 @@
1
- {"mediaType":"application/vnd.dev.sigstore.bundle.v0.3+json","verificationMaterial":{"certificate":{"rawBytes":"MIIHcjCCBvigAwIBAgIUXKs0cwrF4ZTAx8F1hBUkCvowKUMwCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjYwNjE4MDY1MzMyWhcNMjYwNjE4MDcwMzMyWjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DA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EAVY/dvh9e/pl7qjAiBXqcSOGIGc8Ng9LVkF1iUb70IgHIca06bqn3qNtcCzeDAKBggqhkjOPQQDAwNoADBlAjEAnAKgfvY73om+150aVaaZXhuuYobNUtSwcLAs1bTfMcXw8hjAC+NPo/FRPlMtXbbfAjACzdPgpEXHsBQZSMxKrw7vKfMxtN+XXoVA53da4GyGEIRAklqJ7+l1l7N8tOaN+As="},"tlogEntries":[{"logIndex":"1857831639","logId":{"keyId":"wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0="},"kindVersion":{"kind":"hashedrekord","version":"0.0.1"},"integratedTime":"1781765612","inclusionPromise":{"signedEntryTimestamp":"MEYCIQDnZYXz/yngjlRUQji7Wd4yKdKLMRavNGhmKo0LubXz8QIhAIbsa6WlKoC2x2xy9JAMnPsn46Ni1JxsQUEjRxpJeYHX"},"inclusionProof":{"logIndex":"1735927377","rootHash":"aTbCoW81qGTPkCgKKUz7fXB/f/5f9DWFKFmEuo4sB74=","treeSize":"1735927384","hashes":["Io0cbWpEsKL39ZhRQRsLXxJrqbkKfqBBH+CHPuIW5vk=","0rIFOjIyuqLkiod9uh6tspD7u0fMSFKjdzu1SBnqz7Y=","Q0ssxe91hU6ieguvCre3lxNEfvgdrQyRyxSFqp9duNo=","LxAO3U9hr/0G/JoIjnLvycdDQArMMUeV+lj5ZGmgO9s=","US9y2TV6adthwvziznjMl+gEQG5s+rbatF7c0kgSHZg=","YdEOvKbYyUAJqT2KPfx3vRDhtULM3xxmOmlGzZ0R0Vk=","rToNJB/Z/GC9W3boPPGK1mkXX5gOF5sDf7GymqWFiRo=","Ore1A2Ceavap3m5U3ZAHLkUinE8F4IgttCeJDxxaK98=","95goX8Iw4H4P6V4eHvRqTdVdViLbhEhsF6i7ICnz/+A=","sWDh7SjDHbJf3HWKGRxiURh6iIYrOzn4Zs37yIij6OA=","x7kXd4VRJvVmTHoSla2KyPQdKvGKDX26/7ST9OONR78=","U8wMiVDzFlmyqT7Nw1RSZYU9+fftsSkRhjpbyXnXUk8=","mqM7J+i75IpuD09QejiUBjeH85AZa+fSm4RXXFmj3lI=","72FC5FYLhxB4a4iiC956o0B/fT54ip4R41vsw2QBKtU=","lYGQ9ibwC8+smMkPQ6TchJm3H9Nc/aTYLfdRacGFChw=","daxmZaajRpZV+JxHiOYZhJBiSKN5ucqjh2WnGbHhirw=","DOCeoSMovIvLExkhIvisow9AuNXgeWs4ECkyR6EcqYU="],"checkpoint":{"envelope":"rekor.sigstore.dev - 1193050959916656506\n1735927384\naTbCoW81qGTPkCgKKUz7fXB/f/5f9DWFKFmEuo4sB74=\n\n— rekor.sigstore.dev wNI9ajBFAiEAycMdZrSuQAk1iglklX3Ry+bWQtbqUNkDWU4fuve8WDUCIBevb8Go8ebI2NAcS6ua72l0+4RzNx5DQ3l9K1CNvcUK\n"}},"canonicalizedBody":"eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiIzZjcyZGNhZjUyM2Y4MWE5ZDJjNWUxYWZlZGVhM2Q0Yzc1ZmM1YTBjN2NmMjkzOWFiNThhNzE2NWQ5NDQxMzk3In19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FUUNJQ3EyTVBNOE1DZjZVbDBWQkNMTlQvYVBRSW1yUmIwajlBREdpbFhVc0MvL0FpQU1ybmhrL3hvUHVoaWw1ZUNYcUcrZ3ZQYmltYW5aNFQrOUNQd1lmbE9FeEE9PSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaGpha05EUW5acFowRjNTVUpCWjBsVldFdHpNR04zY2tZMFdsUkJlRGhHTVdoQ1ZXdERkbTkzUzFWTmQwTm5XVWxMYjFwSmVtb3dSVUYzVFhjS1RucEZWazFDVFVkQk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EgMB4GA1UEAxMXc2lnc3RvcmUtdHNhLXNlbGZzaWduZWQCFDoTVC8MkGHuvMFDL8uKjosqI4sMMAoGCCqGSM49BAMCBGcwZQIwCvn1NibNGr13K+pgpYSm6Xo//kl10bX5RaQ2l1/rOzHYi9JmS+QELtRxIAliDt0AAjEAo6pD+CDxL1lMGYGVHcawTU4xgyRGXHuAEkw0F3TWg2ENwQ8i7TiQdMNUUEuhvFhz"}]}},"messageSignature":{"messageDigest":{"algorithm":"SHA2_256","digest":"P3Lcr1I/ganSxeGv7eo9THX8Wgx88pOatYpxZdlEE5c="},"signature":"MEQCICq2MPM8MCf6Ul0VBCLNT/aPQImrRb0j9ADGilXUsC//AiAMrnhk/xoPuhil5eCXqG+gvPbimanZ4T+9CPwYflOExA=="}}
 
1
+ {"mediaType":"application/vnd.dev.sigstore.bundle.v0.3+json", "verificationMaterial":{"certificate":{"rawBytes":"MIIHSzCCBtGgAwIBAgIUJlLjauFMKjms/QQ19SyEeSB1jkgwCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjYwNjIzMjM0MDQxWhcNMjYwNjIzMjM1MDQxWjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuFBckUQX2LJelzPlwWFzy0lnA9zDRmyqtLy/fUMQKRyLtLaMNSOoo5gdSecr8DFIYHoqlKjnhnTs9MvVO98oxqOCBfAwggXsMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQUwPqgjtdu0npnzjDDzPfz6h3Y5C0wHwYDVR0jBBgwFoAU39Ppz1YkEZb5qNjpKFWixi4YZD8wawYDVR0RAQH/BGEwX4ZdaHR0cHM6Ly9naXRodWIuY29tL2h1Z2dpbmdmYWNlL2tlcm5lbHMtY29tbXVuaXR5Ly5naXRodWIvd29ya2Zsb3dzL2J1aWxkLnlhb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dHBzOi8vZ2l0aHViLmNvbS9odWdnaW5nZmFjZS9rZXJuZWxzLWNvbW11bml0eS8uZ2l0aHViL3dvcmtmbG93cy9idWlsZC55YW1sQHJlZnMvaGVhZHMvbWFpbjA4BgorBgEEAYO/MAETBCoMKGYxMmFmYzkyYzQwYmJkNzZkOTkwZDkxMWViYWJmMjhlNDkwYTdiZGUwIQYKKwYBBAGDvzABFAQTDBF3b3JrZmxvd19kaXNwYXRjaDBkBgorBgEEAYO/MAEVBFYMVGh0dHBzOi8vZ2l0aHViLmNvbS9odWdnaW5nZmFjZS9rZXJuZWxzLWNvbW11bml0eS9hY3Rpb25zL3J1bnMvMjgwMzYyNjg5MzUvYXR0ZW1wdHMvMTAWBgorBgEEAYO/MAEWBAgMBnB1YmxpYzBGBgorBgEEAYO/MAEYBDgMNnJlcG86aHVnZ2luZ2ZhY2Uva2VybmVscy1jb21tdW5pdHk6cmVmOnJlZnMvaGVhZHMvbWFpbjCBigYKKwYBBAHWeQIEAgR8BHoAeAB2AN09MGrGxxEyYxkeHJlnNwKiSl643jyt/4eKcoAvKe6OAAABnvbbgoIAAAQDAEcwRQIhAOYOWmPPwM3fTrUeK0fxDUmkb6ixB+uE4EGIlS5oKBBMAiBL4OdVVh/aGGzoxr0BPO6DZdT6CS9eBJP8BnSUdTt+PTAKBggqhkjOPQQDAwNoADBlAjEAi+oJ2fgcTYEL8rz4gzQANH2pv9CHpMVJWohhcTjLafUyEHst/8OmuQEQtfgbK7yiAjAbDPjT+u4QwTND5V3HRwqmC/GhWkLZ7qV1E/28HumuMgT0DDgg5kTILc6HUfe/lJw="}, "tlogEntries":[{"logIndex":"1933039176", "logId":{"keyId":"wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0="}, "kindVersion":{"kind":"hashedrekord", "version":"0.0.1"}, "integratedTime":"1782258041", "inclusionPromise":{"signedEntryTimestamp":"MEQCIEGqYhETWYlrrpHn8IOTEiLMxfAAe87qzmifEA4avbjoAiAMgtovjtJbEVhUdpjCU+Lt7Rm4TWGoNc6pBpDuQfnFnA=="}, "inclusionProof":{"logIndex":"1811134914", "rootHash":"Mo7p6GAE5vbthsKoVzCojKgL3apqvnCxbAuZzbRuPw8=", "treeSize":"1811134952", "hashes":["33KfZUwDSwH+Qgiyxfv5ooCqUlniFxHBVg1gaHhz7MA=", "LFPGcrnZg0FRabKIK8AD7gW4T7PCbHMY9uXkE83Iy3s=", "7YWKL24QXf8cYhvp0nYHsCnSjY02E5DgshMTGOU39Us=", "ubpQsIzVu9AUVq79n2HxbZuD+7M13ePZ4evoMULnbtU=", "4E/ydT4+W1Xgc4SLmGHd0eycRru2QL2uAqD6hMSqQl8=", "F8ujUbuv7OJbS3b2sw6l5a6cXYBPLmnOWNsaZpOeGuQ=", "e7/f+3LhBuOUmGH8mumO7KvVYW9S3qvnmbhfgUHyhUE=", "mwifXGJ4nqgB69Yt0Pem54qGmK8yLlI1ACFo38BZRc4=", "LzjqkPhZa4hiR0fFtJfuePCkK1oRLVJSKEzhGvUZzIg=", "WD8KwmQq5R8K69koYj5k4K7EKo2VF3LqJcx2xoXcd7o=", "99JTcUz0aJeZZocenAppVOLl8v91qMn0v7CmEjq9lws=", "OSDrt6jTKV6LYAkaG63p2BFz4SmbNmGb3uerhF5pOpQ=", "yehxDZkBWOGIzNDb93qxmQa6VBVo7kacVSoHyXMm3ZI=", "oUh+N71k3jWcTmlDDB6Esa5uqlCnbmzxTmDdut2A16M=", "2BsqkdK2omLvu+CpsFjpwqGi6m22H/7zcwCVkPwslM8=", "S8Oe9ZicoJqbVuL1I0dIdTgVpLc82Cm2CMOcV83sKVs=", "E1O2ilWlpFRLWGdbmJUMDZ2qbGu/eDZ12m6YjQ9/JPA=", "nyv2TDlfkz0XfRwjY98zsbUbOkBZ+Tgz7PML0c2uN14=", "OMfDh4k9YD0E+t4sjqJsh+vg8D1ueo1cC07exyxmr6s=", "+vHKm4wNwGJ46ceyZ8mePD7Vn1SediStNHCStRoTSWQ=", "5HwWjuGNDisetbiWM0cWIXM65TIM3EJlqk13ntCQlcU=", "NDIRlqxO0IaGr94q86MIU7VCAN3yEEgOHS4loya5lu4=", "daxmZaajRpZV+JxHiOYZhJBiSKN5ucqjh2WnGbHhirw=", "DOCeoSMovIvLExkhIvisow9AuNXgeWs4ECkyR6EcqYU="], "checkpoint":{"envelope":"rekor.sigstore.dev - 1193050959916656506\n1811134952\nMo7p6GAE5vbthsKoVzCojKgL3apqvnCxbAuZzbRuPw8=\n\n— rekor.sigstore.dev wNI9ajBGAiEA+clLWbvNjUhVrnaMW3o3Dio+RWwnsX0m+7Hv/anh+dYCIQDduIUH8vyMexwCTOn/5hYtQXSCH4pxmtsJG4Aem+4cMA==\n"}}, "canonicalizedBody":"eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiJkYWI1MzY2ZDY0MDYyODZhOGJhNzMzNDFmYmZkYzBlNzYzNDBhNDM2ODAwNjNlY2E0ZTBjODQ4ZjFjZWI5YjIwIn19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FWUNJUURnSHdUS3VRVm1OV0grUHZZMEdLZWR4T3R1WGRQTHVYQnFWam1Qb2R1ZmNBSWhBSVdzK2xhcENuSmhrMmczcmpEWEhFd3B6RkdpWTk4eXpSNk1xYThxZW05QSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaFRla05EUW5SSFowRjNTVUpCWjBsVlNteE1hbUYxUmsxTGFtMXpMMUZSTVRsVGVVVmxVMEl4YW10bmQwTm5XVWxMYjFwSmVtb3dSVUYzVFhjS1RucEZWazFDVFVkQk1WVkZRMmhOVFdNeWJHNWpNMUoyWTIxVmRWcEhWakpOVWpSM1NFRlpSRlpSVVVSRmVGWjZZV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wGu3sXtS6q2Ia07WKSDQIwJ7SrctC3Fcjdm7XQWZTWpF0xxdRlXPgSL2Eicl/UeUPSM928SJaFxIbibPFUnhA9"}]}}, "messageSignature":{"messageDigest":{"algorithm":"SHA2_256", "digest":"2rU2bWQGKGqLpzNB+/3A52NApDaABj7KTgyEjxzrmyA="}, "signature":"MEYCIQDgHwTKuQVmNWH+PvY0GKedxOtuXdPLuXBqVjmPodufcAIhAIWs+lapCnJhk2g3rjDXHEwpzFGiY98yzR6Mqa8qem9A"}}
build/torch211-cxx11-cu126-aarch64-linux/ops/__init__.py ADDED
File without changes
build/torch211-cxx11-cu126-aarch64-linux/ops/activations.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/model/layers/activations.py
2
+ import math
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ # 1/sqrt(2*pi)-> 0.3989423
9
+ # 1/sqrt(2) -> 0.70710678
10
+ # sqrt(2/pi) -> 0.79788456
11
+
12
+ # this function is tanh approximation of gelu
13
+ # actual gelu is:
14
+ # x * 0.5 * (1.0 + torch.erf(x * 0.70710678))
15
+ @torch.jit.script
16
+ def bias_gelu(y, bias):
17
+ x = bias + y
18
+ return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=y.dtype)
19
+
20
+
21
+ # gradient of tanh approximation of gelu
22
+ # gradient of actual gelu is:
23
+ # 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x)
24
+ @torch.jit.script
25
+ def bias_gelu_back(g, y, bias):
26
+ """Assume that y has shape (B, D) and bias has shape (D)"""
27
+ x = bias + y
28
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
29
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
30
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (
31
+ 1 + tanh_out
32
+ )
33
+ grad_y = ff * g
34
+ return grad_y.to(dtype=y.dtype), grad_y.sum(dim=(0), dtype=bias.dtype)
35
+
36
+
37
+ class GeLUFunction(torch.autograd.Function):
38
+ @staticmethod
39
+ # bias is an optional argument
40
+ def forward(ctx, input, bias):
41
+ ctx.save_for_backward(input, bias)
42
+ return bias_gelu(input, bias)
43
+
44
+ @staticmethod
45
+ def backward(ctx, grad_output):
46
+ input, bias = ctx.saved_tensors
47
+ tmp = bias_gelu_back(grad_output, input, bias)
48
+ return tmp, tmp
49
+
50
+
51
+ bias_gelu_impl = GeLUFunction.apply
52
+
53
+ # this function is tanh approximation of gelu
54
+ # actual gelu is:
55
+ # x * 0.5 * (1.0 + torch.erf(x * 0.70710678))
56
+ @torch.jit.script
57
+ def gelu_fwd(x):
58
+ return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=x.dtype)
59
+
60
+
61
+ # gradient of tanh approximation of gelu
62
+ # gradient of actual gelu is:
63
+ # 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x)
64
+ @torch.jit.script
65
+ def gelu_bwd(g, x):
66
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
67
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
68
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (
69
+ 1 + tanh_out
70
+ )
71
+ return (ff * g).to(dtype=x.dtype)
72
+
73
+
74
+ class FastGeLUFunction(torch.autograd.Function):
75
+ @staticmethod
76
+ # bias is an optional argument
77
+ def forward(ctx, input):
78
+ ctx.save_for_backward(input)
79
+ return gelu_fwd(input)
80
+
81
+ @staticmethod
82
+ def backward(ctx, grad_output):
83
+ (input,) = ctx.saved_tensors
84
+ tmp = gelu_bwd(grad_output, input)
85
+ return tmp
86
+
87
+
88
+ fast_gelu_impl = FastGeLUFunction.apply
89
+
90
+
91
+ @torch.jit.script
92
+ def relu_bwd(g, x):
93
+ return torch.where(x >= 0, g, 0.0).to(dtype=x.dtype)
94
+
95
+
96
+ @torch.jit.script
97
+ def sqrelu_fwd(x):
98
+ r = F.relu(x)
99
+ return (r * r).to(dtype=x.dtype)
100
+
101
+
102
+ @torch.jit.script
103
+ def sqrelu_bwd(g, x):
104
+ return (2.0 * g * F.relu(x)).to(dtype=x.dtype)
105
+
106
+
107
+ swiglu_fwd_codestring = """
108
+ template <typename T> T swiglu_fwd(T x, T y) {
109
+ return float(x) * float(y) / (1.0f + ::exp(-float(x)));
110
+ }
111
+ """
112
+ swiglu_bwd_codestring = """
113
+ template <typename T> void swiglu_bwd(T x, T y, T g, T& dx, T& dy) {
114
+ float x_sigmoid = 1.0f / (1.0f + ::exp(-float(x)));
115
+ dx = x_sigmoid * (1 + float(x) * (1.0f - x_sigmoid)) * float(g) * float(y);
116
+ dy = float(x) * x_sigmoid * float(g);
117
+ }
118
+ """
119
+ swiglu_fwd = torch.cuda.jiterator._create_jit_fn(swiglu_fwd_codestring)
120
+ swiglu_bwd = torch.cuda.jiterator._create_multi_output_jit_fn(swiglu_bwd_codestring, num_outputs=2)
121
+
122
+
123
+ class SwiGLUFunction(torch.autograd.Function):
124
+
125
+ @staticmethod
126
+ def forward(ctx, x, y):
127
+ ctx.save_for_backward(x, y)
128
+ return swiglu_fwd(x, y)
129
+
130
+ @staticmethod
131
+ def backward(ctx, dout):
132
+ x, y = ctx.saved_tensors
133
+ return swiglu_bwd(x, y, dout)
134
+
135
+ swiglu = SwiGLUFunction.apply
build/torch211-cxx11-cu126-aarch64-linux/ops/fused_dense.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+ # Inspired by https://github.com/NVIDIA/apex/blob/master/apex/fused_dense/fused_dense.py
3
+ # We make it work with pytorch amp and with bfloat16.
4
+ # The TensorParallel linear modules are inspired by https://github.com/NVIDIA/apex/blob/master/apex/transformer/tensor_parallel/layers.py
5
+ from functools import partial
6
+ from typing import Optional
7
+
8
+ # import fused_dense_cuda # from apex
9
+ import fused_dense_lib as fused_dense_cuda
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ from torch import Tensor
14
+ from torch.distributed import ProcessGroup
15
+
16
+ from flash_attn.utils.torch import custom_fwd, custom_bwd
17
+ from flash_attn.ops.activations import gelu_bwd, relu_bwd, sqrelu_bwd, sqrelu_fwd
18
+ from flash_attn.utils.distributed import (
19
+ all_gather_raw,
20
+ all_reduce,
21
+ all_reduce_raw,
22
+ reduce_scatter,
23
+ reduce_scatter_raw,
24
+ )
25
+
26
+
27
+ class FusedDenseFunc(torch.autograd.Function):
28
+ @staticmethod
29
+ @custom_fwd
30
+ def forward(
31
+ ctx, x, weight, bias, return_residual=False, process_group=None, sequence_parallel=True
32
+ ):
33
+ """
34
+ If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel
35
+ with sequence parallelism: we do an all_gather_raw of x before doing the matmul.
36
+ """
37
+ ctx.compute_weight_gradient = weight.requires_grad
38
+ ctx.return_residual = return_residual
39
+ ctx.process_group = process_group
40
+ ctx.sequence_parallel = sequence_parallel
41
+
42
+ if torch.is_autocast_enabled():
43
+ x = x.to(dtype=torch.get_autocast_gpu_dtype())
44
+ x = x.contiguous()
45
+ if process_group is not None and sequence_parallel:
46
+ # We want to kick off the all_gather early, before weight dtype conversion
47
+ total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
48
+ else:
49
+ total_x = x
50
+
51
+ if torch.is_autocast_enabled():
52
+ weight = weight.to(dtype=torch.get_autocast_gpu_dtype())
53
+ bias = bias.to(dtype=torch.get_autocast_gpu_dtype()) if bias is not None else None
54
+ weight = weight.contiguous()
55
+ if process_group is not None and sequence_parallel:
56
+ handle_x.wait()
57
+ batch_shape, n = total_x.shape[:-1], total_x.shape[-1]
58
+ batch_dim = batch_shape.numel()
59
+ # https://github.com/pytorch/pytorch/blob/5b51849b48a7dbccd297286cc0110def4706f9e7/aten/src/ATen/native/cuda/Blas.cpp#L174
60
+ if min(batch_dim, n, *weight.shape) > 65535 * 32:
61
+ raise RuntimeError("fused_dense only supports matrix dims <= 2M")
62
+ output = F.linear(total_x, weight, bias)
63
+ if ctx.compute_weight_gradient:
64
+ ctx.save_for_backward(x, weight)
65
+ else:
66
+ ctx.save_for_backward(weight)
67
+ return output if not return_residual else (output, x)
68
+
69
+ @staticmethod
70
+ @custom_bwd
71
+ def backward(ctx, grad_output, *args):
72
+ grad_output = grad_output.contiguous()
73
+ if ctx.return_residual:
74
+ (grad_input,) = args
75
+ grad_input = grad_input.contiguous()
76
+ process_group = ctx.process_group
77
+ sequence_parallel = ctx.sequence_parallel
78
+ if ctx.compute_weight_gradient:
79
+ x, weight = ctx.saved_tensors
80
+ if process_group is not None and sequence_parallel:
81
+ total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
82
+ else:
83
+ total_x = x
84
+ else:
85
+ (weight,) = ctx.saved_tensors
86
+ total_x = None
87
+ batch_shape = grad_output.shape[:-1]
88
+ batch_dim = batch_shape.numel()
89
+ grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1])
90
+ if ctx.needs_input_grad[0]:
91
+ if not ctx.return_residual:
92
+ grad_input = F.linear(grad_output, weight.t())
93
+ else:
94
+ grad_input = torch.addmm(
95
+ grad_input.reshape(batch_dim, grad_input.shape[-1]), grad_output, weight
96
+ )
97
+ grad_input = grad_input.reshape(*batch_shape, grad_input.shape[-1])
98
+ if process_group is not None:
99
+ reduce_fn = reduce_scatter_raw if sequence_parallel else all_reduce_raw
100
+ grad_input, handle_grad_input = reduce_fn(grad_input, process_group, async_op=True)
101
+ else:
102
+ grad_input = None
103
+ if ctx.needs_input_grad[1]:
104
+ assert ctx.compute_weight_gradient
105
+ if process_group is not None and sequence_parallel:
106
+ handle_x.wait()
107
+ grad_weight, grad_bias = fused_dense_cuda.linear_bias_wgrad(
108
+ total_x.reshape(batch_dim, total_x.shape[-1]), grad_output, ctx.needs_input_grad[2]
109
+ )
110
+ else:
111
+ grad_weight = None
112
+ grad_bias = grad_output if ctx.needs_input_grad[2] else None
113
+ if process_group is not None and ctx.needs_input_grad[0]:
114
+ handle_grad_input.wait()
115
+ return grad_input, grad_weight, grad_bias, None, None, None
116
+
117
+
118
+ def fused_dense_func(
119
+ x: Tensor,
120
+ weight: Tensor,
121
+ bias: Optional[Tensor] = None,
122
+ return_residual: bool = False,
123
+ process_group: Optional[ProcessGroup] = None,
124
+ sequence_parallel: bool = True,
125
+ ):
126
+ dtype_eligible = x.dtype in [torch.float16, torch.bfloat16] or (
127
+ x.dtype == torch.float32 and torch.is_autocast_enabled()
128
+ )
129
+ if x.is_cuda and weight.is_cuda and (bias is None or bias.is_cuda) and dtype_eligible:
130
+ return FusedDenseFunc.apply(
131
+ x, weight, bias, return_residual, process_group, sequence_parallel
132
+ )
133
+ else:
134
+ assert process_group is None
135
+ out = F.linear(x, weight, bias)
136
+ return out if not return_residual else (out, x)
137
+
138
+
139
+ class FusedDense(nn.Linear):
140
+ def __init__(
141
+ self,
142
+ in_features: int,
143
+ out_features: int,
144
+ bias: bool = True,
145
+ return_residual: bool = False,
146
+ device=None,
147
+ dtype=None,
148
+ ) -> None:
149
+ super().__init__(in_features, out_features, bias=bias, device=device, dtype=dtype)
150
+ self.return_residual = return_residual
151
+
152
+ def forward(self, x, process_group=None):
153
+ """
154
+ If process_group is not None, we're doing Tensor Parallel with sequence parallelism:
155
+ we do an all_gather of x before doing the matmul.
156
+ """
157
+ return fused_dense_func(
158
+ x,
159
+ self.weight,
160
+ self.bias,
161
+ return_residual=self.return_residual,
162
+ process_group=process_group,
163
+ )
164
+
165
+
166
+ class ColumnParallelLinear(nn.Linear):
167
+ def __init__(
168
+ self,
169
+ in_features: int,
170
+ out_features: int,
171
+ process_group: ProcessGroup,
172
+ bias: bool = True,
173
+ sequence_parallel=True,
174
+ multiple_of=1,
175
+ device=None,
176
+ dtype=None,
177
+ ) -> None:
178
+ world_size = torch.distributed.get_world_size(process_group)
179
+ if out_features % multiple_of:
180
+ raise ValueError(f"out_features ({out_features}) must be a multiple of {multiple_of}")
181
+ multiple = out_features // multiple_of
182
+ # We want to split @multiple across world_size, but it could be an uneven split
183
+ div = multiple // world_size
184
+ mod = multiple % world_size
185
+ # The first @mod ranks get @div + 1 copies, the rest get @div copies
186
+ local_multiple = div + int(torch.distributed.get_rank(process_group) < mod)
187
+ super().__init__(
188
+ in_features, local_multiple * multiple_of, bias=bias, device=device, dtype=dtype
189
+ )
190
+ self.process_group = process_group
191
+ self.sequence_parallel = sequence_parallel
192
+
193
+ def forward(self, x):
194
+ # If self.sequence_parallel is True, we're doing Tensor Parallel with sequence parallelism:
195
+ # we do an all_gather of x before doing the matmul.
196
+ # If not, then the input is already gathered.
197
+ return fused_dense_func(
198
+ x,
199
+ self.weight,
200
+ self.bias,
201
+ process_group=self.process_group,
202
+ sequence_parallel=self.sequence_parallel,
203
+ )
204
+
205
+
206
+ class RowParallelLinear(nn.Linear):
207
+ def __init__(
208
+ self,
209
+ in_features: int,
210
+ out_features: int,
211
+ process_group: ProcessGroup,
212
+ bias: bool = True,
213
+ sequence_parallel=True,
214
+ multiple_of=1,
215
+ device=None,
216
+ dtype=None,
217
+ ) -> None:
218
+ world_size = torch.distributed.get_world_size(process_group)
219
+ rank = torch.distributed.get_rank(process_group)
220
+ if in_features % multiple_of:
221
+ raise ValueError(f"in_features ({in_features}) must be a multiple of {multiple_of}")
222
+ multiple = in_features // multiple_of
223
+ # We want to split @multiple across world_size, but it could be an uneven split
224
+ div = multiple // world_size
225
+ mod = multiple % world_size
226
+ # The first @mod ranks get @div + 1 copies, the rest get @div copies
227
+ local_multiple = div + int(torch.distributed.get_rank(process_group) < mod)
228
+ # Only rank 0 will have bias
229
+ super().__init__(
230
+ local_multiple * multiple_of,
231
+ out_features,
232
+ bias=bias and rank == 0,
233
+ device=device,
234
+ dtype=dtype,
235
+ )
236
+ self.process_group = process_group
237
+ self.sequence_parallel = sequence_parallel
238
+
239
+ def forward(self, x):
240
+ """
241
+ We're doing Tensor Parallel with sequence parallelism: we do the matmul and then
242
+ a reduce_scatter of the result.
243
+ """
244
+ out = fused_dense_func(x, self.weight, self.bias)
245
+ reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce
246
+ return reduce_fn(out, self.process_group)
247
+
248
+
249
+ class FusedMLPFunc(torch.autograd.Function):
250
+ @staticmethod
251
+ @custom_fwd
252
+ def forward(
253
+ ctx,
254
+ x,
255
+ weight1,
256
+ bias1,
257
+ weight2,
258
+ bias2,
259
+ activation="gelu_approx",
260
+ save_pre_act=True,
261
+ return_residual=False,
262
+ checkpoint_lvl=0,
263
+ heuristic=0,
264
+ process_group=None,
265
+ sequence_parallel=True,
266
+ ):
267
+ """
268
+ If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel
269
+ with sequence parallelism: we do an all_gather of x before doing the matmul.
270
+ If sequence_parallel=False, then the input is already gathered.
271
+
272
+ checkpoint_lvl:
273
+ 0: no recomputation in the bwd
274
+ 1: recompute gelu_out / relu_out in the bwd
275
+ 2: recompute pre_act and gelu_out / relu_out in the bwd
276
+ """
277
+ assert -1 <= heuristic <= 4
278
+ assert activation in ["gelu_approx", "relu", "sqrelu"]
279
+ if activation == "sqrelu":
280
+ assert heuristic == -1
281
+ if not save_pre_act:
282
+ checkpoint_lvl = 2
283
+ assert checkpoint_lvl in [0, 1, 2]
284
+ ctx.return_residual = return_residual
285
+ ctx.process_group = process_group
286
+ ctx.sequence_parallel = sequence_parallel
287
+ ctx.checkpoint_lvl = checkpoint_lvl
288
+ ctx.activation = activation
289
+ ctx.heuristic = heuristic
290
+
291
+ if torch.is_autocast_enabled():
292
+ x = x.to(dtype=torch.get_autocast_gpu_dtype())
293
+ x = x.contiguous()
294
+ if process_group is not None and sequence_parallel:
295
+ # We want to kick off the all_gather early, before weight dtype conversion
296
+ total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
297
+ else:
298
+ total_x = x
299
+
300
+ if torch.is_autocast_enabled():
301
+ dtype = torch.get_autocast_gpu_dtype()
302
+ weight1, weight2 = [a.to(dtype=dtype) for a in [weight1, weight2]]
303
+ bias1 = bias1.to(dtype=dtype) if bias1 is not None else None
304
+ bias2 = bias2.to(dtype=dtype) if bias2 is not None else None
305
+ weight1 = weight1.contiguous()
306
+ bias1 = bias1.contiguous() if bias1 is not None else None
307
+ weight2 = weight2.contiguous()
308
+ bias2 = bias2.contiguous() if bias2 is not None else None
309
+ if process_group is not None and sequence_parallel:
310
+ handle_x.wait()
311
+ batch_shape, n = total_x.shape[:-1], total_x.shape[-1]
312
+ batch_dim = batch_shape.numel()
313
+ # https://github.com/pytorch/pytorch/blob/5b51849b48a7dbccd297286cc0110def4706f9e7/aten/src/ATen/native/cuda/Blas.cpp#L174
314
+ if min(batch_dim, n, *weight1.shape, *weight2.shape) > 65535 * 32:
315
+ raise RuntimeError("fused_dense only supports matrix dims <= 2M")
316
+ if heuristic == -1:
317
+ pre_act = F.linear(total_x, weight1, bias1)
318
+ activation_fn = (
319
+ partial(F.gelu, approximate="tanh")
320
+ if activation == "gelu_approx"
321
+ else (sqrelu_fwd if activation == "sqrelu" else F.relu)
322
+ )
323
+ with torch.jit.fuser("fuser2"):
324
+ output1 = activation_fn(pre_act)
325
+ # This is before adding bias1
326
+ # pre_act = F.linear(total_x.reshape(batch_dim, n), weight1)
327
+ # with torch.jit.fuser('fuser2'):
328
+ # output1 = bias_gelu(pre_act, bias1)
329
+ else:
330
+ is_gelu = activation == "gelu_approx"
331
+ output1, *rest = fused_dense_cuda.linear_act_forward(
332
+ total_x.reshape(batch_dim, n), weight1, bias1, is_gelu, save_pre_act, heuristic
333
+ )
334
+ if save_pre_act:
335
+ pre_act = rest[0]
336
+ output2 = F.linear(output1, weight2, bias2)
337
+ if checkpoint_lvl == 0 or (checkpoint_lvl == 1 and activation == "relu"):
338
+ # For RELU the pre_act is very small (just a bit-mask) so we just save it
339
+ ctx.save_for_backward(x, weight1, weight2, pre_act, output1)
340
+ elif checkpoint_lvl == 1:
341
+ ctx.save_for_backward(x, weight1, weight2, pre_act)
342
+ elif checkpoint_lvl == 2:
343
+ ctx.save_for_backward(x, weight1, weight2, bias1)
344
+ output2 = output2.reshape(*batch_shape, output2.shape[-1])
345
+ return output2 if not return_residual else (output2, x)
346
+
347
+ @staticmethod
348
+ @custom_bwd
349
+ def backward(ctx, grad_output, *args):
350
+ grad_output = grad_output.contiguous()
351
+ checkpoint_lvl = ctx.checkpoint_lvl
352
+ activation = ctx.activation
353
+ activation_fn = (
354
+ partial(F.gelu, approximate="tanh")
355
+ if activation == "gelu_approx"
356
+ else (sqrelu_fwd if activation == "sqrelu" else F.relu)
357
+ )
358
+ if ctx.return_residual:
359
+ (grad_input,) = args
360
+ grad_input = grad_input.contiguous()
361
+ process_group = ctx.process_group
362
+ sequence_parallel = ctx.sequence_parallel
363
+ x, weight1, weight2, *rest = ctx.saved_tensors
364
+ if process_group is None or not sequence_parallel:
365
+ total_x = x
366
+ batch_shape = grad_output.shape[:-1]
367
+ batch_dim = batch_shape.numel()
368
+ if checkpoint_lvl in [0, 1]:
369
+ if process_group is not None and sequence_parallel:
370
+ total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
371
+ if checkpoint_lvl == 0 or (checkpoint_lvl == 1 and activation == "relu"):
372
+ pre_act, output1 = rest
373
+ elif checkpoint_lvl == 1:
374
+ (pre_act,) = rest
375
+ with torch.jit.fuser("fuser2"):
376
+ output1 = activation_fn(pre_act)
377
+ elif checkpoint_lvl == 2:
378
+ (bias1,) = rest
379
+ if process_group is not None and sequence_parallel:
380
+ total_x, _ = all_gather_raw(x, process_group)
381
+ if ctx.heuristic == -1:
382
+ pre_act = F.linear(total_x, weight1, bias1)
383
+ with torch.jit.fuser("fuser2"):
384
+ output1 = activation_fn(pre_act)
385
+ else:
386
+ output1, pre_act = fused_dense_cuda.linear_act_forward(
387
+ total_x.reshape(batch_dim, total_x.shape[-1]),
388
+ weight1,
389
+ bias1,
390
+ activation == "gelu_approx",
391
+ True,
392
+ ctx.heuristic,
393
+ )
394
+
395
+ grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1])
396
+ output1 = output1.reshape(batch_dim, output1.shape[-1])
397
+ pre_act = pre_act.reshape(batch_dim, pre_act.shape[-1])
398
+ if ctx.needs_input_grad[3]:
399
+ grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad(
400
+ output1, grad_output, ctx.needs_input_grad[4]
401
+ )
402
+ else:
403
+ grad_weight2 = None
404
+ grad_bias2 = grad_output if ctx.needs_input_grad[4] else None
405
+ if ctx.heuristic == -1:
406
+ # grad_pre_act = matmul_dgelu(grad_output, weight2, pre_act)
407
+ grad_output1 = F.linear(grad_output, weight2.t())
408
+ activation_grad_fn = (
409
+ gelu_bwd
410
+ if activation == "gelu_approx"
411
+ else (sqrelu_bwd if activation == "sqrelu" else relu_bwd)
412
+ )
413
+ with torch.jit.fuser("fuser2"):
414
+ grad_pre_act = activation_grad_fn(grad_output1, pre_act)
415
+ else:
416
+ # The cublasLt epilogue has to compute both gelu/relu grad and bias grad, we can't
417
+ # just compute gelu/relu grad
418
+ grad_pre_act, grad_bias1 = fused_dense_cuda.bias_act_linear_dgrad_bgrad(
419
+ weight2, grad_output, pre_act, activation == "gelu_approx", ctx.heuristic
420
+ )
421
+ if not ctx.needs_input_grad[2]:
422
+ grad_bias1 = None
423
+ if ctx.needs_input_grad[0]:
424
+ if not ctx.return_residual:
425
+ grad_input = F.linear(grad_pre_act, weight1.t())
426
+ else:
427
+ grad_input = torch.addmm(
428
+ grad_input.reshape(batch_dim, grad_input.shape[-1]), grad_pre_act, weight1
429
+ )
430
+ grad_input = grad_input.reshape(*batch_shape, grad_input.shape[-1])
431
+ if process_group is not None:
432
+ reduce_fn = reduce_scatter_raw if sequence_parallel else all_reduce_raw
433
+ grad_input, handle_grad_input = reduce_fn(grad_input, process_group, async_op=True)
434
+ else:
435
+ grad_input = None
436
+ if ctx.heuristic == -1:
437
+ if ctx.needs_input_grad[1]:
438
+ if process_group is not None and sequence_parallel and checkpoint_lvl != 2:
439
+ handle_x.wait()
440
+ grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_wgrad(
441
+ total_x.reshape(batch_dim, total_x.shape[-1]),
442
+ grad_pre_act,
443
+ ctx.needs_input_grad[2],
444
+ )
445
+ else:
446
+ grad_weight1 = None
447
+ grad_bias1 = grad_pre_act if ctx.needs_input_grad[2] else None
448
+ else:
449
+ if ctx.needs_input_grad[1]:
450
+ if process_group is not None and sequence_parallel and checkpoint_lvl != 2:
451
+ handle_x.wait()
452
+ grad_weight1 = F.linear(
453
+ grad_pre_act.t(), total_x.reshape(batch_dim, total_x.shape[-1]).t()
454
+ )
455
+ else:
456
+ grad_weight1 = None
457
+ if process_group is not None and ctx.needs_input_grad[0]:
458
+ handle_grad_input.wait()
459
+ return (
460
+ grad_input,
461
+ grad_weight1,
462
+ grad_bias1,
463
+ grad_weight2,
464
+ grad_bias2,
465
+ None,
466
+ None,
467
+ None,
468
+ None,
469
+ None,
470
+ None,
471
+ None,
472
+ )
473
+
474
+
475
+ def fused_mlp_func(
476
+ x: Tensor,
477
+ weight1: Tensor,
478
+ weight2: Tensor,
479
+ bias1: Optional[Tensor] = None,
480
+ bias2: Optional[Tensor] = None,
481
+ activation: str = "gelu_approx",
482
+ save_pre_act: bool = True,
483
+ return_residual: bool = False,
484
+ checkpoint_lvl: int = 0,
485
+ heuristic: int = 0,
486
+ process_group: Optional[ProcessGroup] = None,
487
+ sequence_parallel: bool = True,
488
+ ):
489
+ assert activation in ["gelu_approx", "relu", "sqrelu"]
490
+ dtype_eligible = x.dtype in [torch.float16, torch.bfloat16] or (
491
+ x.dtype == torch.float32 and torch.is_autocast_enabled()
492
+ )
493
+ # If we save pre-activation, dimension must be divisible by 128 (relu) or 8 (gelu)
494
+ dim_eligible = not save_pre_act or (x.shape[-1] % (128 if activation == "relu" else 8) == 0)
495
+ if (
496
+ x.is_cuda
497
+ and weight1.is_cuda
498
+ and weight2.is_cuda
499
+ and (bias1 is None or bias1.is_cuda)
500
+ and (bias2 is None or bias2.is_cuda)
501
+ and dtype_eligible
502
+ and dim_eligible
503
+ ):
504
+ return FusedMLPFunc.apply(
505
+ x,
506
+ weight1,
507
+ bias1,
508
+ weight2,
509
+ bias2,
510
+ activation,
511
+ save_pre_act,
512
+ return_residual,
513
+ checkpoint_lvl,
514
+ heuristic,
515
+ process_group,
516
+ sequence_parallel,
517
+ )
518
+ else:
519
+ assert process_group is None
520
+ pre_act = F.linear(x, weight1, bias1)
521
+ activation_fn = (
522
+ partial(F.gelu, approximate="tanh")
523
+ if activation == "gelu_approx"
524
+ else partial(F.relu, inplace=True)
525
+ )
526
+ output1 = activation_fn(pre_act)
527
+ output2 = F.linear(output1, weight2, bias2)
528
+ return output2 if not return_residual else (output2, x)
529
+
530
+
531
+ class FusedMLP(nn.Module):
532
+ def __init__(
533
+ self,
534
+ in_features,
535
+ hidden_features=None,
536
+ out_features=None,
537
+ bias1=True,
538
+ bias2=True,
539
+ activation="gelu_approx",
540
+ return_residual=False,
541
+ checkpoint_lvl=0,
542
+ heuristic="auto",
543
+ device=None,
544
+ dtype=None,
545
+ ):
546
+ """
547
+ If process_group is not None, we're doing Tensor Parallel with sequence parallelism:
548
+ we do an all_gather of x before doing the matmul, gelu, then matmul.
549
+ Finally we do a reduce_scatter of the output.
550
+
551
+ checkpoint_lvl (increasing lvl means slower but more memory saving):
552
+ 0: no recomputation in the bwd
553
+ 1: recompute gelu_out in the bwd
554
+ 2: recompute pre_act and gelu_out in the bwd
555
+ heuristic:
556
+ -1: don't fuse gemm + gelu (separate kernel)
557
+ 0..4: use this heuristic for the algo section in the fused gemm + gelu
558
+ 'auto': heuristic will be picked automatically:
559
+ For CUDA >= 11.8, we set heuristic=0 for both fp16 and bf16 for best perf.
560
+ For CUDA <= 11.7, we set heuristic=1 for fp16 and heuristic=-1 for bf16.
561
+ For H100, we set heuristic=-1 for both fp16 and bf16 as the fused cuBlasLt implementation
562
+ is slower than the unfused version.
563
+ return_residual: whether to return the input x along with the output. This is for
564
+ performance reason: for post-norm architecture, returning the input allows us
565
+ to fuse the backward of nn.Linear with the residual connection.
566
+ """
567
+ assert checkpoint_lvl in [0, 1, 2]
568
+ assert activation in ["gelu_approx", "relu", "sqrelu"]
569
+ factory_kwargs = {"device": device, "dtype": dtype}
570
+ super().__init__()
571
+ out_features = out_features or in_features
572
+ hidden_features = hidden_features or in_features * 4
573
+ self.activation = activation
574
+ self.return_residual = return_residual
575
+ self.checkpoint_lvl = checkpoint_lvl
576
+ self.heuristic = heuristic if activation != "sqrelu" else -1
577
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1, **factory_kwargs)
578
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs)
579
+
580
+ def forward(self, x, process_group=None):
581
+ dtype = x.dtype if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype()
582
+ if self.heuristic == "auto":
583
+ if self.activation == "gelu_approx":
584
+ if torch.cuda.get_device_capability("cuda") == (9, 0):
585
+ heuristic = -1
586
+ else:
587
+ cuda_ver = tuple(map(int, torch.version.cuda.split(".")))
588
+ heuristic = 0 if cuda_ver >= (11, 8) else (1 if dtype == torch.float16 else -1)
589
+ else:
590
+ heuristic = 0
591
+ else:
592
+ heuristic = self.heuristic
593
+ out = fused_mlp_func(
594
+ x,
595
+ self.fc1.weight,
596
+ self.fc2.weight,
597
+ self.fc1.bias,
598
+ self.fc2.bias,
599
+ activation=self.activation,
600
+ save_pre_act=self.training,
601
+ return_residual=self.return_residual,
602
+ checkpoint_lvl=self.checkpoint_lvl,
603
+ heuristic=heuristic,
604
+ process_group=process_group,
605
+ )
606
+ if self.return_residual:
607
+ out, x = out
608
+ if process_group is not None:
609
+ out = reduce_scatter(out, process_group)
610
+ return out if not self.return_residual else (out, x)
611
+
612
+
613
+ class ParallelFusedMLP(nn.Module):
614
+ def __init__(
615
+ self,
616
+ in_features,
617
+ hidden_features=None,
618
+ out_features=None,
619
+ activation="gelu_approx",
620
+ process_group: ProcessGroup = None,
621
+ bias1=True,
622
+ bias2=True,
623
+ sequence_parallel=True,
624
+ checkpoint_lvl=0,
625
+ heuristic="auto",
626
+ device=None,
627
+ dtype=None,
628
+ ):
629
+ """
630
+ process_group is required. We're doing Tensor Parallel with sequence parallelism:
631
+ we do an all_gather of x before doing the matmul, gelu, then matmul.
632
+ Finally we do a reduce_scatter of the output.
633
+
634
+ checkpoint_lvl (increasing lvl means slower but more memory saving):
635
+ 0: no recomputation in the bwd
636
+ 1: recompute gelu_out in the bwd
637
+ 2: recompute pre_act and gelu_out in the bwd
638
+ heuristic:
639
+ -1: don't fuse gemm + gelu (separate kernel)
640
+ 0..4: use this heuristic for the algo section in the fused gemm + gelu
641
+ 'auto': heuristic will be picked automatically:
642
+ For CUDA >= 11.8, we set heuristic=0 for both fp16 and bf16 for best perf.
643
+ For CUDA <= 11.7, we set heuristic=1 for fp16 and heuristic=-1 for bf16.
644
+ """
645
+ assert checkpoint_lvl in [0, 1, 2]
646
+ assert activation in ["gelu_approx", "relu", "sqrelu"]
647
+ assert process_group is not None
648
+ factory_kwargs = {"device": device, "dtype": dtype}
649
+ super().__init__()
650
+ out_features = out_features or in_features
651
+ hidden_features = hidden_features or in_features * 4
652
+ self.activation = activation
653
+ self.process_group = process_group
654
+ self.sequence_parallel = sequence_parallel
655
+ self.checkpoint_lvl = checkpoint_lvl
656
+ self.heuristic = heuristic if activation != "sqrelu" else -1
657
+ self.fc1 = ColumnParallelLinear(
658
+ in_features, hidden_features, process_group, bias=bias1, **factory_kwargs
659
+ )
660
+ self.fc2 = RowParallelLinear(
661
+ hidden_features, out_features, process_group, bias=bias2, **factory_kwargs
662
+ )
663
+
664
+ def forward(self, x):
665
+ dtype = x.dtype if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype()
666
+ if self.heuristic == "auto":
667
+ if self.activation == "gelu_approx":
668
+ cuda_ver = tuple(map(int, torch.version.cuda.split(".")))
669
+ heuristic = 0 if cuda_ver >= (11, 8) else (1 if dtype == torch.float16 else -1)
670
+ else:
671
+ heuristic = 0
672
+ else:
673
+ heuristic = self.heuristic
674
+ out = fused_mlp_func(
675
+ x,
676
+ self.fc1.weight,
677
+ self.fc2.weight,
678
+ self.fc1.bias,
679
+ self.fc2.bias,
680
+ activation=self.activation,
681
+ save_pre_act=self.training,
682
+ checkpoint_lvl=self.checkpoint_lvl,
683
+ heuristic=heuristic,
684
+ process_group=self.process_group,
685
+ sequence_parallel=self.sequence_parallel,
686
+ )
687
+ reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce
688
+ return reduce_fn(out, self.process_group)
build/torch211-cxx11-cu126-aarch64-linux/ops/layer_norm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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, Tri Dao.
2
+ # Adapted from https://github.com/NVIDIA/apex/blob/master/apex/contrib/layer_norm/layer_norm.py
3
+
4
+ import dropout_layer_norm
5
+ import torch
6
+ from torch.nn import init
7
+
8
+
9
+ def maybe_align(x, alignment_in_bytes=16):
10
+ """Assume that x already has last dim divisible by alignment_in_bytes"""
11
+ # TD [2023-07-04] I'm not 100% sure that clone will align the memory
12
+ # https://discuss.pytorch.org/t/how-to-ensure-that-tensor-data-ptr-is-aligned-to-16-bytes/183440
13
+ return x if x.data_ptr() % alignment_in_bytes == 0 else x.clone()
14
+
15
+
16
+ def _dropout_add_layer_norm_forward(
17
+ x0,
18
+ residual,
19
+ gamma,
20
+ beta,
21
+ rowscale,
22
+ colscale,
23
+ dropout_p,
24
+ epsilon,
25
+ residual_in_fp32=False,
26
+ is_rms_norm=False,
27
+ ):
28
+ """Assume that arguments are contiguous and aligned to 16 bytes"""
29
+ hidden_size = gamma.numel()
30
+ x0mat = x0.view((-1, hidden_size))
31
+ residualmat = residual.view((-1, hidden_size)) if residual is not None else None
32
+ rowscale = rowscale.view(-1) if rowscale is not None else None
33
+ zmat, xmat, dmask, mu, rsigma = dropout_layer_norm.dropout_add_ln_fwd(
34
+ x0mat,
35
+ residualmat,
36
+ gamma,
37
+ beta,
38
+ rowscale,
39
+ colscale,
40
+ None,
41
+ None,
42
+ dropout_p,
43
+ epsilon,
44
+ 1.0,
45
+ 0,
46
+ None,
47
+ residual_in_fp32,
48
+ is_rms_norm,
49
+ )
50
+ # dmask is None if dropout_p == 0.0
51
+ # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype
52
+ return zmat, xmat if xmat is not None else x0mat, dmask, mu, rsigma
53
+
54
+
55
+ def _dropout_add_layer_norm_backward(
56
+ dz,
57
+ dx,
58
+ x,
59
+ x0,
60
+ dmask,
61
+ mu,
62
+ rsigma,
63
+ gamma,
64
+ rowscale,
65
+ colscale,
66
+ dropout_p,
67
+ has_residual,
68
+ is_rms_norm=False,
69
+ ):
70
+ """Assume that arguments are contiguous and aligned to 16 bytes
71
+ dx == None means that it was a post-norm architecture
72
+ (x = drop(x0) + residual was not returned in the fwd).
73
+ x0 must not be None if we have colscale.
74
+ """
75
+ hidden_size = gamma.numel()
76
+ xmat = x.view((-1, hidden_size))
77
+ dzmat = dz.view(xmat.shape)
78
+ dxmat = dx.view(xmat.shape) if dx is not None else None
79
+ x0mat = x0.view((-1, hidden_size)) if x0 is not None else None
80
+ rowscale = rowscale.view(-1) if rowscale is not None else None
81
+ if colscale is not None:
82
+ assert x0 is not None, "x0 is required to compute the gradient of colscale"
83
+ dx0mat, dresidualmat, dgamma, dbeta, _, _, *rest = dropout_layer_norm.dropout_add_ln_bwd(
84
+ dzmat,
85
+ dxmat,
86
+ xmat,
87
+ x0mat,
88
+ dmask,
89
+ mu,
90
+ rsigma,
91
+ gamma,
92
+ rowscale,
93
+ colscale,
94
+ None,
95
+ None,
96
+ dropout_p,
97
+ 1.0,
98
+ 0,
99
+ has_residual,
100
+ is_rms_norm,
101
+ )
102
+ # dresidualmat is None if not has_residual
103
+ if colscale is None:
104
+ return dx0mat, dresidualmat, dgamma, dbeta
105
+ else:
106
+ dcolscale = rest[0]
107
+ return dx0mat, dresidualmat, dgamma, dbeta, dcolscale
108
+
109
+
110
+ def _dropout_add_layer_norm_subset_forward(
111
+ x0,
112
+ residual,
113
+ gamma,
114
+ beta,
115
+ colscale,
116
+ x0_subset,
117
+ out_subset,
118
+ dropout_p,
119
+ epsilon,
120
+ rowscale_const,
121
+ out_numrows,
122
+ residual_in_fp32=False,
123
+ is_rms_norm=False,
124
+ ):
125
+ """Assume that arguments are contiguous and aligned to 16 bytes"""
126
+ hidden_size = gamma.numel()
127
+ x0mat = x0.view((-1, hidden_size))
128
+ residualmat = residual.view((-1, hidden_size)) if residual is not None else None
129
+ x0_subset = x0_subset.view(-1) if x0_subset is not None else None
130
+ out_subset = out_subset.view(-1) if out_subset is not None else None
131
+ zmat, xmat, dmask, mu, rsigma = dropout_layer_norm.dropout_add_ln_fwd(
132
+ x0mat,
133
+ residualmat,
134
+ gamma,
135
+ beta,
136
+ None,
137
+ colscale,
138
+ x0_subset,
139
+ out_subset,
140
+ dropout_p,
141
+ epsilon,
142
+ rowscale_const,
143
+ out_numrows,
144
+ None,
145
+ residual_in_fp32,
146
+ is_rms_norm,
147
+ )
148
+ # dmask is None if dropout_p == 0.0
149
+ # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype
150
+ return zmat, xmat if xmat is not None else x0mat, dmask, mu, rsigma
151
+
152
+
153
+ def _dropout_add_layer_norm_subset_backward(
154
+ dz,
155
+ dx,
156
+ x,
157
+ x0,
158
+ dmask,
159
+ mu,
160
+ rsigma,
161
+ gamma,
162
+ colscale,
163
+ x0_subset,
164
+ out_subset,
165
+ dropout_p,
166
+ rowscale_const,
167
+ x0_numrows,
168
+ has_residual,
169
+ is_rms_norm=False,
170
+ ):
171
+ """Assume that arguments are contiguous and aligned to 16 bytes
172
+ dx == None means that it was a post-norm architecture
173
+ (x = drop(x0) + residual was not returned in the fwd).
174
+ x0 must not be None if we have colscale.
175
+ """
176
+ hidden_size = gamma.numel()
177
+ xmat = x.view((-1, hidden_size))
178
+ dzmat = dz.view(-1, hidden_size)
179
+ dxmat = dx.view(xmat.shape) if dx is not None else None
180
+ x0mat = x0.view((-1, hidden_size)) if x0 is not None else None
181
+ x0_subset = x0_subset.view(-1) if x0_subset is not None else None
182
+ out_subset = out_subset.view(-1) if out_subset is not None else None
183
+ if colscale is not None:
184
+ assert x0 is not None, "x0 is required to compute the gradient of colscale"
185
+ dx0mat, dresidualmat, dgamma, dbeta, _, _, *rest = dropout_layer_norm.dropout_add_ln_bwd(
186
+ dzmat,
187
+ dxmat,
188
+ xmat,
189
+ x0mat,
190
+ dmask,
191
+ mu,
192
+ rsigma,
193
+ gamma,
194
+ None,
195
+ colscale,
196
+ x0_subset,
197
+ out_subset,
198
+ dropout_p,
199
+ rowscale_const,
200
+ x0_numrows,
201
+ has_residual,
202
+ is_rms_norm,
203
+ )
204
+ # dresidualmat is None if not has_residual
205
+ if colscale is None:
206
+ return dx0mat, dresidualmat, dgamma, dbeta
207
+ else:
208
+ dcolscale = rest[0]
209
+ return dx0mat, dresidualmat, dgamma, dbeta, dcolscale
210
+
211
+
212
+ def _dropout_add_layer_norm_parallel_residual_forward(
213
+ x0,
214
+ x1,
215
+ residual,
216
+ gamma0,
217
+ beta0,
218
+ gamma1,
219
+ beta1,
220
+ dropout_p,
221
+ epsilon,
222
+ residual_in_fp32=False,
223
+ is_rms_norm=False,
224
+ ):
225
+ """Assume that arguments are contiguous and aligned to 16 bytes"""
226
+ hidden_size = gamma0.numel()
227
+ x0mat = x0.view((-1, hidden_size))
228
+ x1mat = x1.view((-1, hidden_size)) if x1 is not None else None
229
+ residualmat = residual.view((-1, hidden_size)) if residual is not None else None
230
+ (
231
+ z0mat,
232
+ z1mat,
233
+ xmat,
234
+ dmask0,
235
+ dmask1,
236
+ mu,
237
+ rsigma,
238
+ ) = dropout_layer_norm.dropout_add_ln_parallel_residual_fwd(
239
+ x0mat,
240
+ x1mat,
241
+ residualmat,
242
+ gamma0,
243
+ beta0,
244
+ gamma1,
245
+ beta1,
246
+ dropout_p,
247
+ epsilon,
248
+ None,
249
+ residual_in_fp32,
250
+ is_rms_norm,
251
+ )
252
+ # dmask0 and dmask1 are None if dropout_p == 0.0
253
+ # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype
254
+ return z0mat, z1mat, xmat if xmat is not None else x0mat, dmask0, dmask1, mu, rsigma
255
+
256
+
257
+ def _dropout_add_layer_norm_parallel_residual_backward(
258
+ dz0,
259
+ dz1,
260
+ dx,
261
+ x,
262
+ dmask0,
263
+ dmask1,
264
+ mu,
265
+ rsigma,
266
+ gamma0,
267
+ gamma1,
268
+ dropout_p,
269
+ has_x1,
270
+ has_residual,
271
+ is_rms_norm=False,
272
+ ):
273
+ """Assume that arguments are contiguous and aligned to 16 bytes
274
+ dx == None means that it was a post-norm architecture
275
+ (x = drop(x0) + residual was not returned in the fwd).
276
+ """
277
+ hidden_size = gamma0.numel()
278
+ xmat = x.view((-1, hidden_size))
279
+ dz0mat = dz0.view(xmat.shape)
280
+ dz1mat = dz1.view(xmat.shape) if dz1 is not None else None
281
+ dxmat = dx.view(xmat.shape) if dx is not None else None
282
+ (
283
+ dx0mat,
284
+ dx1mat,
285
+ dresidualmat,
286
+ dgamma0,
287
+ dbeta0,
288
+ dgamma1,
289
+ dbeta1,
290
+ *rest,
291
+ ) = dropout_layer_norm.dropout_add_ln_parallel_residual_bwd(
292
+ dz0mat,
293
+ dz1mat,
294
+ dxmat,
295
+ xmat,
296
+ dmask0,
297
+ dmask1,
298
+ mu,
299
+ rsigma,
300
+ gamma0,
301
+ gamma1,
302
+ dropout_p,
303
+ has_x1,
304
+ has_residual,
305
+ is_rms_norm,
306
+ )
307
+ # dresidualmat is None if not has_residual
308
+ return dx0mat, dx1mat, dresidualmat, dgamma0, dbeta0, dgamma1, dbeta1
309
+
310
+
311
+ class DropoutAddLayerNormFn(torch.autograd.Function):
312
+ @staticmethod
313
+ def forward(
314
+ ctx,
315
+ x0,
316
+ residual,
317
+ gamma,
318
+ beta,
319
+ rowscale,
320
+ colscale,
321
+ dropout_p,
322
+ epsilon,
323
+ residual_in_fp32=False,
324
+ prenorm=False,
325
+ is_rms_norm=False,
326
+ return_dmask=False,
327
+ ):
328
+ x0 = maybe_align(x0.contiguous(), 16)
329
+ residual = maybe_align(residual.contiguous(), 16) if residual is not None else None
330
+ gamma = maybe_align(gamma.contiguous(), 16)
331
+ beta = maybe_align(beta.contiguous(), 16) if beta is not None else None
332
+ rowscale = maybe_align(rowscale.contiguous(), 16) if rowscale is not None else None
333
+ colscale = maybe_align(colscale.contiguous(), 16) if colscale is not None else None
334
+ zmat, xmat, dmask, mu, rsigma = _dropout_add_layer_norm_forward(
335
+ x0,
336
+ residual,
337
+ gamma,
338
+ beta,
339
+ rowscale,
340
+ colscale,
341
+ dropout_p,
342
+ epsilon,
343
+ residual_in_fp32,
344
+ is_rms_norm,
345
+ )
346
+ # Only need to save x0 if we need to compute gradient wrt colscale
347
+ x0_saved = x0 if colscale is not None else None
348
+ ctx.save_for_backward(
349
+ xmat.view(x0.shape), x0_saved, dmask, gamma, mu, rsigma, rowscale, colscale
350
+ )
351
+ ctx.prenorm = prenorm
352
+ ctx.dropout_p = dropout_p
353
+ ctx.has_residual = residual is not None
354
+ ctx.is_rms_norm = is_rms_norm
355
+ ctx.has_beta = beta is not None
356
+ if not return_dmask:
357
+ return (
358
+ zmat.view(x0.shape) if not prenorm else (zmat.view(x0.shape), xmat.view(x0.shape))
359
+ )
360
+ else:
361
+ dmask = (
362
+ dmask.view(x0.shape)
363
+ if dropout_p > 0.0
364
+ else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)
365
+ )
366
+ ctx.mark_non_differentiable(dmask)
367
+ return (
368
+ (zmat.view(x0.shape), dmask)
369
+ if not prenorm
370
+ else (zmat.view(x0.shape), xmat.view(x0.shape), dmask)
371
+ )
372
+
373
+ @staticmethod
374
+ def backward(ctx, dz, *args):
375
+ # assert dz.is_contiguous()
376
+ dz = maybe_align(dz.contiguous(), 16) # this happens!
377
+ dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None
378
+ x, x0, dmask, gamma, mu, rsigma, rowscale, colscale = ctx.saved_tensors
379
+ # x0 is None if colscale is None
380
+ dropout_p = ctx.dropout_p
381
+ has_residual = ctx.has_residual
382
+ dx0mat, dresidualmat, dgamma, dbeta, *rest = _dropout_add_layer_norm_backward(
383
+ dz,
384
+ dx,
385
+ x,
386
+ x0,
387
+ dmask,
388
+ mu,
389
+ rsigma,
390
+ gamma,
391
+ rowscale,
392
+ colscale,
393
+ dropout_p,
394
+ has_residual,
395
+ ctx.is_rms_norm,
396
+ )
397
+ dx0 = dx0mat.view(x.shape)
398
+ dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None
399
+ dcolscale = rest[0] if colscale is not None else None
400
+ return (
401
+ dx0,
402
+ dresidual,
403
+ dgamma,
404
+ dbeta if ctx.has_beta else None,
405
+ None,
406
+ dcolscale,
407
+ None,
408
+ None,
409
+ None,
410
+ None,
411
+ None,
412
+ None,
413
+ )
414
+
415
+
416
+ class DropoutAddLayerNormSubsetFn(torch.autograd.Function):
417
+ @staticmethod
418
+ def forward(
419
+ ctx,
420
+ x0,
421
+ residual,
422
+ gamma,
423
+ beta,
424
+ colscale,
425
+ x0_subset,
426
+ out_subset,
427
+ dropout_p,
428
+ epsilon,
429
+ rowscale_const,
430
+ out_numrows,
431
+ residual_in_fp32=False,
432
+ prenorm=False,
433
+ is_rms_norm=False,
434
+ return_dmask=False,
435
+ ):
436
+ x0 = maybe_align(x0.contiguous(), 16)
437
+ residual = maybe_align(residual.contiguous(), 16) if residual is not None else None
438
+ gamma = maybe_align(gamma.contiguous(), 16)
439
+ beta = maybe_align(beta.contiguous(), 16) if beta is not None else None
440
+ colscale = maybe_align(colscale.contiguous(), 16) if colscale is not None else None
441
+ zmat, xmat, dmask, mu, rsigma = _dropout_add_layer_norm_subset_forward(
442
+ x0,
443
+ residual,
444
+ gamma,
445
+ beta,
446
+ colscale,
447
+ x0_subset,
448
+ out_subset,
449
+ dropout_p,
450
+ epsilon,
451
+ rowscale_const,
452
+ out_numrows,
453
+ residual_in_fp32,
454
+ is_rms_norm,
455
+ )
456
+ # Only need to save x0 if we need to compute gradient wrt colscale
457
+ x0_saved = x0 if colscale is not None else None
458
+ x_shape = (-1, *x0.shape[1:])
459
+ ctx.save_for_backward(
460
+ xmat.view(x_shape), x0_saved, dmask, gamma, mu, rsigma, colscale, x0_subset, out_subset
461
+ )
462
+ ctx.prenorm = prenorm
463
+ ctx.dropout_p = dropout_p
464
+ ctx.rowscale_const = rowscale_const
465
+ ctx.x0_numrows = x0.shape[:-1].numel()
466
+ ctx.has_residual = residual is not None
467
+ ctx.is_rms_norm = is_rms_norm
468
+ ctx.has_beta = beta is not None
469
+ z_shape = (-1, *x0.shape[1:])
470
+ if not return_dmask:
471
+ return zmat.view(z_shape) if not prenorm else (zmat.view(z_shape), xmat.view(x0.shape))
472
+ else:
473
+ z = zmat.view(z_shape)
474
+ dmask = (
475
+ dmask.view(x0.shape)
476
+ if dropout_p > 0.0
477
+ else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)
478
+ )
479
+ ctx.mark_non_differentiable(dmask)
480
+ return (z, dmask) if not prenorm else (z, xmat.view(x_shape), dmask)
481
+
482
+ @staticmethod
483
+ def backward(ctx, dz, *args):
484
+ # assert dz.is_contiguous()
485
+ dz = maybe_align(dz.contiguous(), 16) # this happens!
486
+ dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None
487
+ x, x0, dmask, gamma, mu, rsigma, colscale, x0_subset, out_subset = ctx.saved_tensors
488
+ # x0 is None if colscale is None
489
+ dropout_p = ctx.dropout_p
490
+ has_residual = ctx.has_residual
491
+ dx0mat, dresidualmat, dgamma, dbeta, *rest = _dropout_add_layer_norm_subset_backward(
492
+ dz,
493
+ dx,
494
+ x,
495
+ x0,
496
+ dmask,
497
+ mu,
498
+ rsigma,
499
+ gamma,
500
+ colscale,
501
+ x0_subset,
502
+ out_subset,
503
+ dropout_p,
504
+ ctx.rowscale_const,
505
+ ctx.x0_numrows,
506
+ has_residual,
507
+ ctx.is_rms_norm,
508
+ )
509
+ dx0 = dx0mat.view(-1, *x.shape[1:])
510
+ dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None
511
+ dcolscale = rest[0] if colscale is not None else None
512
+ return (
513
+ dx0,
514
+ dresidual,
515
+ dgamma,
516
+ dbeta if ctx.has_beta else None,
517
+ dcolscale,
518
+ None,
519
+ None,
520
+ None,
521
+ None,
522
+ None,
523
+ None,
524
+ None,
525
+ None,
526
+ None,
527
+ None,
528
+ )
529
+
530
+
531
+ class DropoutAddLayerNormParallelResidualFn(torch.autograd.Function):
532
+ @staticmethod
533
+ def forward(
534
+ ctx,
535
+ x0,
536
+ x1,
537
+ residual,
538
+ gamma0,
539
+ beta0,
540
+ gamma1,
541
+ beta1,
542
+ dropout_p,
543
+ epsilon,
544
+ residual_in_fp32=False,
545
+ prenorm=False,
546
+ is_rms_norm=False,
547
+ return_dmask=False,
548
+ ):
549
+ x0 = maybe_align(x0.contiguous(), 16)
550
+ x1 = maybe_align(x1.contiguous(), 16) if x1 is not None else None
551
+ residual = maybe_align(residual.contiguous(), 16) if residual is not None else None
552
+ gamma0 = maybe_align(gamma0.contiguous(), 16)
553
+ beta0 = maybe_align(beta0.contiguous(), 16) if beta0 is not None else None
554
+ gamma1 = maybe_align(gamma1.contiguous(), 16) if gamma1 is not None else None
555
+ beta1 = maybe_align(beta1.contiguous(), 16) if beta1 is not None else None
556
+ (
557
+ z0mat,
558
+ z1mat,
559
+ xmat,
560
+ dmask0,
561
+ dmask1,
562
+ mu,
563
+ rsigma,
564
+ ) = _dropout_add_layer_norm_parallel_residual_forward(
565
+ x0,
566
+ x1,
567
+ residual,
568
+ gamma0,
569
+ beta0,
570
+ gamma1,
571
+ beta1,
572
+ dropout_p,
573
+ epsilon,
574
+ residual_in_fp32,
575
+ is_rms_norm,
576
+ )
577
+ ctx.save_for_backward(xmat.view(x0.shape), dmask0, dmask1, gamma0, gamma1, mu, rsigma)
578
+ ctx.prenorm = prenorm
579
+ ctx.dropout_p = dropout_p
580
+ ctx.has_x1 = x1 is not None
581
+ ctx.has_residual = residual is not None
582
+ ctx.is_rms_norm = is_rms_norm
583
+ ctx.has_beta = beta0 is not None
584
+ z = (z0mat.view(x0.shape), z1mat.view(x0.shape) if z1mat is not None else None)
585
+ if not return_dmask:
586
+ return z if not prenorm else (*z, xmat.view(x0.shape))
587
+ else:
588
+ dmask0 = (
589
+ dmask0.view(x0.shape)
590
+ if dropout_p > 0.0
591
+ else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)
592
+ )
593
+ dmask1 = (
594
+ dmask1.view(x0.shape)
595
+ if dropout_p > 0.0 and x1 is not None
596
+ else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)
597
+ )
598
+ ctx.mark_non_differentiable(dmask0)
599
+ ctx.mark_non_differentiable(dmask1)
600
+ return (
601
+ (*z, dmask0, dmask1) if not prenorm else (*z, xmat.view(x0.shape), dmask0, dmask1)
602
+ )
603
+
604
+ @staticmethod
605
+ def backward(ctx, dz0, dz1, *args):
606
+ dz0 = maybe_align(dz0.contiguous(), 16) # this happens!
607
+ dz1 = maybe_align(dz1.contiguous(), 16) if dz1 is not None else None
608
+ dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None
609
+ x, dmask0, dmask1, gamma0, gamma1, mu, rsigma = ctx.saved_tensors
610
+ dropout_p = ctx.dropout_p
611
+ has_x1 = ctx.has_x1
612
+ has_residual = ctx.has_residual
613
+ (
614
+ dx0mat,
615
+ dx1mat,
616
+ dresidualmat,
617
+ dgamma0,
618
+ dbeta0,
619
+ dgamma1,
620
+ dbeta1,
621
+ ) = _dropout_add_layer_norm_parallel_residual_backward(
622
+ dz0,
623
+ dz1,
624
+ dx,
625
+ x,
626
+ dmask0,
627
+ dmask1,
628
+ mu,
629
+ rsigma,
630
+ gamma0,
631
+ gamma1,
632
+ dropout_p,
633
+ has_x1,
634
+ has_residual,
635
+ ctx.is_rms_norm,
636
+ )
637
+ dx0 = dx0mat.view(x.shape)
638
+ dx1 = dx1mat.view(x.shape) if dx1mat is not None else None
639
+ dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None
640
+ return (
641
+ dx0,
642
+ dx1,
643
+ dresidual,
644
+ dgamma0,
645
+ dbeta0 if ctx.has_beta else None,
646
+ dgamma1,
647
+ dbeta1 if ctx.has_beta else None,
648
+ None,
649
+ None,
650
+ None,
651
+ None,
652
+ None,
653
+ None,
654
+ )
655
+
656
+
657
+ def layer_norm(x, weight, bias, epsilon):
658
+ return DropoutAddLayerNormFn.apply(x, None, weight, bias, None, None, 0.0, epsilon, False)
659
+
660
+
661
+ def dropout_add_layer_norm(
662
+ x0,
663
+ residual,
664
+ weight,
665
+ bias,
666
+ dropout_p,
667
+ epsilon,
668
+ rowscale=None,
669
+ layerscale=None,
670
+ prenorm=False,
671
+ residual_in_fp32=False,
672
+ return_dropout_mask=False,
673
+ ):
674
+ """residual_in_fp32 only has an effect if residual is None.
675
+ Otherwise residual dtype is residual.dtype.
676
+ """
677
+ return DropoutAddLayerNormFn.apply(
678
+ x0,
679
+ residual,
680
+ weight,
681
+ bias,
682
+ rowscale,
683
+ layerscale,
684
+ dropout_p,
685
+ epsilon,
686
+ residual_in_fp32,
687
+ prenorm,
688
+ False,
689
+ return_dropout_mask,
690
+ )
691
+
692
+
693
+ def dropout_add_layer_norm_subset(
694
+ x0,
695
+ residual,
696
+ weight,
697
+ bias,
698
+ dropout_p,
699
+ epsilon,
700
+ layerscale=None,
701
+ x0_subset=None,
702
+ out_subset=None,
703
+ rowscale_const=1.0,
704
+ out_numrows=0,
705
+ prenorm=False,
706
+ residual_in_fp32=False,
707
+ return_dropout_mask=False,
708
+ ):
709
+ """residual_in_fp32 only has an effect if residual is None.
710
+ Otherwise residual dtype is residual.dtype.
711
+ """
712
+ return DropoutAddLayerNormSubsetFn.apply(
713
+ x0,
714
+ residual,
715
+ weight,
716
+ bias,
717
+ layerscale,
718
+ x0_subset,
719
+ out_subset,
720
+ dropout_p,
721
+ epsilon,
722
+ rowscale_const,
723
+ out_numrows,
724
+ residual_in_fp32,
725
+ prenorm,
726
+ False,
727
+ return_dropout_mask,
728
+ )
729
+
730
+
731
+ def dropout_add_layer_norm_parallel_residual(
732
+ x0,
733
+ x1,
734
+ residual,
735
+ weight0,
736
+ bias0,
737
+ weight1,
738
+ bias1,
739
+ dropout_p,
740
+ epsilon,
741
+ prenorm=False,
742
+ residual_in_fp32=False,
743
+ return_dropout_mask=False,
744
+ ):
745
+ """residual_in_fp32 only has an effect if residual is None.
746
+ Otherwise residual dtype is residual.dtype.
747
+ """
748
+ return DropoutAddLayerNormParallelResidualFn.apply(
749
+ x0,
750
+ x1,
751
+ residual,
752
+ weight0,
753
+ bias0,
754
+ weight1,
755
+ bias1,
756
+ dropout_p,
757
+ epsilon,
758
+ residual_in_fp32,
759
+ prenorm,
760
+ False,
761
+ return_dropout_mask,
762
+ )
763
+
764
+
765
+ class DropoutAddLayerNorm(torch.nn.Module):
766
+ def __init__(
767
+ self,
768
+ hidden_size,
769
+ prenorm=False,
770
+ p=0.0,
771
+ eps=1e-5,
772
+ residual_in_fp32=False,
773
+ device=None,
774
+ dtype=None,
775
+ ):
776
+ factory_kwargs = {"device": device, "dtype": dtype}
777
+ super().__init__()
778
+ self.prenorm = prenorm
779
+ self.p = p
780
+ self.eps = eps
781
+ self.residual_in_fp32 = residual_in_fp32
782
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
783
+ self.bias = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
784
+ self.reset_parameters()
785
+
786
+ def reset_parameters(self):
787
+ init.ones_(self.weight)
788
+ init.zeros_(self.bias)
789
+
790
+ def forward(self, x0, residual=None):
791
+ return dropout_add_layer_norm(
792
+ x0,
793
+ residual,
794
+ self.weight,
795
+ self.bias,
796
+ self.p if self.training else 0.0,
797
+ self.eps,
798
+ prenorm=self.prenorm,
799
+ residual_in_fp32=self.residual_in_fp32,
800
+ )
build/torch211-cxx11-cu126-aarch64-linux/ops/rms_norm.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, Tri Dao.
2
+ # Adapted from https://github.com/NVIDIA/apex/blob/master/apex/contrib/layer_norm/layer_norm.py
3
+
4
+ import torch
5
+ from torch.nn import init
6
+
7
+ from flash_attn.ops.layer_norm import (
8
+ DropoutAddLayerNormFn,
9
+ DropoutAddLayerNormParallelResidualFn,
10
+ DropoutAddLayerNormSubsetFn,
11
+ )
12
+
13
+
14
+ def rms_norm(x, weight, epsilon):
15
+ return DropoutAddLayerNormFn.apply(
16
+ x, None, weight, None, None, None, 0.0, epsilon, False, False, True
17
+ )
18
+
19
+
20
+ def dropout_add_rms_norm(
21
+ x0,
22
+ residual,
23
+ weight,
24
+ bias,
25
+ dropout_p,
26
+ epsilon,
27
+ rowscale=None,
28
+ layerscale=None,
29
+ prenorm=False,
30
+ residual_in_fp32=False,
31
+ return_dropout_mask=False,
32
+ ):
33
+ """residual_in_fp32 only has an effect if residual is None.
34
+ Otherwise residual dtype is residual.dtype.
35
+ """
36
+ return DropoutAddLayerNormFn.apply(
37
+ x0,
38
+ residual,
39
+ weight,
40
+ bias,
41
+ rowscale,
42
+ layerscale,
43
+ dropout_p,
44
+ epsilon,
45
+ residual_in_fp32,
46
+ prenorm,
47
+ True,
48
+ return_dropout_mask,
49
+ )
50
+
51
+
52
+ def dropout_add_rms_norm_subset(
53
+ x0,
54
+ residual,
55
+ weight,
56
+ bias,
57
+ dropout_p,
58
+ epsilon,
59
+ layerscale=None,
60
+ x0_subset=None,
61
+ out_subset=None,
62
+ rowscale_const=1.0,
63
+ out_numrows=0,
64
+ prenorm=False,
65
+ residual_in_fp32=False,
66
+ return_dropout_mask=False,
67
+ ):
68
+ """residual_in_fp32 only has an effect if residual is None.
69
+ Otherwise residual dtype is residual.dtype.
70
+ """
71
+ return DropoutAddLayerNormSubsetFn.apply(
72
+ x0,
73
+ residual,
74
+ weight,
75
+ bias,
76
+ layerscale,
77
+ x0_subset,
78
+ out_subset,
79
+ dropout_p,
80
+ epsilon,
81
+ rowscale_const,
82
+ out_numrows,
83
+ residual_in_fp32,
84
+ prenorm,
85
+ True,
86
+ return_dropout_mask,
87
+ )
88
+
89
+
90
+ def dropout_add_rms_norm_parallel_residual(
91
+ x0,
92
+ x1,
93
+ residual,
94
+ weight0,
95
+ bias0,
96
+ weight1,
97
+ bias1,
98
+ dropout_p,
99
+ epsilon,
100
+ prenorm=False,
101
+ residual_in_fp32=False,
102
+ return_dropout_mask=False,
103
+ ):
104
+ """residual_in_fp32 only has an effect if residual is None.
105
+ Otherwise residual dtype is residual.dtype.
106
+ """
107
+ return DropoutAddLayerNormParallelResidualFn.apply(
108
+ x0,
109
+ x1,
110
+ residual,
111
+ weight0,
112
+ bias0,
113
+ weight1,
114
+ bias1,
115
+ dropout_p,
116
+ epsilon,
117
+ residual_in_fp32,
118
+ prenorm,
119
+ True,
120
+ return_dropout_mask,
121
+ )
122
+
123
+
124
+ class RMSNorm(torch.nn.Module):
125
+ def __init__(self, hidden_size, eps=1e-5, device=None, dtype=None):
126
+ factory_kwargs = {"device": device, "dtype": dtype}
127
+ super().__init__()
128
+ self.eps = eps
129
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
130
+ self.register_parameter("bias", None)
131
+ self.reset_parameters()
132
+
133
+ def reset_parameters(self):
134
+ init.ones_(self.weight)
135
+
136
+ def forward(self, x):
137
+ return rms_norm(x, self.weight, self.eps)
138
+
139
+
140
+ class DropoutAddRMSNorm(torch.nn.Module):
141
+ def __init__(
142
+ self,
143
+ hidden_size,
144
+ prenorm=False,
145
+ p=0.0,
146
+ eps=1e-5,
147
+ residual_in_fp32=False,
148
+ device=None,
149
+ dtype=None,
150
+ ):
151
+ factory_kwargs = {"device": device, "dtype": dtype}
152
+ super().__init__()
153
+ self.prenorm = prenorm
154
+ self.p = p
155
+ self.eps = eps
156
+ self.residual_in_fp32 = residual_in_fp32
157
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
158
+ self.register_parameter("bias", None)
159
+ self.reset_parameters()
160
+
161
+ def reset_parameters(self):
162
+ init.ones_(self.weight)
163
+
164
+ def forward(self, x0, residual=None):
165
+ return dropout_add_rms_norm(
166
+ x0,
167
+ residual,
168
+ self.weight,
169
+ None,
170
+ self.p if self.training else 0.0,
171
+ self.eps,
172
+ prenorm=self.prenorm,
173
+ residual_in_fp32=self.residual_in_fp32,
174
+ )
build/torch211-cxx11-cu126-aarch64-linux/ops/triton/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
build/torch211-cxx11-cu126-aarch64-linux/ops/triton/cross_entropy.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ from typing import Tuple, Optional, Union
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+ import triton
9
+ import triton.language as tl
10
+
11
+ # `all_gather_into_tensor` and `reduce_scatter_tensor` are new placeholders for
12
+ # `_all_gather_base` and `_reduce_scatter_base`. They require the most recent
13
+ # version of PyTorch. The following 2 lines are for backward compatibility with
14
+ # older PyTorch.
15
+ if "all_gather_into_tensor" not in dir(torch.distributed):
16
+ torch.distributed.all_gather_into_tensor = torch.distributed._all_gather_base
17
+
18
+
19
+ @triton.heuristics(
20
+ {
21
+ "HAS_SMOOTHING": lambda args: args["smoothing"] > 0.0,
22
+ }
23
+ )
24
+ @triton.jit
25
+ def cross_entropy_fwd_kernel(
26
+ loss_ptr, # data ptrs
27
+ lse_ptr,
28
+ z_loss_ptr,
29
+ logits_ptr,
30
+ labels_ptr,
31
+ smoothing,
32
+ logit_scale,
33
+ lse_square_scale,
34
+ ignore_index,
35
+ total_classes,
36
+ class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes
37
+ n_cols, # shapes
38
+ logits_row_stride, # strides
39
+ BLOCK_SIZE: tl.constexpr,
40
+ HAS_SMOOTHING: tl.constexpr,
41
+ # if SPLIT (e.g. tensor parallel), don't include the LSE in the loss since it's not the final LSE
42
+ SPLIT: tl.constexpr,
43
+ PRECOMPUTED_LSE: tl.constexpr, # If LSE is already computed (also no smoothing and logit_scale == 1.0)
44
+ ):
45
+ row_idx = tl.program_id(0)
46
+ logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64)
47
+ sum_logits = 0.0 # For smoothing
48
+ if not PRECOMPUTED_LSE:
49
+ # Statistics for online softmax
50
+ m_i = -float("inf")
51
+ l_i = 0.0
52
+ for col_offset in range(0, n_cols, BLOCK_SIZE):
53
+ cols = col_offset + tl.arange(0, BLOCK_SIZE)
54
+ logits = tl.load(logits_ptr + cols, mask=cols < n_cols, other=-float("inf")).to(
55
+ tl.float32
56
+ ) * logit_scale
57
+ if HAS_SMOOTHING:
58
+ sum_logits += tl.sum(tl.where(cols < n_cols, logits, 0.0))
59
+ m_i_new = tl.maximum(m_i, tl.max(logits))
60
+ l_i = tl.exp(m_i - m_i_new) * l_i + tl.sum(tl.exp(logits - m_i_new))
61
+ m_i = m_i_new
62
+ lse = tl.log(l_i) + m_i
63
+ tl.store(lse_ptr + row_idx, lse)
64
+ else:
65
+ lse = tl.load(lse_ptr + row_idx)
66
+ label_idx = tl.load(labels_ptr + row_idx)
67
+ if label_idx == ignore_index:
68
+ loss = 0.0
69
+ z_loss = 0.0
70
+ else:
71
+ label_idx -= class_start_idx
72
+ if label_idx >= 0 and label_idx < n_cols:
73
+ logits_label = tl.load(logits_ptr + label_idx) * logit_scale
74
+ if HAS_SMOOTHING:
75
+ loss = (
76
+ (lse if not SPLIT else 0.0)
77
+ - smoothing * sum_logits / total_classes
78
+ - (1 - smoothing) * logits_label
79
+ )
80
+ else:
81
+ loss = (lse if not SPLIT else 0.0) - logits_label
82
+ else:
83
+ # If label is out of bounds, we set the CE loss to 0.0. But we still want the smoothing loss
84
+ if HAS_SMOOTHING:
85
+ loss = smoothing * ((lse if not SPLIT else 0.0) - sum_logits / total_classes)
86
+ else:
87
+ loss = 0.0
88
+ if not SPLIT:
89
+ z_loss = lse_square_scale * lse * lse
90
+ loss += z_loss
91
+ else:
92
+ z_loss = 0.0
93
+ tl.store(loss_ptr + row_idx, loss)
94
+ if not SPLIT:
95
+ tl.store(z_loss_ptr + row_idx, z_loss)
96
+
97
+
98
+ @triton.heuristics(
99
+ {
100
+ "HAS_SMOOTHING": lambda args: args["smoothing"] > 0.0,
101
+ }
102
+ )
103
+ @triton.jit
104
+ def cross_entropy_bwd_kernel(
105
+ dlogits_ptr, # data ptrs
106
+ dloss_ptr,
107
+ logits_ptr,
108
+ lse_ptr,
109
+ labels_ptr,
110
+ smoothing,
111
+ logit_scale,
112
+ lse_square_scale,
113
+ ignore_index,
114
+ total_classes,
115
+ class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes
116
+ n_cols, # shapes
117
+ logits_row_stride, # strides
118
+ dlogits_row_stride,
119
+ dloss_row_stride,
120
+ BLOCK_SIZE: tl.constexpr,
121
+ HAS_SMOOTHING: tl.constexpr,
122
+ ):
123
+ row_idx = tl.program_id(0)
124
+ col_block_idx = tl.program_id(1)
125
+ logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64)
126
+ dlogits_ptr = dlogits_ptr + row_idx * dlogits_row_stride.to(tl.int64)
127
+ col_offsets = col_block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
128
+ label_idx = tl.load(labels_ptr + row_idx)
129
+ if label_idx != ignore_index:
130
+ dloss = tl.load(dloss_ptr + row_idx * dloss_row_stride)
131
+ else:
132
+ dloss = 0.0
133
+ logits = tl.load(logits_ptr + col_offsets, mask=col_offsets < n_cols, other=-float("inf")).to(
134
+ tl.float32
135
+ ) * logit_scale
136
+ lse = tl.load(lse_ptr + row_idx)
137
+ probs = tl.exp(logits - lse)
138
+ probs += 2.0 * lse_square_scale * lse * probs
139
+ label_idx -= class_start_idx
140
+ if HAS_SMOOTHING:
141
+ smooth_positive = 1.0 - smoothing
142
+ smooth_negative = smoothing / total_classes
143
+ probs = tl.where(col_offsets == label_idx, probs - smooth_positive, probs) - smooth_negative
144
+ else:
145
+ probs = tl.where(col_offsets == label_idx, probs - 1.0, probs)
146
+ tl.store(dlogits_ptr + col_offsets, (dloss * logit_scale) * probs, mask=col_offsets < n_cols)
147
+
148
+
149
+ class CrossEntropyLoss(torch.autograd.Function):
150
+
151
+ @staticmethod
152
+ def forward(
153
+ ctx,
154
+ logits,
155
+ labels,
156
+ precomputed_lse=None,
157
+ smoothing=0.0,
158
+ logit_scale=1.0,
159
+ lse_square_scale=0.0,
160
+ ignore_index=-100,
161
+ inplace_backward=False,
162
+ process_group=None,
163
+ ):
164
+ # For some reason Triton generates wrong code when labels has dtype long and its address
165
+ # is not aligned to 16 bytes. The ld.global.b64 seems to load the wrong label index.
166
+ if labels.dtype == torch.long and labels.data_ptr() % 16 != 0:
167
+ labels = F.pad(labels, (0, 1))[..., :-1]
168
+ assert labels.data_ptr() % 16 == 0
169
+ assert logit_scale > 0.0
170
+ n_rows, n_cols = logits.shape
171
+ assert labels.shape == (n_rows,)
172
+ world_size = 1 if process_group is None else torch.distributed.get_world_size(process_group)
173
+ total_classes = world_size * n_cols
174
+ rank = 0 if process_group is None else torch.distributed.get_rank(process_group)
175
+ class_start_idx = rank * n_cols
176
+ use_precomputed_lse = precomputed_lse is not None and logit_scale == 1.0 and smoothing == 0.0
177
+
178
+ if logits.stride(-1) != 1:
179
+ logits = logits.contiguous()
180
+ MAX_BLOCK_SIZE = 16 * 1024
181
+ BLOCK_SIZE = min(triton.next_power_of_2(n_cols), MAX_BLOCK_SIZE)
182
+ num_warps = (
183
+ 4
184
+ if BLOCK_SIZE < 2048
185
+ else (8 if BLOCK_SIZE < 8192 else (16 if BLOCK_SIZE < 128 * 1024 else 32))
186
+ )
187
+ losses = torch.empty(n_rows, dtype=torch.float, device=logits.device)
188
+ if use_precomputed_lse:
189
+ assert precomputed_lse.shape == (n_rows,)
190
+ lse = precomputed_lse.contiguous()
191
+ else:
192
+ lse = torch.empty(n_rows, dtype=torch.float, device=logits.device)
193
+ z_losses = torch.empty(n_rows, dtype=torch.float, device=logits.device)
194
+ # Need this, otherwise Triton tries to launch from cuda:0 and we get
195
+ # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?)
196
+ with torch.cuda.device(logits.device.index):
197
+ cross_entropy_fwd_kernel[(n_rows,)](
198
+ losses, # data ptrs
199
+ lse,
200
+ z_losses,
201
+ logits,
202
+ labels,
203
+ smoothing,
204
+ logit_scale,
205
+ lse_square_scale,
206
+ ignore_index,
207
+ total_classes,
208
+ class_start_idx,
209
+ n_cols, # shapes
210
+ logits.stride(0), # strides
211
+ BLOCK_SIZE=BLOCK_SIZE, # constants
212
+ SPLIT=world_size > 1,
213
+ PRECOMPUTED_LSE=use_precomputed_lse,
214
+ num_warps=num_warps,
215
+ )
216
+
217
+ if world_size > 1:
218
+ # If there's no smoothing, if labels are in the vocab of this partition, losses contains
219
+ # - predicted logit, and 0 otherwise.
220
+ # If there's smoothing=0.1, for labels in the vocab of this partition, losses contains
221
+ # -0.9 * predicted logit - 0.1 * sum logit / total_classes.
222
+ # For labels not in the vocab of this partition, losses contains
223
+ # -0.1 * sum logit / total_classes.
224
+ if world_size > 1:
225
+ lse_allgather = torch.empty(world_size, n_rows, dtype=lse.dtype, device=lse.device)
226
+ torch.distributed.all_gather_into_tensor(lse_allgather, lse, group=process_group)
227
+ handle_losses = torch.distributed.all_reduce(
228
+ losses, op=torch.distributed.ReduceOp.SUM, group=process_group, async_op=True
229
+ )
230
+ lse = torch.logsumexp(lse_allgather, dim=0)
231
+ handle_losses.wait()
232
+ # After the allreduce, if there's no smoothing, the total losses are - predicted_logit,
233
+ # we just have to add the (global) lse.
234
+ # If there's smoothing=0.1, the total losses are
235
+ # -0.9 * predicted_logit - 0.1 * sum logit / total_classes.
236
+ # Again, we just have to add the (global) lse.
237
+ losses += lse
238
+ if lse_square_scale != 0.0:
239
+ z_losses = lse_square_scale * lse.square()
240
+ z_losses.masked_fill_(labels == ignore_index, 0.0)
241
+ losses += z_losses
242
+ else:
243
+ z_losses = torch.zeros_like(losses)
244
+ losses.masked_fill_(labels == ignore_index, 0.0)
245
+
246
+ ctx.save_for_backward(logits, lse, labels)
247
+ ctx.mark_non_differentiable(z_losses)
248
+ ctx.smoothing = smoothing
249
+ ctx.logit_scale = logit_scale
250
+ ctx.lse_square_scale = lse_square_scale
251
+ ctx.ignore_index = ignore_index
252
+ ctx.total_classes = total_classes
253
+ ctx.class_start_idx = class_start_idx
254
+ ctx.inplace_backward = inplace_backward
255
+ return losses, z_losses
256
+
257
+ @staticmethod
258
+ def backward(ctx, grad_losses, grad_z_losses):
259
+ del grad_z_losses # z_losses are only for logging.
260
+
261
+ logits, lse, labels = ctx.saved_tensors
262
+ dlogits = logits if ctx.inplace_backward else torch.empty_like(logits)
263
+ n_rows, n_cols = logits.shape
264
+ BLOCK_SIZE = min(triton.next_power_of_2(n_cols), 4 * 1024)
265
+ num_warps = 4 if BLOCK_SIZE < 2048 else (8 if BLOCK_SIZE < 8192 else 16)
266
+ grid = lambda META: (n_rows, triton.cdiv(n_cols, META["BLOCK_SIZE"])) # noqa
267
+ # Need this, otherwise Triton tries to launch from cuda:0 and we get
268
+ # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?)
269
+ with torch.cuda.device(logits.device.index):
270
+ cross_entropy_bwd_kernel[grid](
271
+ dlogits, # data ptrs
272
+ grad_losses,
273
+ logits,
274
+ lse,
275
+ labels,
276
+ ctx.smoothing,
277
+ ctx.logit_scale,
278
+ ctx.lse_square_scale,
279
+ ctx.ignore_index,
280
+ ctx.total_classes,
281
+ ctx.class_start_idx,
282
+ n_cols, # shapes
283
+ logits.stride(0), # strides
284
+ dlogits.stride(0),
285
+ grad_losses.stride(0),
286
+ BLOCK_SIZE=BLOCK_SIZE, # constants
287
+ num_warps=num_warps,
288
+ )
289
+ return dlogits, None, None, None, None, None, None, None, None, None
290
+
291
+
292
+ def cross_entropy_loss(
293
+ logits: torch.Tensor,
294
+ labels: torch.Tensor,
295
+ precomputed_lse: Optional[torch.Tensor] = None,
296
+ label_smoothing: float = 0.0,
297
+ logit_scale: float = 1.0,
298
+ lse_square_scale: float = 0.0,
299
+ ignore_index=-100,
300
+ inplace_backward: bool = False,
301
+ process_group=None,
302
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
303
+ """
304
+ Arguments:
305
+ logits: (batch, vocab_size)
306
+ labels: (batch,)
307
+ label_smoothing: float
308
+ logit_scale: float. Multiply logits by this scale before calculating the loss.
309
+ lse_square_scale: float. If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss.
310
+ This is also referred to as "z-loss".
311
+ ignore_index: int. If labels == ignore_index, the loss is set to 0.0.
312
+ inplace_backward: bool. If True, we do the backward pass in-place by modifying the logits.
313
+ This saves memory.
314
+ process_group: if not None, we're doing Tensor Parallel: each process is responsible for
315
+ one part of the vocab. The loss will be aggregated across processes.
316
+ Returns:
317
+ losses: (batch,), float
318
+ z_losses: (batch,), float
319
+ """
320
+ return CrossEntropyLoss.apply(
321
+ logits,
322
+ labels,
323
+ precomputed_lse,
324
+ label_smoothing,
325
+ logit_scale,
326
+ lse_square_scale,
327
+ ignore_index,
328
+ inplace_backward,
329
+ process_group,
330
+ )
build/torch211-cxx11-cu126-aarch64-linux/ops/triton/k_activations.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/facebookresearch/xformers/blob/main/xformers/triton/k_activations.py
2
+ # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ from enum import Enum
9
+ from typing import Optional
10
+
11
+ import triton
12
+ import triton.language as tl
13
+
14
+ _sqrt2pi = math.sqrt(2.0 / math.pi)
15
+ _sqrt1_2 = math.sqrt(1.0 / 2)
16
+ _gaussian_pdf_normalization = 1.0 / math.sqrt(2 * math.pi)
17
+
18
+
19
+ class Activation(str, Enum):
20
+ SquaredReLU = "squared_relu"
21
+ GeLU = "gelu"
22
+ GeLUApprox = "gelu_approx"
23
+ LeakyReLU = "leaky_relu"
24
+ ReLU = "relu"
25
+
26
+
27
+ def get_triton_activation_kernel(activation: Optional[Activation]):
28
+ return (
29
+ {
30
+ Activation.ReLU: relu,
31
+ Activation.LeakyReLU: leaky_relu,
32
+ Activation.GeLU: gelu,
33
+ Activation.GeLUApprox: gelu_approx,
34
+ Activation.SquaredReLU: squared_relu,
35
+ }[activation]
36
+ if activation
37
+ else None
38
+ )
39
+
40
+
41
+ def get_triton_activation_bwd_kernel(activation: Optional[Activation]):
42
+ return (
43
+ {
44
+ Activation.ReLU: relu_grad,
45
+ Activation.LeakyReLU: leaky_relu_grad,
46
+ Activation.GeLU: gelu_grad,
47
+ Activation.GeLUApprox: gelu_approx_grad,
48
+ Activation.SquaredReLU: squared_relu_grad,
49
+ }[activation]
50
+ if activation
51
+ else None
52
+ )
53
+
54
+
55
+ @triton.jit
56
+ def tanh(x):
57
+ # Tanh is just a scaled sigmoid
58
+ return 2 * tl.sigmoid(2 * x) - 1
59
+
60
+
61
+ @triton.jit
62
+ def cosh(x):
63
+ exp_x = tl.exp(x)
64
+ return (exp_x + 1.0 / exp_x) * 0.5
65
+
66
+
67
+ # a Triton implementation of the most used activations
68
+ # See for instance http://arxiv.org/abs/1606.08415 for an overview
69
+
70
+ # ReLU
71
+ @triton.jit
72
+ def relu(x):
73
+ """
74
+ ReLU_ activation function
75
+
76
+ .. _ReLU: https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html
77
+ """
78
+ zero = 0.0
79
+ return tl.where(x >= 0, x, zero.to(x.dtype))
80
+
81
+
82
+ @triton.jit
83
+ def relu_grad(x):
84
+ # ReLU is different from other activations
85
+ # in that it does not require the input to retrospectively compute its gradient
86
+ # here the input is the downstream gradient, and we return the upstream gradient directly
87
+ zero = 0.0
88
+ one = 1.0
89
+ return tl.where(x >= 0, one.to(x.dtype), zero.to(x.dtype))
90
+
91
+
92
+ @triton.jit
93
+ def squared_relu(x):
94
+ """
95
+ Squared ReLU activation, as proposed in the Primer_ paper.
96
+
97
+ .. _Primer: https://arxiv.org/abs/2109.08668
98
+ """
99
+ x_ = relu(x)
100
+ return (x_ * x_).to(x.dtype)
101
+
102
+
103
+ @triton.jit
104
+ def squared_relu_grad(x):
105
+ return tl.where(x >= 0, 2.0 * x, 0.0)
106
+
107
+
108
+ # Leaky ReLU
109
+ @triton.jit
110
+ def leaky_relu(x):
111
+ """
112
+ LeakyReLU_ activation
113
+
114
+ .. _LeakyReLU: https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html
115
+ """
116
+ scale = 0.01 + 0.0
117
+ scale = scale.to(x.dtype)
118
+ return tl.where(x >= 0, x, scale * x)
119
+
120
+
121
+ @triton.jit
122
+ def leaky_relu_grad(x):
123
+ min_grad = 0.01
124
+ max_grad = 1
125
+
126
+ min_grad = min_grad.to(x.dtype)
127
+ max_grad = max_grad.to(x.dtype)
128
+
129
+ return tl.where(x >= 0, max_grad, min_grad)
130
+
131
+
132
+ @triton.jit
133
+ def gelu(x):
134
+ """Gaussian Error Linear Unit (GELU)"""
135
+ return x * 0.5 * (1.0 + tl.libdevice.erf(x * _sqrt1_2))
136
+
137
+
138
+ @triton.jit
139
+ def gelu_grad(x):
140
+ cdf = 0.5 * (1.0 + tl.libdevice.erf(x * _sqrt1_2))
141
+ pdf = tl.exp(-0.5 * x * x) * _gaussian_pdf_normalization
142
+ return cdf + x * pdf
143
+
144
+
145
+ @triton.jit
146
+ def gelu_approx(x):
147
+ """
148
+ GeLU_ activation - Gaussian error linear unit, with tanh approximation
149
+
150
+ .. _GeLU: https://arxiv.org/pdf/1606.08415.pdf
151
+ """
152
+ return 0.5 * x * (1.0 + tanh(_sqrt2pi * x * (1.0 + 0.044715 * x * x)))
153
+
154
+
155
+ @triton.jit
156
+ def gelu_approx_grad(x):
157
+ # CREDITS: Fast implementation proposed in
158
+ # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/fused_bias_gelu.py#L30
159
+ tanh_out = tanh(0.79788456 * x * (1 + 0.044715 * x * x))
160
+ return 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (
161
+ 1 + tanh_out
162
+ )
build/torch211-cxx11-cu126-aarch64-linux/ops/triton/layer_norm.py ADDED
@@ -0,0 +1,1254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, Tri Dao.
2
+ # Implement dropout + residual + layer_norm / rms_norm.
3
+
4
+ # Based on the Triton LayerNorm tutorial: https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
5
+ # For the backward pass, we keep weight_grad and bias_grad in registers and accumulate.
6
+ # This is faster for dimensions up to 8k, but after that it's much slower due to register spilling.
7
+ # The models we train have hidden dim up to 8k anyway (e.g. Llama 70B), so this is fine.
8
+
9
+ import math
10
+ from typing import Optional, List
11
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from torch import Tensor
15
+
16
+ import triton
17
+ import triton.language as tl
18
+
19
+ from flash_attn.utils.torch import custom_fwd, custom_bwd
20
+ from flash_attn.utils.library import triton_op
21
+
22
+ from ..._ops import add_op_namespace_prefix
23
+
24
+
25
+ def maybe_contiguous_lastdim(x):
26
+ return x.contiguous() if x is not None and x.stride(-1) != 1 else x
27
+
28
+
29
+ def maybe_contiguous(x):
30
+ return x.contiguous() if x is not None else None
31
+
32
+
33
+ def triton_autotune_configs():
34
+ # Return configs with a valid warp count for the current device
35
+ configs = []
36
+ # Maximum threads per block is architecture-dependent in theory, but in reality all are 1024
37
+ max_threads_per_block = 1024
38
+ # Default to warp size 32 if not defined by device
39
+ warp_size = getattr(torch.cuda.get_device_properties(torch.cuda.current_device()), "warp_size", 32)
40
+ # Autotune for warp counts which are powers of 2 and do not exceed thread per block limit
41
+ return [triton.Config({}, num_warps=warp_count) for warp_count in [1, 2, 4, 8, 16, 32]
42
+ if warp_count * warp_size <= max_threads_per_block]
43
+ # return [triton.Config({}, num_warps=8)]
44
+
45
+
46
+ def layer_norm_ref(
47
+ x,
48
+ weight,
49
+ bias,
50
+ residual=None,
51
+ x1=None,
52
+ weight1=None,
53
+ bias1=None,
54
+ eps=1e-6,
55
+ dropout_p=0.0,
56
+ rowscale=None,
57
+ prenorm=False,
58
+ zero_centered_weight=False,
59
+ dropout_mask=None,
60
+ dropout_mask1=None,
61
+ upcast=False,
62
+ ):
63
+ dtype = x.dtype
64
+ if upcast:
65
+ x = x.float()
66
+ weight = weight.float()
67
+ bias = bias.float() if bias is not None else None
68
+ residual = residual.float() if residual is not None else residual
69
+ x1 = x1.float() if x1 is not None else None
70
+ weight1 = weight1.float() if weight1 is not None else None
71
+ bias1 = bias1.float() if bias1 is not None else None
72
+ if zero_centered_weight:
73
+ weight = weight + 1.0
74
+ if weight1 is not None:
75
+ weight1 = weight1 + 1.0
76
+ if x1 is not None:
77
+ assert rowscale is None, "rowscale is not supported with parallel LayerNorm"
78
+ if rowscale is not None:
79
+ x = x * rowscale[..., None]
80
+ if dropout_p > 0.0:
81
+ if dropout_mask is not None:
82
+ x = x.masked_fill(~dropout_mask, 0.0) / (1.0 - dropout_p)
83
+ else:
84
+ x = F.dropout(x, p=dropout_p)
85
+ if x1 is not None:
86
+ if dropout_mask1 is not None:
87
+ x1 = x1.masked_fill(~dropout_mask1, 0.0) / (1.0 - dropout_p)
88
+ else:
89
+ x1 = F.dropout(x1, p=dropout_p)
90
+ if x1 is not None:
91
+ x = x + x1
92
+ if residual is not None:
93
+ x = (x + residual).to(x.dtype)
94
+ out = F.layer_norm(x.to(weight.dtype), x.shape[-1:], weight=weight, bias=bias, eps=eps).to(
95
+ dtype
96
+ )
97
+ if weight1 is None:
98
+ return out if not prenorm else (out, x)
99
+ else:
100
+ out1 = F.layer_norm(
101
+ x.to(weight1.dtype), x.shape[-1:], weight=weight1, bias=bias1, eps=eps
102
+ ).to(dtype)
103
+ return (out, out1) if not prenorm else (out, out1, x)
104
+
105
+
106
+ def rms_norm_ref(
107
+ x,
108
+ weight,
109
+ bias,
110
+ residual=None,
111
+ x1=None,
112
+ weight1=None,
113
+ bias1=None,
114
+ eps=1e-6,
115
+ dropout_p=0.0,
116
+ rowscale=None,
117
+ prenorm=False,
118
+ zero_centered_weight=False,
119
+ dropout_mask=None,
120
+ dropout_mask1=None,
121
+ upcast=False,
122
+ ):
123
+ dtype = x.dtype
124
+ if upcast:
125
+ x = x.float()
126
+ weight = weight.float()
127
+ bias = bias.float() if bias is not None else None
128
+ residual = residual.float() if residual is not None else residual
129
+ x1 = x1.float() if x1 is not None else None
130
+ weight1 = weight1.float() if weight1 is not None else None
131
+ bias1 = bias1.float() if bias1 is not None else None
132
+ if zero_centered_weight:
133
+ weight = weight + 1.0
134
+ if weight1 is not None:
135
+ weight1 = weight1 + 1.0
136
+ if x1 is not None:
137
+ assert rowscale is None, "rowscale is not supported with parallel LayerNorm"
138
+ if rowscale is not None:
139
+ x = x * rowscale[..., None]
140
+ if dropout_p > 0.0:
141
+ if dropout_mask is not None:
142
+ x = x.masked_fill(~dropout_mask, 0.0) / (1.0 - dropout_p)
143
+ else:
144
+ x = F.dropout(x, p=dropout_p)
145
+ if x1 is not None:
146
+ if dropout_mask1 is not None:
147
+ x1 = x1.masked_fill(~dropout_mask1, 0.0) / (1.0 - dropout_p)
148
+ else:
149
+ x1 = F.dropout(x1, p=dropout_p)
150
+ if x1 is not None:
151
+ x = x + x1
152
+ if residual is not None:
153
+ x = (x + residual).to(x.dtype)
154
+ rstd = 1 / torch.sqrt((x.square()).mean(dim=-1, keepdim=True) + eps)
155
+ out = ((x * rstd * weight) + bias if bias is not None else (x * rstd * weight)).to(dtype)
156
+ if weight1 is None:
157
+ return out if not prenorm else (out, x)
158
+ else:
159
+ out1 = ((x * rstd * weight1) + bias1 if bias1 is not None else (x * rstd * weight1)).to(
160
+ dtype
161
+ )
162
+ return (out, out1) if not prenorm else (out, out1, x)
163
+
164
+
165
+ @triton.autotune(
166
+ configs=triton_autotune_configs(),
167
+ key=["N", "HAS_RESIDUAL", "STORE_RESIDUAL_OUT", "IS_RMS_NORM", "HAS_BIAS", "HAS_X1", "HAS_W1", "HAS_B1"],
168
+ )
169
+ # torch compile doesn't like triton.heuristics, so we set these manually when calling the kernel
170
+ # @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None})
171
+ # @triton.heuristics({"HAS_RESIDUAL": lambda args: args["RESIDUAL"] is not None})
172
+ # @triton.heuristics({"HAS_X1": lambda args: args["X1"] is not None})
173
+ # @triton.heuristics({"HAS_W1": lambda args: args["W1"] is not None})
174
+ # @triton.heuristics({"HAS_B1": lambda args: args["B1"] is not None})
175
+ @triton.jit
176
+ def _layer_norm_fwd_1pass_kernel(
177
+ X, # pointer to the input
178
+ Y, # pointer to the output
179
+ W, # pointer to the weights
180
+ B, # pointer to the biases
181
+ RESIDUAL, # pointer to the residual
182
+ X1,
183
+ W1,
184
+ B1,
185
+ Y1,
186
+ RESIDUAL_OUT, # pointer to the residual
187
+ ROWSCALE,
188
+ SEEDS, # Dropout seeds for each row
189
+ DROPOUT_MASK,
190
+ DROPOUT_MASK1,
191
+ Mean, # pointer to the mean
192
+ Rstd, # pointer to the 1/std
193
+ stride_x_row, # how much to increase the pointer when moving by 1 row
194
+ stride_y_row,
195
+ stride_res_row,
196
+ stride_res_out_row,
197
+ stride_x1_row,
198
+ stride_y1_row,
199
+ M, # number of rows in X
200
+ N, # number of columns in X
201
+ eps, # epsilon to avoid division by zero
202
+ dropout_p, # Dropout probability
203
+ zero_centered_weight, # If true, add 1.0 to the weight
204
+ IS_RMS_NORM: tl.constexpr,
205
+ BLOCK_N: tl.constexpr,
206
+ HAS_RESIDUAL: tl.constexpr,
207
+ STORE_RESIDUAL_OUT: tl.constexpr,
208
+ HAS_BIAS: tl.constexpr,
209
+ HAS_DROPOUT: tl.constexpr,
210
+ STORE_DROPOUT_MASK: tl.constexpr,
211
+ HAS_ROWSCALE: tl.constexpr,
212
+ HAS_X1: tl.constexpr,
213
+ HAS_W1: tl.constexpr,
214
+ HAS_B1: tl.constexpr,
215
+ ):
216
+ # Map the program id to the row of X and Y it should compute.
217
+ row = tl.program_id(0)
218
+ X += row * stride_x_row
219
+ Y += row * stride_y_row
220
+ if HAS_RESIDUAL:
221
+ RESIDUAL += row * stride_res_row
222
+ if STORE_RESIDUAL_OUT:
223
+ RESIDUAL_OUT += row * stride_res_out_row
224
+ if HAS_X1:
225
+ X1 += row * stride_x1_row
226
+ if HAS_W1:
227
+ Y1 += row * stride_y1_row
228
+ # Compute mean and variance
229
+ cols = tl.arange(0, BLOCK_N)
230
+ x = tl.load(X + cols, mask=cols < N, other=0.0).to(tl.float32)
231
+ if HAS_ROWSCALE:
232
+ rowscale = tl.load(ROWSCALE + row).to(tl.float32)
233
+ x *= rowscale
234
+ if HAS_DROPOUT:
235
+ # Compute dropout mask
236
+ # 7 rounds is good enough, and reduces register pressure
237
+ keep_mask = tl.rand(tl.load(SEEDS + row).to(tl.uint32), cols, n_rounds=7) > dropout_p
238
+ x = tl.where(keep_mask, x / (1.0 - dropout_p), 0.0)
239
+ if STORE_DROPOUT_MASK:
240
+ tl.store(DROPOUT_MASK + row * N + cols, keep_mask, mask=cols < N)
241
+ if HAS_X1:
242
+ x1 = tl.load(X1 + cols, mask=cols < N, other=0.0).to(tl.float32)
243
+ if HAS_ROWSCALE:
244
+ rowscale = tl.load(ROWSCALE + M + row).to(tl.float32)
245
+ x1 *= rowscale
246
+ if HAS_DROPOUT:
247
+ # Compute dropout mask
248
+ # 7 rounds is good enough, and reduces register pressure
249
+ keep_mask = (
250
+ tl.rand(tl.load(SEEDS + M + row).to(tl.uint32), cols, n_rounds=7) > dropout_p
251
+ )
252
+ x1 = tl.where(keep_mask, x1 / (1.0 - dropout_p), 0.0)
253
+ if STORE_DROPOUT_MASK:
254
+ tl.store(DROPOUT_MASK1 + row * N + cols, keep_mask, mask=cols < N)
255
+ x += x1
256
+ if HAS_RESIDUAL:
257
+ residual = tl.load(RESIDUAL + cols, mask=cols < N, other=0.0).to(tl.float32)
258
+ x += residual
259
+ if STORE_RESIDUAL_OUT:
260
+ tl.store(RESIDUAL_OUT + cols, x, mask=cols < N)
261
+ if not IS_RMS_NORM:
262
+ mean = tl.sum(x, axis=0) / N
263
+ tl.store(Mean + row, mean)
264
+ xbar = tl.where(cols < N, x - mean, 0.0)
265
+ var = tl.sum(xbar * xbar, axis=0) / N
266
+ else:
267
+ xbar = tl.where(cols < N, x, 0.0)
268
+ var = tl.sum(xbar * xbar, axis=0) / N
269
+ rstd = 1 / tl.sqrt(var + eps)
270
+ tl.store(Rstd + row, rstd)
271
+ # Normalize and apply linear transformation
272
+ mask = cols < N
273
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
274
+ if zero_centered_weight:
275
+ w += 1.0
276
+ if HAS_BIAS:
277
+ b = tl.load(B + cols, mask=mask).to(tl.float32)
278
+ x_hat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
279
+ y = x_hat * w + b if HAS_BIAS else x_hat * w
280
+ # Write output
281
+ tl.store(Y + cols, y, mask=mask)
282
+ if HAS_W1:
283
+ w1 = tl.load(W1 + cols, mask=mask).to(tl.float32)
284
+ if zero_centered_weight:
285
+ w1 += 1.0
286
+ if HAS_B1:
287
+ b1 = tl.load(B1 + cols, mask=mask).to(tl.float32)
288
+ y1 = x_hat * w1 + b1 if HAS_B1 else x_hat * w1
289
+ tl.store(Y1 + cols, y1, mask=mask)
290
+
291
+
292
+ def _layer_norm_fwd(
293
+ x: Tensor,
294
+ weight: Tensor,
295
+ bias: Tensor,
296
+ eps: float,
297
+ residual: Optional[Tensor] = None,
298
+ x1: Optional[Tensor] = None,
299
+ weight1: Optional[Tensor] = None,
300
+ bias1: Optional[Tensor] = None,
301
+ dropout_p: float = 0.0,
302
+ rowscale: Optional[Tensor] = None,
303
+ out_dtype: Optional[torch.dtype] = None,
304
+ residual_dtype: Optional[torch.dtype] = None,
305
+ zero_centered_weight: bool = False,
306
+ is_rms_norm: bool = False,
307
+ return_dropout_mask: bool = False,
308
+ out: Optional[Tensor] = None,
309
+ residual_out: Optional[Tensor] = None
310
+ ) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor):
311
+ # Need to wrap to handle the case where residual_out is a alias of x, which makes torch.library
312
+ # and torch.compile unhappy. Also allocate memory for out and residual_out if they are None
313
+ # so that _layer_norm_fwd_impl doesn't have to return them.
314
+ if out is None:
315
+ out = torch.empty_like(x, dtype=x.dtype if out_dtype is None else out_dtype)
316
+ if residual is not None:
317
+ residual_dtype = residual.dtype
318
+ if residual_out is None and (
319
+ residual is not None
320
+ or (residual_dtype is not None and residual_dtype != x.dtype)
321
+ or dropout_p > 0.0
322
+ or rowscale is not None
323
+ or x1 is not None
324
+ ):
325
+ residual_out = torch.empty_like(
326
+ x, dtype=residual_dtype if residual_dtype is not None else x.dtype
327
+ )
328
+ else:
329
+ residual_out = None
330
+ y1, mean, rstd, seeds, dropout_mask, dropout_mask1 = _layer_norm_fwd_impl(
331
+ x,
332
+ weight,
333
+ bias,
334
+ eps,
335
+ out,
336
+ residual=residual,
337
+ x1=x1,
338
+ weight1=weight1,
339
+ bias1=bias1,
340
+ dropout_p=dropout_p,
341
+ rowscale=rowscale,
342
+ zero_centered_weight=zero_centered_weight,
343
+ is_rms_norm=is_rms_norm,
344
+ return_dropout_mask=return_dropout_mask,
345
+ residual_out=residual_out,
346
+ )
347
+ # residual_out is None if residual is None and residual_dtype == input_dtype and dropout_p == 0.0
348
+ if residual_out is None:
349
+ residual_out = x
350
+ return out, y1, mean, rstd, residual_out, seeds, dropout_mask, dropout_mask1
351
+
352
+
353
+ # [2025-04-28] torch.library.triton_op ignores the schema argument, but here we need the schema
354
+ # since we're returning a tuple of tensors
355
+ @triton_op(add_op_namespace_prefix("layer_norm_fwd_impl"), mutates_args={"out", "residual_out"},
356
+ schema="(Tensor x, Tensor weight, Tensor bias, float eps, Tensor(a!) out, Tensor? residual, Tensor? x1, Tensor? weight1, Tensor? bias1, float dropout_p, Tensor? rowscale, bool zero_centered_weight, bool is_rms_norm, bool return_dropout_mask, Tensor(a!)? residual_out) -> (Tensor y1, Tensor mean, Tensor rstd, Tensor seeds, Tensor dropout_mask, Tensor dropout_mask1)")
357
+ def _layer_norm_fwd_impl(
358
+ x: Tensor,
359
+ weight: Tensor,
360
+ bias: Tensor,
361
+ eps: float,
362
+ out: Tensor,
363
+ residual: Optional[Tensor] = None,
364
+ x1: Optional[Tensor] = None,
365
+ weight1: Optional[Tensor] = None,
366
+ bias1: Optional[Tensor] = None,
367
+ dropout_p: float = 0.0,
368
+ rowscale: Optional[Tensor] = None,
369
+ zero_centered_weight: bool = False,
370
+ is_rms_norm: bool = False,
371
+ return_dropout_mask: bool = False,
372
+ residual_out: Optional[Tensor] = None
373
+ ) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor):
374
+ M, N = x.shape
375
+ assert x.stride(-1) == 1
376
+ if residual is not None:
377
+ assert residual.stride(-1) == 1
378
+ assert residual.shape == (M, N)
379
+ assert weight.shape == (N,)
380
+ assert weight.stride(-1) == 1
381
+ if bias is not None:
382
+ assert bias.stride(-1) == 1
383
+ assert bias.shape == (N,)
384
+ if x1 is not None:
385
+ assert x1.shape == x.shape
386
+ assert rowscale is None
387
+ assert x1.stride(-1) == 1
388
+ if weight1 is not None:
389
+ assert weight1.shape == (N,)
390
+ assert weight1.stride(-1) == 1
391
+ if bias1 is not None:
392
+ assert bias1.shape == (N,)
393
+ assert bias1.stride(-1) == 1
394
+ if rowscale is not None:
395
+ assert rowscale.is_contiguous()
396
+ assert rowscale.shape == (M,)
397
+ assert out.shape == x.shape
398
+ assert out.stride(-1) == 1
399
+ if residual_out is not None:
400
+ assert residual_out.shape == x.shape
401
+ assert residual_out.stride(-1) == 1
402
+ if weight1 is not None:
403
+ y1 = torch.empty_like(out)
404
+ assert y1.stride(-1) == 1
405
+ else:
406
+ y1 = None
407
+ mean = torch.empty((M,), dtype=torch.float32, device=x.device) if not is_rms_norm else None
408
+ rstd = torch.empty((M,), dtype=torch.float32, device=x.device)
409
+ if dropout_p > 0.0:
410
+ seeds = torch.randint(
411
+ 2**32, (M if x1 is None else 2 * M,), device=x.device, dtype=torch.int64
412
+ )
413
+ else:
414
+ seeds = None
415
+ if return_dropout_mask and dropout_p > 0.0:
416
+ dropout_mask = torch.empty(M, N, device=x.device, dtype=torch.bool)
417
+ if x1 is not None:
418
+ dropout_mask1 = torch.empty(M, N, device=x.device, dtype=torch.bool)
419
+ else:
420
+ dropout_mask1 = None
421
+ else:
422
+ dropout_mask, dropout_mask1 = None, None
423
+ # Less than 64KB per feature: enqueue fused kernel
424
+ MAX_FUSED_SIZE = 65536 // x.element_size()
425
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
426
+ if N > BLOCK_N:
427
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
428
+ with torch.cuda.device(x.device.index):
429
+ torch.library.wrap_triton(_layer_norm_fwd_1pass_kernel)[(M,)](
430
+ x,
431
+ out,
432
+ weight,
433
+ bias,
434
+ residual,
435
+ x1,
436
+ weight1,
437
+ bias1,
438
+ y1,
439
+ residual_out,
440
+ rowscale,
441
+ seeds,
442
+ dropout_mask,
443
+ dropout_mask1,
444
+ mean,
445
+ rstd,
446
+ x.stride(0),
447
+ out.stride(0),
448
+ residual.stride(0) if residual is not None else 0,
449
+ residual_out.stride(0) if residual_out is not None else 0,
450
+ x1.stride(0) if x1 is not None else 0,
451
+ y1.stride(0) if y1 is not None else 0,
452
+ M,
453
+ N,
454
+ eps,
455
+ dropout_p,
456
+ # Passing bool make torch inductor very unhappy since it then tries to compare to int_max
457
+ int(zero_centered_weight),
458
+ is_rms_norm,
459
+ BLOCK_N,
460
+ residual is not None,
461
+ residual_out is not None,
462
+ bias is not None,
463
+ dropout_p > 0.0,
464
+ dropout_mask is not None,
465
+ rowscale is not None,
466
+ HAS_X1=x1 is not None,
467
+ HAS_W1=weight1 is not None,
468
+ HAS_B1=bias1 is not None,
469
+ )
470
+ return y1, mean, rstd, seeds, dropout_mask, dropout_mask1
471
+
472
+
473
+ @triton.autotune(
474
+ configs=triton_autotune_configs(),
475
+ key=["N", "HAS_DRESIDUAL", "STORE_DRESIDUAL", "IS_RMS_NORM", "HAS_BIAS", "HAS_DROPOUT"],
476
+ )
477
+ # torch compile doesn't like triton.heuristics, so we set these manually when calling the kernel
478
+ # @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None})
479
+ # @triton.heuristics({"HAS_DRESIDUAL": lambda args: args["DRESIDUAL"] is not None})
480
+ # @triton.heuristics({"STORE_DRESIDUAL": lambda args: args["DRESIDUAL_IN"] is not None})
481
+ # @triton.heuristics({"HAS_ROWSCALE": lambda args: args["ROWSCALE"] is not None})
482
+ # @triton.heuristics({"HAS_DY1": lambda args: args["DY1"] is not None})
483
+ # @triton.heuristics({"HAS_DX1": lambda args: args["DX1"] is not None})
484
+ # @triton.heuristics({"HAS_B1": lambda args: args["DB1"] is not None})
485
+ # @triton.heuristics({"RECOMPUTE_OUTPUT": lambda args: args["Y"] is not None})
486
+ @triton.jit
487
+ def _layer_norm_bwd_kernel(
488
+ X, # pointer to the input
489
+ W, # pointer to the weights
490
+ B, # pointer to the biases
491
+ Y, # pointer to the output to be recomputed
492
+ DY, # pointer to the output gradient
493
+ DX, # pointer to the input gradient
494
+ DW, # pointer to the partial sum of weights gradient
495
+ DB, # pointer to the partial sum of biases gradient
496
+ DRESIDUAL,
497
+ W1,
498
+ DY1,
499
+ DX1,
500
+ DW1,
501
+ DB1,
502
+ DRESIDUAL_IN,
503
+ ROWSCALE,
504
+ SEEDS,
505
+ Mean, # pointer to the mean
506
+ Rstd, # pointer to the 1/std
507
+ stride_x_row, # how much to increase the pointer when moving by 1 row
508
+ stride_y_row,
509
+ stride_dy_row,
510
+ stride_dx_row,
511
+ stride_dres_row,
512
+ stride_dy1_row,
513
+ stride_dx1_row,
514
+ stride_dres_in_row,
515
+ M, # number of rows in X
516
+ N, # number of columns in X
517
+ eps, # epsilon to avoid division by zero
518
+ dropout_p,
519
+ zero_centered_weight,
520
+ rows_per_program,
521
+ IS_RMS_NORM: tl.constexpr,
522
+ BLOCK_N: tl.constexpr,
523
+ HAS_DRESIDUAL: tl.constexpr,
524
+ STORE_DRESIDUAL: tl.constexpr,
525
+ HAS_BIAS: tl.constexpr,
526
+ HAS_DROPOUT: tl.constexpr,
527
+ HAS_ROWSCALE: tl.constexpr,
528
+ HAS_DY1: tl.constexpr,
529
+ HAS_DX1: tl.constexpr,
530
+ HAS_B1: tl.constexpr,
531
+ RECOMPUTE_OUTPUT: tl.constexpr,
532
+ ):
533
+ # Map the program id to the elements of X, DX, and DY it should compute.
534
+ row_block_id = tl.program_id(0)
535
+ row_start = row_block_id * rows_per_program
536
+ # Do not early exit if row_start >= M, because we need to write DW and DB
537
+ cols = tl.arange(0, BLOCK_N)
538
+ mask = cols < N
539
+ X += row_start * stride_x_row
540
+ if HAS_DRESIDUAL:
541
+ DRESIDUAL += row_start * stride_dres_row
542
+ if STORE_DRESIDUAL:
543
+ DRESIDUAL_IN += row_start * stride_dres_in_row
544
+ DY += row_start * stride_dy_row
545
+ DX += row_start * stride_dx_row
546
+ if HAS_DY1:
547
+ DY1 += row_start * stride_dy1_row
548
+ if HAS_DX1:
549
+ DX1 += row_start * stride_dx1_row
550
+ if RECOMPUTE_OUTPUT:
551
+ Y += row_start * stride_y_row
552
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
553
+ if zero_centered_weight:
554
+ w += 1.0
555
+ if RECOMPUTE_OUTPUT and HAS_BIAS:
556
+ b = tl.load(B + cols, mask=mask, other=0.0).to(tl.float32)
557
+ if HAS_DY1:
558
+ w1 = tl.load(W1 + cols, mask=mask).to(tl.float32)
559
+ if zero_centered_weight:
560
+ w1 += 1.0
561
+ dw = tl.zeros((BLOCK_N,), dtype=tl.float32)
562
+ if HAS_BIAS:
563
+ db = tl.zeros((BLOCK_N,), dtype=tl.float32)
564
+ if HAS_DY1:
565
+ dw1 = tl.zeros((BLOCK_N,), dtype=tl.float32)
566
+ if HAS_B1:
567
+ db1 = tl.zeros((BLOCK_N,), dtype=tl.float32)
568
+ row_end = min((row_block_id + 1) * rows_per_program, M)
569
+ for row in range(row_start, row_end):
570
+ # Load data to SRAM
571
+ x = tl.load(X + cols, mask=mask, other=0).to(tl.float32)
572
+ dy = tl.load(DY + cols, mask=mask, other=0).to(tl.float32)
573
+ if HAS_DY1:
574
+ dy1 = tl.load(DY1 + cols, mask=mask, other=0).to(tl.float32)
575
+ if not IS_RMS_NORM:
576
+ mean = tl.load(Mean + row)
577
+ rstd = tl.load(Rstd + row)
578
+ # Compute dx
579
+ xhat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
580
+ xhat = tl.where(mask, xhat, 0.0)
581
+ if RECOMPUTE_OUTPUT:
582
+ y = xhat * w + b if HAS_BIAS else xhat * w
583
+ tl.store(Y + cols, y, mask=mask)
584
+ wdy = w * dy
585
+ dw += dy * xhat
586
+ if HAS_BIAS:
587
+ db += dy
588
+ if HAS_DY1:
589
+ wdy += w1 * dy1
590
+ dw1 += dy1 * xhat
591
+ if HAS_B1:
592
+ db1 += dy1
593
+ if not IS_RMS_NORM:
594
+ c1 = tl.sum(xhat * wdy, axis=0) / N
595
+ c2 = tl.sum(wdy, axis=0) / N
596
+ dx = (wdy - (xhat * c1 + c2)) * rstd
597
+ else:
598
+ c1 = tl.sum(xhat * wdy, axis=0) / N
599
+ dx = (wdy - xhat * c1) * rstd
600
+ if HAS_DRESIDUAL:
601
+ dres = tl.load(DRESIDUAL + cols, mask=mask, other=0).to(tl.float32)
602
+ dx += dres
603
+ # Write dx
604
+ if STORE_DRESIDUAL:
605
+ tl.store(DRESIDUAL_IN + cols, dx, mask=mask)
606
+ if HAS_DX1:
607
+ if HAS_DROPOUT:
608
+ keep_mask = (
609
+ tl.rand(tl.load(SEEDS + M + row).to(tl.uint32), cols, n_rounds=7) > dropout_p
610
+ )
611
+ dx1 = tl.where(keep_mask, dx / (1.0 - dropout_p), 0.0)
612
+ else:
613
+ dx1 = dx
614
+ tl.store(DX1 + cols, dx1, mask=mask)
615
+ if HAS_DROPOUT:
616
+ keep_mask = tl.rand(tl.load(SEEDS + row).to(tl.uint32), cols, n_rounds=7) > dropout_p
617
+ dx = tl.where(keep_mask, dx / (1.0 - dropout_p), 0.0)
618
+ if HAS_ROWSCALE:
619
+ rowscale = tl.load(ROWSCALE + row).to(tl.float32)
620
+ dx *= rowscale
621
+ tl.store(DX + cols, dx, mask=mask)
622
+
623
+ X += stride_x_row
624
+ if HAS_DRESIDUAL:
625
+ DRESIDUAL += stride_dres_row
626
+ if STORE_DRESIDUAL:
627
+ DRESIDUAL_IN += stride_dres_in_row
628
+ if RECOMPUTE_OUTPUT:
629
+ Y += stride_y_row
630
+ DY += stride_dy_row
631
+ DX += stride_dx_row
632
+ if HAS_DY1:
633
+ DY1 += stride_dy1_row
634
+ if HAS_DX1:
635
+ DX1 += stride_dx1_row
636
+ tl.store(DW + row_block_id * N + cols, dw, mask=mask)
637
+ if HAS_BIAS:
638
+ tl.store(DB + row_block_id * N + cols, db, mask=mask)
639
+ if HAS_DY1:
640
+ tl.store(DW1 + row_block_id * N + cols, dw1, mask=mask)
641
+ if HAS_B1:
642
+ tl.store(DB1 + row_block_id * N + cols, db1, mask=mask)
643
+
644
+
645
+ def _layer_norm_bwd(
646
+ dy: Tensor,
647
+ x: Tensor,
648
+ weight: Tensor,
649
+ bias: Tensor,
650
+ eps: float,
651
+ mean: Tensor,
652
+ rstd: Tensor,
653
+ dresidual: Optional[Tensor] = None,
654
+ dy1: Optional[Tensor] = None,
655
+ weight1: Optional[Tensor] = None,
656
+ bias1: Optional[Tensor] = None,
657
+ seeds: Optional[Tensor] = None,
658
+ dropout_p: float = 0.0,
659
+ rowscale: Optional[Tensor] = None,
660
+ has_residual: bool = False,
661
+ has_x1: bool = False,
662
+ zero_centered_weight: bool = False,
663
+ is_rms_norm: bool = False,
664
+ x_dtype: Optional[torch.dtype] = None,
665
+ recompute_output: bool = False,
666
+ ) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor):
667
+ # Need to wrap to handle the case where dresidual_in or dx1 are aliases of x,
668
+ # which makes torch.library unhappy
669
+ dx, dw, db, dresidual_in, dx1, dw1, db1, y = _layer_norm_bwd_impl(
670
+ dy,
671
+ x,
672
+ weight,
673
+ bias,
674
+ eps,
675
+ mean,
676
+ rstd,
677
+ dresidual,
678
+ dy1,
679
+ weight1,
680
+ bias1,
681
+ seeds,
682
+ dropout_p,
683
+ rowscale,
684
+ has_residual,
685
+ has_x1,
686
+ zero_centered_weight,
687
+ is_rms_norm,
688
+ x_dtype=x_dtype,
689
+ recompute_output=recompute_output,
690
+ )
691
+ # Don't need to compute dresidual_in separately in this case
692
+ if has_residual and dx.dtype == x.dtype and dropout_p == 0.0 and rowscale is None:
693
+ dresidual_in = dx
694
+ if has_x1 and dropout_p == 0.0:
695
+ dx1 = dx
696
+ return dx, dw, db, dresidual_in, dx1, dw1, db1, y
697
+
698
+
699
+
700
+ @triton_op(add_op_namespace_prefix("layer_norm_bwd_impl"), mutates_args={},
701
+ schema="(Tensor dy, Tensor x, Tensor weight, Tensor bias, float eps, Tensor mean, Tensor rstd, Tensor? dresidual, Tensor? dy1, Tensor? weight1, Tensor? bias1, Tensor? seeds, float dropout_p, Tensor? rowscale, bool has_residual, bool has_x1, bool zero_centered_weight, bool is_rms_norm, ScalarType? x_dtype, bool recompute_output) -> (Tensor dx, Tensor dw, Tensor db, Tensor dresidual_in, Tensor dx1, Tensor dw1, Tensor db1, Tensor y)",
702
+ allow_decomposition=False, # Don't let torch.compile trace inside
703
+ )
704
+ def _layer_norm_bwd_impl(
705
+ dy: Tensor,
706
+ x: Tensor,
707
+ weight: Tensor,
708
+ bias: Tensor,
709
+ eps: float,
710
+ mean: Tensor,
711
+ rstd: Tensor,
712
+ dresidual: Optional[Tensor] = None,
713
+ dy1: Optional[Tensor] = None,
714
+ weight1: Optional[Tensor] = None,
715
+ bias1: Optional[Tensor] = None,
716
+ seeds: Optional[Tensor] = None,
717
+ dropout_p: float = 0.0,
718
+ rowscale: Optional[Tensor] = None,
719
+ has_residual: bool = False,
720
+ has_x1: bool = False,
721
+ zero_centered_weight: bool = False,
722
+ is_rms_norm: bool = False,
723
+ x_dtype: Optional[torch.dtype] = None,
724
+ recompute_output: bool = False,
725
+ ) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor):
726
+ M, N = x.shape
727
+ assert x.stride(-1) == 1
728
+ dy = maybe_contiguous_lastdim(dy)
729
+ assert dy.stride(-1) == 1
730
+ assert dy.shape == (M, N)
731
+ if dresidual is not None:
732
+ dresidual = maybe_contiguous_lastdim(dresidual)
733
+ assert dresidual.stride(-1) == 1
734
+ assert dresidual.shape == (M, N)
735
+ assert weight.shape == (N,)
736
+ assert weight.stride(-1) == 1
737
+ if bias is not None:
738
+ assert bias.stride(-1) == 1
739
+ assert bias.shape == (N,)
740
+ if dy1 is not None:
741
+ dy1 = maybe_contiguous_lastdim(dy1)
742
+ assert weight1 is not None
743
+ assert dy1.shape == dy.shape
744
+ assert dy1.stride(-1) == 1
745
+ if weight1 is not None:
746
+ assert weight1.shape == (N,)
747
+ assert weight1.stride(-1) == 1
748
+ if bias1 is not None:
749
+ assert bias1.shape == (N,)
750
+ assert bias1.stride(-1) == 1
751
+ if seeds is not None:
752
+ assert seeds.is_contiguous()
753
+ assert seeds.shape == (M if not has_x1 else M * 2,)
754
+ if rowscale is not None:
755
+ assert rowscale.is_contiguous()
756
+ assert rowscale.shape == (M,)
757
+ # allocate output
758
+ dx = (
759
+ torch.empty_like(x)
760
+ if x_dtype is None
761
+ else torch.empty(M, N, dtype=x_dtype, device=x.device)
762
+ )
763
+ dresidual_in = (
764
+ torch.empty_like(x)
765
+ if has_residual
766
+ and (dx.dtype != x.dtype or dropout_p > 0.0 or rowscale is not None or has_x1)
767
+ else None
768
+ )
769
+ dx1 = torch.empty_like(dx) if (has_x1 and dropout_p > 0.0) else None
770
+ y = torch.empty(M, N, dtype=dy.dtype, device=dy.device) if recompute_output else None
771
+ if recompute_output:
772
+ assert weight1 is None, "recompute_output is not supported with parallel LayerNorm"
773
+
774
+ # Less than 64KB per feature: enqueue fused kernel
775
+ MAX_FUSED_SIZE = 65536 // x.element_size()
776
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
777
+ if N > BLOCK_N:
778
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
779
+ # Increasing the multiple (e.g. 8) will allow more thread blocks to be launched and hide the
780
+ # latency of the gmem reads/writes, but will increase the time of summing up dw / db.
781
+ sm_count = torch.cuda.get_device_properties(x.device).multi_processor_count * 8
782
+ _dw = torch.empty((sm_count, N), dtype=torch.float32, device=weight.device)
783
+ _db = (
784
+ torch.empty((sm_count, N), dtype=torch.float32, device=bias.device)
785
+ if bias is not None
786
+ else None
787
+ )
788
+ _dw1 = torch.empty_like(_dw) if weight1 is not None else None
789
+ _db1 = torch.empty_like(_db) if bias1 is not None else None
790
+ rows_per_program = math.ceil(M / sm_count)
791
+ grid = (sm_count,)
792
+ with torch.cuda.device(x.device.index):
793
+ torch.library.wrap_triton(_layer_norm_bwd_kernel)[grid](
794
+ x,
795
+ weight,
796
+ bias,
797
+ y,
798
+ dy,
799
+ dx,
800
+ _dw,
801
+ _db,
802
+ dresidual,
803
+ weight1,
804
+ dy1,
805
+ dx1,
806
+ _dw1,
807
+ _db1,
808
+ dresidual_in,
809
+ rowscale,
810
+ seeds,
811
+ mean,
812
+ rstd,
813
+ x.stride(0),
814
+ 0 if not recompute_output else y.stride(0),
815
+ dy.stride(0),
816
+ dx.stride(0),
817
+ dresidual.stride(0) if dresidual is not None else 0,
818
+ dy1.stride(0) if dy1 is not None else 0,
819
+ dx1.stride(0) if dx1 is not None else 0,
820
+ dresidual_in.stride(0) if dresidual_in is not None else 0,
821
+ M,
822
+ N,
823
+ eps,
824
+ dropout_p,
825
+ # Passing bool make torch inductor very unhappy since it then tries to compare to int_max
826
+ int(zero_centered_weight),
827
+ rows_per_program,
828
+ is_rms_norm,
829
+ BLOCK_N,
830
+ dresidual is not None,
831
+ dresidual_in is not None,
832
+ bias is not None,
833
+ dropout_p > 0.0,
834
+ HAS_ROWSCALE=rowscale is not None,
835
+ HAS_DY1=dy1 is not None,
836
+ HAS_DX1=dx1 is not None,
837
+ HAS_B1=bias1 is not None,
838
+ RECOMPUTE_OUTPUT=y is not None,
839
+ )
840
+ dw = _dw.sum(0).to(weight.dtype)
841
+ db = _db.sum(0).to(bias.dtype) if bias is not None else None
842
+ dw1 = _dw1.sum(0).to(weight1.dtype) if weight1 is not None else None
843
+ db1 = _db1.sum(0).to(bias1.dtype) if bias1 is not None else None
844
+ # dresidual_in and dx1 could be None, the wrapper will handle assigning them from dx
845
+ return dx, dw, db, dresidual_in, dx1, dw1, db1, y
846
+
847
+
848
+ class LayerNormFn(torch.autograd.Function):
849
+
850
+ @staticmethod
851
+ def forward(
852
+ ctx,
853
+ x,
854
+ weight,
855
+ bias,
856
+ residual=None,
857
+ x1=None,
858
+ weight1=None,
859
+ bias1=None,
860
+ eps=1e-6,
861
+ dropout_p=0.0,
862
+ rowscale=None,
863
+ prenorm=False,
864
+ residual_in_fp32=False,
865
+ zero_centered_weight=False,
866
+ is_rms_norm=False,
867
+ return_dropout_mask=False,
868
+ out_dtype=None,
869
+ out=None,
870
+ residual_out=None
871
+ ):
872
+ x_shape_og = x.shape
873
+ # reshape input data into 2D tensor
874
+ x = maybe_contiguous_lastdim(x.reshape(-1, x.shape[-1]))
875
+ if residual is not None:
876
+ assert residual.shape == x_shape_og
877
+ residual = maybe_contiguous_lastdim(residual.reshape(-1, residual.shape[-1]))
878
+ if x1 is not None:
879
+ assert x1.shape == x_shape_og
880
+ assert rowscale is None, "rowscale is not supported with parallel LayerNorm"
881
+ x1 = maybe_contiguous_lastdim(x1.reshape(-1, x1.shape[-1]))
882
+ weight = weight.contiguous()
883
+ bias = maybe_contiguous(bias)
884
+ weight1 = maybe_contiguous(weight1)
885
+ bias1 = maybe_contiguous(bias1)
886
+ if rowscale is not None:
887
+ rowscale = rowscale.reshape(-1).contiguous()
888
+ residual_dtype = (
889
+ residual.dtype
890
+ if residual is not None
891
+ else (torch.float32 if residual_in_fp32 else None)
892
+ )
893
+ if out is not None:
894
+ out = out.reshape(-1, out.shape[-1])
895
+ if residual_out is not None:
896
+ residual_out = residual_out.reshape(-1, residual_out.shape[-1])
897
+ y, y1, mean, rstd, residual_out, seeds, dropout_mask, dropout_mask1 = _layer_norm_fwd(
898
+ x,
899
+ weight,
900
+ bias,
901
+ eps,
902
+ residual,
903
+ x1,
904
+ weight1,
905
+ bias1,
906
+ dropout_p=dropout_p,
907
+ rowscale=rowscale,
908
+ out_dtype=out_dtype,
909
+ residual_dtype=residual_dtype,
910
+ zero_centered_weight=zero_centered_weight,
911
+ is_rms_norm=is_rms_norm,
912
+ return_dropout_mask=return_dropout_mask,
913
+ out=out,
914
+ residual_out=residual_out,
915
+ )
916
+ ctx.save_for_backward(
917
+ residual_out, weight, bias, weight1, bias1, rowscale, seeds, mean, rstd
918
+ )
919
+ ctx.x_shape_og = x_shape_og
920
+ ctx.eps = eps
921
+ ctx.dropout_p = dropout_p
922
+ ctx.is_rms_norm = is_rms_norm
923
+ ctx.has_residual = residual is not None
924
+ ctx.has_x1 = x1 is not None
925
+ ctx.prenorm = prenorm
926
+ ctx.x_dtype = x.dtype
927
+ ctx.zero_centered_weight = zero_centered_weight
928
+ y = y.reshape(x_shape_og)
929
+ y1 = y1.reshape(x_shape_og) if y1 is not None else None
930
+ residual_out = residual_out.reshape(x_shape_og) if residual_out is not None else None
931
+ dropout_mask = dropout_mask.reshape(x_shape_og) if dropout_mask is not None else None
932
+ dropout_mask1 = dropout_mask1.reshape(x_shape_og) if dropout_mask1 is not None else None
933
+ if not return_dropout_mask:
934
+ if weight1 is None:
935
+ return y if not prenorm else (y, residual_out)
936
+ else:
937
+ return (y, y1) if not prenorm else (y, y1, residual_out)
938
+ else:
939
+ if weight1 is None:
940
+ return (
941
+ (y, dropout_mask, dropout_mask1)
942
+ if not prenorm
943
+ else (y, residual_out, dropout_mask, dropout_mask1)
944
+ )
945
+ else:
946
+ return (
947
+ (y, y1, dropout_mask, dropout_mask1)
948
+ if not prenorm
949
+ else (y, y1, residual_out, dropout_mask, dropout_mask1)
950
+ )
951
+
952
+ @staticmethod
953
+ def backward(ctx, dy, *args):
954
+ x, weight, bias, weight1, bias1, rowscale, seeds, mean, rstd = ctx.saved_tensors
955
+ dy = dy.reshape(-1, dy.shape[-1])
956
+ if weight1 is not None:
957
+ dy1, args = args[0], args[1:]
958
+ dy1 = dy1.reshape(-1, dy1.shape[-1])
959
+ assert dy1.shape == x.shape
960
+ else:
961
+ dy1 = None
962
+ if ctx.prenorm:
963
+ dresidual = args[0]
964
+ dresidual = dresidual.reshape(-1, dresidual.shape[-1])
965
+ assert dresidual.shape == x.shape
966
+ else:
967
+ dresidual = None
968
+ dx, dw, db, dresidual_in, dx1, dw1, db1, _ = _layer_norm_bwd(
969
+ dy,
970
+ x,
971
+ weight,
972
+ bias,
973
+ ctx.eps,
974
+ mean,
975
+ rstd,
976
+ dresidual,
977
+ dy1,
978
+ weight1,
979
+ bias1,
980
+ seeds,
981
+ ctx.dropout_p,
982
+ rowscale,
983
+ ctx.has_residual,
984
+ ctx.has_x1,
985
+ ctx.zero_centered_weight,
986
+ ctx.is_rms_norm,
987
+ x_dtype=ctx.x_dtype,
988
+ recompute_output=False,
989
+ )
990
+ return (
991
+ dx.reshape(ctx.x_shape_og),
992
+ dw,
993
+ db,
994
+ dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
995
+ dx1.reshape(ctx.x_shape_og) if dx1 is not None else None,
996
+ dw1,
997
+ db1,
998
+ None,
999
+ None,
1000
+ None,
1001
+ None,
1002
+ None,
1003
+ None,
1004
+ None,
1005
+ None,
1006
+ None,
1007
+ None,
1008
+ None,
1009
+ )
1010
+
1011
+
1012
+ def layer_norm_fn(
1013
+ x,
1014
+ weight,
1015
+ bias,
1016
+ residual=None,
1017
+ x1=None,
1018
+ weight1=None,
1019
+ bias1=None,
1020
+ eps=1e-6,
1021
+ dropout_p=0.0,
1022
+ rowscale=None,
1023
+ prenorm=False,
1024
+ residual_in_fp32=False,
1025
+ zero_centered_weight=False,
1026
+ is_rms_norm=False,
1027
+ return_dropout_mask=False,
1028
+ out_dtype=None,
1029
+ out=None,
1030
+ residual_out=None
1031
+ ):
1032
+ return LayerNormFn.apply(
1033
+ x,
1034
+ weight,
1035
+ bias,
1036
+ residual,
1037
+ x1,
1038
+ weight1,
1039
+ bias1,
1040
+ eps,
1041
+ dropout_p,
1042
+ rowscale,
1043
+ prenorm,
1044
+ residual_in_fp32,
1045
+ zero_centered_weight,
1046
+ is_rms_norm,
1047
+ return_dropout_mask,
1048
+ out_dtype,
1049
+ out,
1050
+ residual_out
1051
+ )
1052
+
1053
+
1054
+ def rms_norm_fn(
1055
+ x,
1056
+ weight,
1057
+ bias,
1058
+ residual=None,
1059
+ x1=None,
1060
+ weight1=None,
1061
+ bias1=None,
1062
+ eps=1e-6,
1063
+ dropout_p=0.0,
1064
+ rowscale=None,
1065
+ prenorm=False,
1066
+ residual_in_fp32=False,
1067
+ zero_centered_weight=False,
1068
+ return_dropout_mask=False,
1069
+ out_dtype=None,
1070
+ out=None,
1071
+ residual_out=None
1072
+ ):
1073
+ return LayerNormFn.apply(
1074
+ x,
1075
+ weight,
1076
+ bias,
1077
+ residual,
1078
+ x1,
1079
+ weight1,
1080
+ bias1,
1081
+ eps,
1082
+ dropout_p,
1083
+ rowscale,
1084
+ prenorm,
1085
+ residual_in_fp32,
1086
+ zero_centered_weight,
1087
+ True,
1088
+ return_dropout_mask,
1089
+ out_dtype,
1090
+ out,
1091
+ residual_out
1092
+ )
1093
+
1094
+
1095
+ class RMSNorm(torch.nn.Module):
1096
+
1097
+ def __init__(self, hidden_size, eps=1e-5, dropout_p=0.0, zero_centered_weight=False,
1098
+ device=None, dtype=None):
1099
+ factory_kwargs = {"device": device, "dtype": dtype}
1100
+ super().__init__()
1101
+ self.eps = eps
1102
+ if dropout_p > 0.0:
1103
+ self.drop = torch.nn.Dropout(dropout_p)
1104
+ else:
1105
+ self.drop = None
1106
+ self.zero_centered_weight = zero_centered_weight
1107
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
1108
+ self.register_parameter("bias", None)
1109
+ self.reset_parameters()
1110
+
1111
+ def reset_parameters(self):
1112
+ if not self.zero_centered_weight:
1113
+ torch.nn.init.ones_(self.weight)
1114
+ else:
1115
+ torch.nn.init.zeros_(self.weight)
1116
+
1117
+ def forward(self, x, residual=None, prenorm=False, residual_in_fp32=False):
1118
+ return rms_norm_fn(
1119
+ x,
1120
+ self.weight,
1121
+ self.bias,
1122
+ residual=residual,
1123
+ eps=self.eps,
1124
+ dropout_p=self.drop.p if self.drop is not None and self.training else 0.0,
1125
+ prenorm=prenorm,
1126
+ residual_in_fp32=residual_in_fp32,
1127
+ zero_centered_weight=self.zero_centered_weight,
1128
+ )
1129
+
1130
+
1131
+ class LayerNormLinearFn(torch.autograd.Function):
1132
+
1133
+ @staticmethod
1134
+ @custom_fwd
1135
+ def forward(
1136
+ ctx,
1137
+ x,
1138
+ norm_weight,
1139
+ norm_bias,
1140
+ linear_weight,
1141
+ linear_bias,
1142
+ residual=None,
1143
+ eps=1e-6,
1144
+ prenorm=False,
1145
+ residual_in_fp32=False,
1146
+ is_rms_norm=False,
1147
+ ):
1148
+ x_shape_og = x.shape
1149
+ # reshape input data into 2D tensor
1150
+ x = maybe_contiguous_lastdim(x.reshape(-1, x.shape[-1]))
1151
+ if residual is not None:
1152
+ assert residual.shape == x_shape_og
1153
+ residual = maybe_contiguous_lastdim(residual.reshape(-1, residual.shape[-1]))
1154
+ norm_weight = norm_weight.contiguous()
1155
+ norm_bias = maybe_contiguous(norm_bias)
1156
+ residual_dtype = (
1157
+ residual.dtype
1158
+ if residual is not None
1159
+ else (torch.float32 if residual_in_fp32 else None)
1160
+ )
1161
+ y, _, mean, rstd, residual_out, *rest = _layer_norm_fwd(
1162
+ x,
1163
+ norm_weight,
1164
+ norm_bias,
1165
+ eps,
1166
+ residual,
1167
+ out_dtype=None if not torch.is_autocast_enabled() else torch.get_autocast_dtype("cuda"),
1168
+ residual_dtype=residual_dtype,
1169
+ is_rms_norm=is_rms_norm,
1170
+ )
1171
+ y = y.reshape(x_shape_og)
1172
+ dtype = torch.get_autocast_dtype("cuda") if torch.is_autocast_enabled() else y.dtype
1173
+ linear_weight = linear_weight.to(dtype)
1174
+ linear_bias = linear_bias.to(dtype) if linear_bias is not None else None
1175
+ out = F.linear(y.to(linear_weight.dtype), linear_weight, linear_bias)
1176
+ # We don't store y, will be recomputed in the backward pass to save memory
1177
+ ctx.save_for_backward(residual_out, norm_weight, norm_bias, linear_weight, mean, rstd)
1178
+ ctx.x_shape_og = x_shape_og
1179
+ ctx.eps = eps
1180
+ ctx.is_rms_norm = is_rms_norm
1181
+ ctx.has_residual = residual is not None
1182
+ ctx.prenorm = prenorm
1183
+ ctx.x_dtype = x.dtype
1184
+ ctx.linear_bias_is_none = linear_bias is None
1185
+ return out if not prenorm else (out, residual_out.reshape(x_shape_og))
1186
+
1187
+ @staticmethod
1188
+ @custom_bwd
1189
+ def backward(ctx, dout, *args):
1190
+ x, norm_weight, norm_bias, linear_weight, mean, rstd = ctx.saved_tensors
1191
+ dout = dout.reshape(-1, dout.shape[-1])
1192
+ dy = F.linear(dout, linear_weight.t())
1193
+ dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0)
1194
+ dy = maybe_contiguous_lastdim(dy)
1195
+ assert dy.shape == x.shape
1196
+ if ctx.prenorm:
1197
+ dresidual = args[0]
1198
+ dresidual = maybe_contiguous_lastdim(dresidual.reshape(-1, dresidual.shape[-1]))
1199
+ assert dresidual.shape == x.shape
1200
+ else:
1201
+ dresidual = None
1202
+ dx, dnorm_weight, dnorm_bias, dresidual_in, _, _, _, y = _layer_norm_bwd(
1203
+ dy,
1204
+ x,
1205
+ norm_weight,
1206
+ norm_bias,
1207
+ ctx.eps,
1208
+ mean,
1209
+ rstd,
1210
+ dresidual=dresidual,
1211
+ has_residual=ctx.has_residual,
1212
+ is_rms_norm=ctx.is_rms_norm,
1213
+ x_dtype=ctx.x_dtype,
1214
+ recompute_output=True,
1215
+ )
1216
+ dlinear_weight = torch.einsum("bo,bi->oi", dout, y)
1217
+ return (
1218
+ dx.reshape(ctx.x_shape_og),
1219
+ dnorm_weight,
1220
+ dnorm_bias,
1221
+ dlinear_weight,
1222
+ dlinear_bias,
1223
+ dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
1224
+ None,
1225
+ None,
1226
+ None,
1227
+ None,
1228
+ )
1229
+
1230
+
1231
+ def layer_norm_linear_fn(
1232
+ x,
1233
+ norm_weight,
1234
+ norm_bias,
1235
+ linear_weight,
1236
+ linear_bias,
1237
+ residual=None,
1238
+ eps=1e-6,
1239
+ prenorm=False,
1240
+ residual_in_fp32=False,
1241
+ is_rms_norm=False,
1242
+ ):
1243
+ return LayerNormLinearFn.apply(
1244
+ x,
1245
+ norm_weight,
1246
+ norm_bias,
1247
+ linear_weight,
1248
+ linear_bias,
1249
+ residual,
1250
+ eps,
1251
+ prenorm,
1252
+ residual_in_fp32,
1253
+ is_rms_norm,
1254
+ )
build/torch211-cxx11-cu126-aarch64-linux/ops/triton/linear.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/ELS-RD/kernl/blob/main/src/kernl/implementations/linear_layer.py
2
+ # and https://github.com/openai/triton/blob/master/python/triton/ops/matmul.py
3
+ from typing import Optional
4
+
5
+ import torch
6
+ import triton
7
+ import triton.language as tl
8
+ from triton.ops.matmul_perf_model import early_config_prune, estimate_matmul_time
9
+
10
+ from flash_attn.ops.triton.k_activations import (
11
+ gelu,
12
+ gelu_approx,
13
+ gelu_approx_grad,
14
+ gelu_grad,
15
+ squared_relu,
16
+ squared_relu_grad,
17
+ )
18
+
19
+ # CREDITS: Initially inspired by the Triton tutorial on matrix multiplications
20
+
21
+
22
+ def init_to_zero(name):
23
+ return lambda nargs: nargs[name].zero_()
24
+
25
+
26
+ def get_configs_io_bound():
27
+ configs = []
28
+ for num_stages in [2, 3, 4, 5, 6]:
29
+ for block_m in [16, 32]:
30
+ for block_k in [32, 64]:
31
+ for block_n in [32, 64, 128, 256]:
32
+ num_warps = 2 if block_n <= 64 else 4
33
+ configs.append(
34
+ triton.Config(
35
+ {
36
+ "BLOCK_M": block_m,
37
+ "BLOCK_N": block_n,
38
+ "BLOCK_K": block_k,
39
+ "SPLIT_K": 1,
40
+ },
41
+ num_stages=num_stages,
42
+ num_warps=num_warps,
43
+ )
44
+ )
45
+ # split_k not used
46
+ # for split_k in [2, 4, 8, 16]:
47
+ # configs.append(triton.Config(
48
+ # {'BLOCK_M': block_m, 'BLOCK_N': block_n, 'BLOCK_K': block_k, 'SPLIT_K': split_k},
49
+ # num_stages=num_stages, num_warps=num_warps, pre_hook=init_to_zero('C')))
50
+ return configs
51
+
52
+
53
+ @triton.autotune(
54
+ configs=[
55
+ triton.Config(
56
+ {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8
57
+ ),
58
+ triton.Config(
59
+ {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8
60
+ ),
61
+ triton.Config(
62
+ {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
63
+ ),
64
+ triton.Config(
65
+ {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
66
+ ),
67
+ triton.Config(
68
+ {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
69
+ ),
70
+ triton.Config(
71
+ {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
72
+ ),
73
+ triton.Config(
74
+ {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
75
+ ),
76
+ triton.Config(
77
+ {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
78
+ ),
79
+ triton.Config(
80
+ {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=5, num_warps=2
81
+ ),
82
+ # good for int8
83
+ triton.Config(
84
+ {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1},
85
+ num_stages=3,
86
+ num_warps=8,
87
+ ),
88
+ triton.Config(
89
+ {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1},
90
+ num_stages=3,
91
+ num_warps=8,
92
+ ),
93
+ triton.Config(
94
+ {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4
95
+ ),
96
+ triton.Config(
97
+ {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4
98
+ ),
99
+ triton.Config(
100
+ {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1},
101
+ num_stages=4,
102
+ num_warps=4,
103
+ ),
104
+ triton.Config(
105
+ {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
106
+ ),
107
+ triton.Config(
108
+ {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
109
+ ),
110
+ triton.Config(
111
+ {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
112
+ ),
113
+ triton.Config(
114
+ {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=5, num_warps=2
115
+ ),
116
+ ]
117
+ + get_configs_io_bound(),
118
+ key=["CACHE_KEY_M", "CACHE_KEY_N", "CACHE_KEY_K"],
119
+ prune_configs_by={
120
+ "early_config_prune": early_config_prune,
121
+ "perf_model": estimate_matmul_time,
122
+ "top_k": 10,
123
+ },
124
+ )
125
+ @triton.heuristics(
126
+ {
127
+ "EVEN_K": lambda args: args["K"] % (args["BLOCK_K"] * args["SPLIT_K"]) == 0,
128
+ }
129
+ )
130
+ @triton.jit
131
+ def kernel_fwd(
132
+ C, # Pointers to matrices
133
+ ACT_INPUT,
134
+ A,
135
+ B,
136
+ bias,
137
+ # Matrix dimensions
138
+ M,
139
+ N,
140
+ K,
141
+ CACHE_KEY_M,
142
+ CACHE_KEY_N,
143
+ CACHE_KEY_K,
144
+ # The stride variables represent how much to increase the ptr by when moving by 1
145
+ # element in a particular dimension. E.g. stride_am is how much to increase a_ptr
146
+ # by to get the element one row down (A has M rows)
147
+ stride_cm,
148
+ # stride_cn, # Assume that stride_cn == 1
149
+ stride_am,
150
+ stride_ak,
151
+ stride_bn,
152
+ stride_bk,
153
+ # Meta-parameters
154
+ BLOCK_M: tl.constexpr,
155
+ GROUP_M: tl.constexpr,
156
+ BLOCK_N: tl.constexpr,
157
+ BLOCK_K: tl.constexpr,
158
+ # split k not used, not performant with activation, kept because early_config_prune is expecting it
159
+ SPLIT_K: tl.constexpr,
160
+ EVEN_K: tl.constexpr,
161
+ A_ROWMAJOR: tl.constexpr,
162
+ B_COLMAJOR: tl.constexpr,
163
+ BIAS: tl.constexpr,
164
+ SAVE_ACT_INPUT: tl.constexpr,
165
+ ACTIVATION: tl.constexpr,
166
+ ):
167
+
168
+ """
169
+ Kernel for computing Out = activation(A x W + C)
170
+ - Input has shape (M, K)
171
+ - Weight has shape (K, N)
172
+ - Bias has shape (N,)
173
+ - Output has shape (M, N)
174
+ - ActInputs (optional) has shape (M, N)
175
+ 'ActInputs' optionally saves the A x W + C intermediate for backward computations
176
+ This kernel will consolidate over K
177
+ """
178
+
179
+ pid = tl.program_id(axis=0)
180
+
181
+ grid_m = (M + BLOCK_M - 1) // BLOCK_M
182
+ grid_n = (N + BLOCK_N - 1) // BLOCK_N
183
+ # re-order program ID for better L2 performance
184
+ width = GROUP_M * grid_n
185
+ group_id = pid // width
186
+ group_size = min(grid_m - group_id * GROUP_M, GROUP_M)
187
+ pid_m = group_id * GROUP_M + (pid % group_size)
188
+ pid_n = (pid % width) // (group_size)
189
+
190
+ # now compute the block that each program will go through
191
+ # rm (resp. rn) denotes a range of indices
192
+ # for rows (resp. col) of C
193
+ rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
194
+ rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
195
+ # trick to avoid masking on M and N axis
196
+ ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M)
197
+ rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N)
198
+ rk = tl.arange(0, BLOCK_K)
199
+
200
+ if A_ROWMAJOR:
201
+ A = A + (ram[:, None] * stride_am + rk[None, :])
202
+ else:
203
+ A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak)
204
+ if B_COLMAJOR:
205
+ B = B + (rk[:, None] + rbn[None, :] * stride_bn)
206
+ else:
207
+ B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn)
208
+
209
+ acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
210
+
211
+ for k in range(K, 0, -BLOCK_K):
212
+ if EVEN_K:
213
+ a = tl.load(A)
214
+ b = tl.load(B)
215
+ else:
216
+ a = tl.load(A, mask=rk[None, :] < k, other=0.0)
217
+ b = tl.load(B, mask=rk[:, None] < k, other=0.0)
218
+ acc += tl.dot(a, b)
219
+
220
+ if A_ROWMAJOR:
221
+ A += BLOCK_K
222
+ else:
223
+ A += BLOCK_K * stride_ak
224
+ if B_COLMAJOR:
225
+ B += BLOCK_K
226
+ else:
227
+ B += BLOCK_K * stride_bk
228
+
229
+ # Putting bias after the matmul (instead of before) is faster, idk why
230
+ if BIAS:
231
+ bias = tl.load(bias + rn, mask=rn < N, other=0.0).to(tl.float32)
232
+ acc += bias[None, :]
233
+
234
+ # optional: save the activation inputs
235
+ if SAVE_ACT_INPUT:
236
+ # act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :] * stride_cn
237
+ act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :]
238
+ tl.store(act_in_ptrs, acc)
239
+
240
+ # optional: fused activation (while the data is in shared memory)
241
+ if ACTIVATION == "gelu":
242
+ acc = gelu(acc)
243
+ elif ACTIVATION == "gelu_approx":
244
+ acc = gelu_approx(acc)
245
+ elif ACTIVATION == "squared_relu":
246
+ acc = squared_relu(acc)
247
+ # rematerialize rm and rn to save registers
248
+ rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
249
+ rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
250
+
251
+ # write back result
252
+ # C = C + rm[:, None] * stride_cm + rn[None, :] * stride_cn
253
+ C = C + rm[:, None] * stride_cm + rn[None, :]
254
+ mask = (rm < M)[:, None] & (rn < N)[None, :]
255
+ tl.store(C, acc)
256
+
257
+
258
+ def triton_linear_act(
259
+ x: torch.Tensor,
260
+ weight: torch.Tensor,
261
+ bias: Optional[torch.Tensor] = None,
262
+ activation: str = "id",
263
+ save_act_input: bool = False,
264
+ ) -> torch.Tensor:
265
+ """
266
+ Compute e = activation(x @ weight.T + bias).
267
+ This wrapper kicks the `kernel_fwd` Triton kernel
268
+ :param x: input tensor
269
+ :param weight: weight matrix
270
+ :param bias: an optional bias tensor
271
+ :param activation: Activation name. Needs to be a Triton kernel.
272
+ :param act_input: an optional tensor to save the activation inputs (for backward)
273
+ :return: result tensor
274
+ """
275
+ # if torch.is_autocast_enabled():
276
+ # dtype = torch.get_autocast_gpu_dtype()
277
+ # x, weight, bias = [a.to(dtype=dtype) for a in [x, weight, bias]]
278
+
279
+ assert activation in ["id", "gelu", "gelu_approx", "squared_relu"]
280
+
281
+ batch_shape, n = x.shape[:-1], x.shape[-1]
282
+ batch_dim = batch_shape.numel()
283
+ x_reshaped = x.reshape(batch_dim, n)
284
+
285
+ if x_reshaped.stride(0) > 1 and x_reshaped.stride(1) > 1:
286
+ x_reshaped = x_reshaped.contiguous()
287
+ if weight.stride(0) > 1 and weight.stride(1) > 1:
288
+ weight = weight.contiguous()
289
+ bias = bias.contiguous() if bias is not None else None
290
+
291
+ assert (
292
+ x.dtype == weight.dtype
293
+ ), f"Input and weight must have the same dtype, got {x.dtype} and {weight.dtype}"
294
+ if bias is not None:
295
+ assert (
296
+ x.dtype == bias.dtype
297
+ ), f"Input and bias must have the same dtype, got {x.dtype} and {bias.dtype}"
298
+ assert (
299
+ x_reshaped.shape[1] == weight.shape[1]
300
+ ), f"Incompatible dimensions: {x_reshaped.shape} - {weight.shape}"
301
+
302
+ assert (
303
+ bias is None or bias.shape[0] == weight.shape[0]
304
+ ), "Incompatible dimensions in between weight and bias"
305
+
306
+ M, K = x_reshaped.shape
307
+ N, K = weight.shape
308
+
309
+ output = torch.empty((M, N), device=x.device, dtype=x.dtype)
310
+ act_input = torch.empty_like(output) if save_act_input else None
311
+
312
+ # 1D launch kernel where each block gets its own program.
313
+ grid = lambda META: (triton.cdiv(M, META["BLOCK_M"]) * triton.cdiv(N, META["BLOCK_N"]),) # noqa
314
+
315
+ kernel_fwd[grid](
316
+ output,
317
+ act_input,
318
+ x_reshaped,
319
+ weight, # data ptrs
320
+ bias if bias is not None else x, # auto skip bias if not present
321
+ M, # shapes
322
+ N,
323
+ K,
324
+ M // 32, # key for triton cache (limit number of compilations)
325
+ N // 32,
326
+ K // 32,
327
+ stride_cm=output.stride(0), # strides
328
+ # stride_cn=output.stride(1),
329
+ stride_am=x_reshaped.stride(0),
330
+ stride_ak=x_reshaped.stride(1),
331
+ stride_bk=weight.stride(1),
332
+ stride_bn=weight.stride(0),
333
+ BIAS=bias is not None, # optional fused bias
334
+ SAVE_ACT_INPUT=save_act_input, # optional save activation inputs
335
+ ACTIVATION=activation, # optional fused activation
336
+ A_ROWMAJOR=x_reshaped.stride(1) == 1,
337
+ B_COLMAJOR=weight.stride(1) == 1,
338
+ GROUP_M=8, # speed optimization: group the programs
339
+ )
340
+
341
+ if not save_act_input:
342
+ return output.reshape(*batch_shape, output.shape[-1])
343
+ else:
344
+ return (
345
+ output.reshape(*batch_shape, output.shape[-1]),
346
+ act_input.reshape(*batch_shape, act_input.shape[-1]),
347
+ )
348
+
349
+
350
+ @triton.autotune(
351
+ configs=[
352
+ triton.Config(
353
+ {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8
354
+ ),
355
+ triton.Config(
356
+ {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8
357
+ ),
358
+ triton.Config(
359
+ {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
360
+ ),
361
+ triton.Config(
362
+ {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
363
+ ),
364
+ triton.Config(
365
+ {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
366
+ ),
367
+ triton.Config(
368
+ {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
369
+ ),
370
+ triton.Config(
371
+ {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
372
+ ),
373
+ triton.Config(
374
+ {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
375
+ ),
376
+ triton.Config(
377
+ {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=5, num_warps=2
378
+ ),
379
+ # good for int8
380
+ triton.Config(
381
+ {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1},
382
+ num_stages=3,
383
+ num_warps=8,
384
+ ),
385
+ triton.Config(
386
+ {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1},
387
+ num_stages=3,
388
+ num_warps=8,
389
+ ),
390
+ triton.Config(
391
+ {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4
392
+ ),
393
+ triton.Config(
394
+ {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4
395
+ ),
396
+ triton.Config(
397
+ {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1},
398
+ num_stages=4,
399
+ num_warps=4,
400
+ ),
401
+ triton.Config(
402
+ {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
403
+ ),
404
+ triton.Config(
405
+ {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
406
+ ),
407
+ triton.Config(
408
+ {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
409
+ ),
410
+ triton.Config(
411
+ {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=5, num_warps=2
412
+ ),
413
+ ]
414
+ + get_configs_io_bound(),
415
+ key=["CACHE_KEY_M", "CACHE_KEY_N", "CACHE_KEY_K"],
416
+ prune_configs_by={
417
+ "early_config_prune": early_config_prune,
418
+ "perf_model": estimate_matmul_time,
419
+ "top_k": 10,
420
+ },
421
+ )
422
+ @triton.heuristics(
423
+ {
424
+ "EVEN_K": lambda args: args["K"] % (args["BLOCK_K"] * args["SPLIT_K"]) == 0,
425
+ }
426
+ )
427
+ @triton.jit
428
+ def kernel_bwd(
429
+ C, # Pointers to matrices
430
+ ACT_INPUT,
431
+ A,
432
+ B,
433
+ # Matrix dimensions
434
+ M,
435
+ N,
436
+ K,
437
+ CACHE_KEY_M,
438
+ CACHE_KEY_N,
439
+ CACHE_KEY_K,
440
+ # The stride variables represent how much to increase the ptr by when moving by 1
441
+ # element in a particular dimension. E.g. stride_am is how much to increase a_ptr
442
+ # by to get the element one row down (A has M rows)
443
+ stride_cm,
444
+ # stride_cn, # Assume that stride_cn == 1
445
+ stride_am,
446
+ stride_ak,
447
+ stride_bk,
448
+ stride_bn,
449
+ # Meta-parameters
450
+ BLOCK_M: tl.constexpr,
451
+ GROUP_M: tl.constexpr,
452
+ BLOCK_N: tl.constexpr,
453
+ BLOCK_K: tl.constexpr,
454
+ # split k not used, not performant with activation, kept because early_config_prune is expecting it
455
+ SPLIT_K: tl.constexpr,
456
+ EVEN_K: tl.constexpr,
457
+ ACTIVATION: tl.constexpr,
458
+ ):
459
+
460
+ """
461
+ Kernel for computing Out = activation(A x W + C)
462
+ - Input has shape (M, K)
463
+ - Weight has shape (K, N)
464
+ - Output has shape (M, N)
465
+ - ActInputs (optional) has shape (M, N)
466
+ 'ActInputs' optionally saves the A x W + C intermediate for backward computations
467
+ This kernel will consolidate over K
468
+ """
469
+
470
+ pid = tl.program_id(axis=0)
471
+
472
+ grid_m = (M + BLOCK_M - 1) // BLOCK_M
473
+ grid_n = (N + BLOCK_N - 1) // BLOCK_N
474
+ # re-order program ID for better L2 performance
475
+ width = GROUP_M * grid_n
476
+ group_id = pid // width
477
+ group_size = min(grid_m - group_id * GROUP_M, GROUP_M)
478
+ pid_m = group_id * GROUP_M + (pid % group_size)
479
+ pid_n = (pid % width) // (group_size)
480
+
481
+ # now compute the block that each program will go through
482
+ # rm (resp. rn) denotes a range of indices
483
+ # for rows (resp. col) of C
484
+ rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
485
+ rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
486
+ # trick to avoid masking on M and N axis
487
+ ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M)
488
+ rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N)
489
+ rk = tl.arange(0, BLOCK_K)
490
+
491
+ A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak)
492
+ B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn)
493
+
494
+ acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
495
+
496
+ for k in range(K, 0, -BLOCK_K):
497
+ if EVEN_K:
498
+ a = tl.load(A)
499
+ b = tl.load(B)
500
+ else:
501
+ a = tl.load(A, mask=rk[None, :] < k, other=0.0)
502
+ b = tl.load(B, mask=rk[:, None] < k, other=0.0)
503
+ acc += tl.dot(a, b)
504
+
505
+ A += BLOCK_K * stride_ak
506
+ B += BLOCK_K * stride_bk
507
+
508
+ # optional: fused activation (while the data is in shared memory)
509
+ if ACTIVATION != "id":
510
+ act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :]
511
+ act_input = tl.load(act_in_ptrs).to(acc.dtype)
512
+ if ACTIVATION == "gelu":
513
+ acc *= gelu_grad(act_input)
514
+ elif ACTIVATION == "gelu_approx":
515
+ acc *= gelu_approx_grad(act_input)
516
+ elif ACTIVATION == "squared_relu":
517
+ acc *= squared_relu_grad(act_input)
518
+
519
+ # rematerialize rm and rn to save registers
520
+ rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
521
+ rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
522
+
523
+ # write back result
524
+ C = C + rm[:, None] * stride_cm + rn[None, :]
525
+ mask = (rm < M)[:, None] & (rn < N)[None, :]
526
+ tl.store(C, acc, mask=mask)
527
+
528
+
529
+ def triton_dgrad_act(
530
+ grad_output: torch.Tensor,
531
+ weight: torch.Tensor,
532
+ activation: str = "id",
533
+ act_input: Optional[torch.Tensor] = None,
534
+ ) -> torch.Tensor:
535
+ """
536
+ Compute e = activation(grad_output @ weight + bias).
537
+ This wrapper kicks the `kernel_fwd` Triton kernel
538
+ :param grad_output: input tensor
539
+ :param weight: weight matrix
540
+ :param activation: Activation name. Needs to be a Triton kernel.
541
+ :param act_input: an optional tensor to save the activation inputs (for backward)
542
+ :return: result tensor
543
+ """
544
+ assert activation in ["id", "gelu", "gelu_approx", "squared_relu"]
545
+
546
+ batch_shape, n = grad_output.shape[:-1], grad_output.shape[-1]
547
+ batch_dim = batch_shape.numel()
548
+ grad_output_reshaped = grad_output.reshape(batch_dim, n)
549
+
550
+ if grad_output_reshaped.stride(0) > 1 and grad_output_reshaped.stride(1) > 1:
551
+ grad_output_reshaped = grad_output_reshaped.contiguous()
552
+ if weight.stride(0) > 1 and weight.stride(1) > 1:
553
+ weight = weight.contiguous()
554
+
555
+ assert (
556
+ grad_output.dtype == weight.dtype
557
+ ), f"grad_output and weight must have the same dtype, got {grad_output.dtype} and {weight.dtype}"
558
+ assert (
559
+ grad_output_reshaped.shape[1] == weight.shape[0]
560
+ ), f"Incompatible dimensions: {grad_output_reshaped.shape} - {weight.shape}"
561
+ if activation != "id":
562
+ assert act_input is not None, f"act_input is required for activation {activation}"
563
+
564
+ # M, N, K in bwd are different from M, N, K in fwd
565
+ M, K = grad_output_reshaped.shape
566
+ K, N = weight.shape
567
+
568
+ grad_input = torch.empty((M, N), device=grad_output.device, dtype=grad_output.dtype)
569
+
570
+ # 1D launch kernel where each block gets its own program.
571
+ grid = lambda META: (triton.cdiv(M, META["BLOCK_M"]) * triton.cdiv(N, META["BLOCK_N"]),) # noqa
572
+
573
+ kernel_bwd[grid](
574
+ grad_input,
575
+ act_input,
576
+ grad_output_reshaped,
577
+ weight, # data ptrs
578
+ M, # shapes
579
+ N,
580
+ K,
581
+ M // 32, # key for triton cache (limit number of compilations)
582
+ N // 32,
583
+ K // 32,
584
+ stride_cm=grad_input.stride(0), # strides
585
+ # stride_cn=grad_input.stride(1),
586
+ stride_am=grad_output_reshaped.stride(0),
587
+ stride_ak=grad_output_reshaped.stride(1),
588
+ stride_bk=weight.stride(0),
589
+ stride_bn=weight.stride(1),
590
+ ACTIVATION=activation, # optional fused activation
591
+ GROUP_M=8, # speed optimization: group the programs
592
+ )
593
+
594
+ return grad_input.reshape(*batch_shape, grad_input.shape[-1])
build/torch211-cxx11-cu126-aarch64-linux/ops/triton/mlp.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The triton fused matmul + sqrelu is faster for fp16 but slower for bf16, compared
2
+ # to naive implementation.
3
+ import fused_dense_lib as fused_dense_cuda
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ from flash_attn.utils.torch import custom_fwd, custom_bwd
9
+ from flash_attn.ops.activations import sqrelu_bwd, sqrelu_fwd
10
+ from flash_attn.ops.triton.linear import triton_dgrad_act, triton_linear_act
11
+
12
+
13
+ class FusedDenseSqreluDenseFunc(torch.autograd.Function):
14
+ @staticmethod
15
+ @custom_fwd
16
+ def forward(ctx, x, weight1, bias1, weight2, bias2, checkpoint_lvl=0):
17
+ """checkpoint_lvl:
18
+ 0: no recomputation in the bwd
19
+ 1: recompute gelu_out in the bwd
20
+ 2: recompute act_input and gelu_out in the bwd
21
+ """
22
+ if torch.is_autocast_enabled():
23
+ dtype = torch.get_autocast_gpu_dtype()
24
+ x, weight1, bias1, weight2, bias2 = [
25
+ a.to(dtype=dtype) for a in [x, weight1, bias1, weight2, bias2]
26
+ ]
27
+ is_bf16 = x.dtype == torch.bfloat16
28
+ assert checkpoint_lvl in [0, 1, 2]
29
+ x = x.contiguous()
30
+ weight1 = weight1.contiguous()
31
+ bias1 = bias1.contiguous()
32
+ weight2 = weight2.contiguous()
33
+ bias2 = bias2.contiguous()
34
+ batch_shape, n = x.shape[:-1], x.shape[-1]
35
+ batch_dim = batch_shape.numel()
36
+ if is_bf16:
37
+ act_input = fused_dense_cuda.linear_bias_forward(
38
+ x.reshape(batch_dim, n), weight1, bias1
39
+ )
40
+ output1 = sqrelu_fwd(act_input)
41
+ else:
42
+ save_act_input = checkpoint_lvl != 2
43
+ result = triton_linear_act(
44
+ x.reshape(batch_dim, n),
45
+ weight1,
46
+ bias1,
47
+ activation="squared_relu",
48
+ save_act_input=save_act_input,
49
+ )
50
+ if save_act_input:
51
+ output1, act_input = result
52
+ else:
53
+ output1 = result
54
+ output2 = fused_dense_cuda.linear_bias_forward(output1, weight2, bias2)
55
+ ctx.checkpoint_lvl = checkpoint_lvl
56
+ if checkpoint_lvl == 0:
57
+ ctx.save_for_backward(x, weight1, bias1, weight2, act_input, output1)
58
+ elif checkpoint_lvl == 1:
59
+ ctx.save_for_backward(x, weight1, bias1, weight2, act_input)
60
+ elif checkpoint_lvl == 2:
61
+ ctx.save_for_backward(x, weight1, bias1, weight2)
62
+ return output2.reshape(*batch_shape, output2.shape[-1])
63
+
64
+ @staticmethod
65
+ @custom_bwd
66
+ def backward(ctx, grad_output):
67
+ grad_output = grad_output.contiguous()
68
+ checkpoint_lvl = ctx.checkpoint_lvl
69
+ x, weight1, bias1, weight2, *rest = ctx.saved_tensors
70
+ batch_shape, n = x.shape[:-1], x.shape[-1]
71
+ batch_dim = batch_shape.numel()
72
+ is_bf16 = x.dtype == torch.bfloat16
73
+ if checkpoint_lvl == 0:
74
+ act_input, output1 = rest
75
+ elif checkpoint_lvl == 1:
76
+ (act_input,) = rest
77
+ output1 = sqrelu_fwd(act_input)
78
+ elif checkpoint_lvl == 2:
79
+ if is_bf16:
80
+ act_input = fused_dense_cuda.linear_bias_forward(
81
+ x.reshape(batch_dim, n), weight1, bias1
82
+ )
83
+ output1 = sqrelu_fwd(act_input)
84
+ else:
85
+ output1, act_input = triton_linear_act(
86
+ x.reshape(batch_dim, n),
87
+ weight1,
88
+ bias1,
89
+ activation="squared_relu",
90
+ save_act_input=True,
91
+ )
92
+
93
+ if is_bf16:
94
+ grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1])
95
+ grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad(output1, grad_output)
96
+ grad_output1 = grad_output @ weight2
97
+ grad_act_input = sqrelu_bwd(grad_output1, act_input)
98
+ grad_input, grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_backward(
99
+ x.reshape(batch_dim, n), weight1, grad_act_input
100
+ )
101
+ else:
102
+ grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1])
103
+ grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad(output1, grad_output)
104
+ grad_act_input = triton_dgrad_act(
105
+ grad_output, weight2, activation="squared_relu", act_input=act_input
106
+ )
107
+ grad_input, grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_backward(
108
+ x.reshape(batch_dim, n), weight1, grad_act_input
109
+ )
110
+ return grad_input.reshape_as(x), grad_weight1, grad_bias1, grad_weight2, grad_bias2, None
111
+
112
+
113
+ fused_dense_sqrelu_dense_function = FusedDenseSqreluDenseFunc.apply
114
+
115
+
116
+ class FusedDenseSqreluDense(nn.Module):
117
+ def __init__(
118
+ self,
119
+ in_features,
120
+ hidden_features=None,
121
+ out_features=None,
122
+ bias1=True,
123
+ bias2=True,
124
+ checkpoint_lvl=0,
125
+ device=None,
126
+ dtype=None,
127
+ ):
128
+ """
129
+ checkpoint_lvl (increasing lvl means slower but more memory saving):
130
+ 0: no recomputation in the bwd
131
+ 1: recompute gelu_out in the bwd
132
+ 2: recompute gelu_in and gelu_out in the bwd
133
+ """
134
+ assert checkpoint_lvl in [0, 1, 2]
135
+ factory_kwargs = {"device": device, "dtype": dtype}
136
+ super().__init__()
137
+ out_features = out_features or in_features
138
+ hidden_features = hidden_features or in_features * 4
139
+ assert bias1 == True, "DenseSqreluDense module without bias is currently not supported"
140
+ assert bias2 == True, "DenseSqreluDense module without bias is currently not supported"
141
+ self.checkpoint_lvl = checkpoint_lvl
142
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1, **factory_kwargs)
143
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs)
144
+
145
+ def forward(self, x):
146
+ assert x.is_cuda
147
+ return fused_dense_sqrelu_dense_function(
148
+ x, self.fc1.weight, self.fc1.bias, self.fc2.weight, self.fc2.bias, self.checkpoint_lvl
149
+ )
build/torch211-cxx11-cu126-aarch64-linux/ops/triton/rotary.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, Tri Dao.
2
+ # As of 2025-04-23, we require triton >= 3.0
3
+
4
+ from typing import Optional, Union
5
+
6
+ import torch
7
+
8
+ import triton
9
+ import triton.language as tl
10
+
11
+
12
+ @triton.jit
13
+ def rotary_kernel(
14
+ OUT, # Pointers to matrices
15
+ X,
16
+ COS,
17
+ SIN,
18
+ CU_SEQLENS,
19
+ SEQLEN_OFFSETS, # this could be int or a pointer
20
+ # Matrix dimensions
21
+ seqlen,
22
+ nheads,
23
+ seqlen_ro,
24
+ # strides
25
+ stride_out_batch,
26
+ stride_out_seqlen,
27
+ stride_out_nheads,
28
+ stride_out_headdim,
29
+ stride_x_batch,
30
+ stride_x_seqlen,
31
+ stride_x_nheads,
32
+ stride_x_headdim,
33
+ # Meta-parameters
34
+ # We want ROTARY_DIM to be constexpr, otherwise the triton compiler doesn't know that
35
+ # the mask is constant every 8 elements, and it will generate LDG.16 instead of LDG.128
36
+ ROTARY_DIM: tl.constexpr,
37
+ IS_SEQLEN_OFFSETS_TENSOR: tl.constexpr,
38
+ IS_VARLEN: tl.constexpr,
39
+ INTERLEAVED: tl.constexpr,
40
+ CONJUGATE: tl.constexpr,
41
+ BLOCK_H: tl.constexpr,
42
+ BLOCK_M: tl.constexpr,
43
+ ):
44
+ BLOCK_K: tl.constexpr = triton.next_power_of_2(ROTARY_DIM)
45
+ ROTARY_DIM_HALF = ROTARY_DIM // 2
46
+ pid_head = tl.program_id(axis=0)
47
+ pid_m = tl.program_id(axis=1)
48
+ pid_batch = tl.program_id(axis=2)
49
+
50
+ if not IS_VARLEN:
51
+ X = X + pid_batch * stride_x_batch
52
+ OUT = OUT + pid_batch * stride_out_batch
53
+ else:
54
+ start_idx = tl.load(CU_SEQLENS + pid_batch)
55
+ seqlen = tl.load(CU_SEQLENS + pid_batch + 1) - start_idx
56
+ X = X + start_idx * stride_x_seqlen
57
+ OUT = OUT + start_idx * stride_out_seqlen
58
+
59
+ if pid_m * BLOCK_M >= seqlen:
60
+ return
61
+
62
+ rh = pid_head * BLOCK_H + tl.arange(0, BLOCK_H)
63
+ rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
64
+ if not IS_SEQLEN_OFFSETS_TENSOR:
65
+ rm_cs = rm + SEQLEN_OFFSETS
66
+ else:
67
+ rm_cs = rm + tl.load(SEQLEN_OFFSETS + pid_batch)
68
+
69
+ rk_half = tl.arange(0, BLOCK_K // 2)
70
+ COS = COS + (rm_cs[:, None] * ROTARY_DIM_HALF + rk_half[None, :])
71
+ SIN = SIN + (rm_cs[:, None] * ROTARY_DIM_HALF + rk_half[None, :])
72
+ mask_cs = (rm_cs[:, None] < seqlen_ro) & (rk_half[None, :] < ROTARY_DIM_HALF)
73
+ cos = tl.load(COS, mask=mask_cs, other=1.0).to(tl.float32)
74
+ sin = tl.load(SIN, mask=mask_cs, other=0.0).to(tl.float32)
75
+ if CONJUGATE:
76
+ sin = -sin
77
+
78
+ if not INTERLEAVED:
79
+ # Load the 1st and 2nd halves of X, do calculation, then store to 1st and 2nd halves of OUT
80
+ X = X + (rh[:, None, None] * stride_x_nheads + rm[None, :, None] * stride_x_seqlen + rk_half[None, None, :] * stride_x_headdim)
81
+ OUT = OUT + (rh[:, None, None] * stride_out_nheads + rm[None, :, None] * stride_out_seqlen + rk_half[None, None, :] * stride_out_headdim)
82
+ mask = (rh[:, None, None] < nheads) & (rm[None, :, None] < seqlen) & (rk_half[None, None, :] < ROTARY_DIM_HALF)
83
+ x0 = tl.load(X, mask=mask, other=0.0).to(tl.float32)
84
+ x1 = tl.load(X + ROTARY_DIM_HALF * stride_x_headdim, mask=mask, other=0.0,).to(tl.float32)
85
+ o0 = x0 * cos - x1 * sin
86
+ o1 = x0 * sin + x1 * cos
87
+ tl.store(OUT, o0, mask=mask)
88
+ tl.store(OUT + ROTARY_DIM_HALF * stride_out_headdim, o1, mask=mask)
89
+ else:
90
+ rk = tl.arange(0, BLOCK_K)
91
+ X = X + (rh[:, None, None] * stride_x_nheads + rm[None, :, None] * stride_x_seqlen + rk[None, None, :] * stride_x_headdim)
92
+ OUT = OUT + (rh[:, None, None] * stride_out_nheads + rm[None, :, None] * stride_out_seqlen + rk[None, None, :] * stride_out_headdim)
93
+ mask = (rh[:, None, None] < nheads) & (rm[None, :, None] < seqlen) & (rk[None, None, :] < ROTARY_DIM)
94
+ x = tl.load(X, mask=mask, other=0.0).to(tl.float32)
95
+ x0, x1 = tl.split(tl.reshape(x, [BLOCK_H, BLOCK_M, BLOCK_K // 2, 2]))
96
+ o0 = x0 * cos - x1 * sin
97
+ o1 = x0 * sin + x1 * cos
98
+ o = tl.reshape(tl.join(o0, o1), [BLOCK_H, BLOCK_M, BLOCK_K])
99
+ tl.store(OUT, o, mask=mask)
100
+
101
+
102
+ def apply_rotary(
103
+ x: torch.Tensor,
104
+ cos: torch.Tensor,
105
+ sin: torch.Tensor,
106
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
107
+ cu_seqlens: Optional[torch.Tensor] = None,
108
+ max_seqlen: Optional[int] = None,
109
+ interleaved=False,
110
+ inplace=False,
111
+ conjugate=False,
112
+ ) -> torch.Tensor:
113
+ """
114
+ Arguments:
115
+ x: (batch, seqlen, nheads, headdim) if cu_seqlens is None
116
+ else (total_seqlen, nheads, headdim).
117
+ cos: (seqlen_ro, rotary_dim / 2)
118
+ sin: (seqlen_ro, rotary_dim / 2)
119
+ seqlen_offsets: integer or integer tensor of size (batch,)
120
+ cu_seqlens: (batch + 1,) or None
121
+ max_seqlen: int
122
+ Returns:
123
+ y: (batch, seqlen, nheads, headdim)
124
+ """
125
+ is_varlen = cu_seqlens is not None
126
+ if not is_varlen:
127
+ batch, seqlen, nheads, headdim = x.shape
128
+ else:
129
+ assert max_seqlen is not None, "If cu_seqlens is passed in, then max_seqlen must be passed"
130
+ total_seqlen, nheads, headdim = x.shape
131
+ batch_p_1 = cu_seqlens.shape[0]
132
+ batch = batch_p_1 - 1
133
+ seqlen = max_seqlen
134
+ seqlen_ro, rotary_dim = cos.shape
135
+ assert sin.shape == cos.shape
136
+ rotary_dim *= 2
137
+ assert rotary_dim <= headdim, "rotary_dim must be <= headdim"
138
+ assert headdim <= 256, "Only support headdim <= 256"
139
+ assert seqlen_ro >= seqlen, "seqlen_ro must be >= seqlen"
140
+
141
+ cos, sin = cos.contiguous(), sin.contiguous()
142
+ if isinstance(seqlen_offsets, torch.Tensor):
143
+ assert seqlen_offsets.shape == (batch,)
144
+ assert seqlen_offsets.dtype in [torch.int32, torch.int64]
145
+ seqlen_offsets = seqlen_offsets.contiguous()
146
+ else:
147
+ assert seqlen_offsets + seqlen <= seqlen_ro
148
+
149
+ output = torch.empty_like(x) if not inplace else x
150
+ if rotary_dim < headdim and not inplace:
151
+ output[..., rotary_dim:].copy_(x[..., rotary_dim:])
152
+
153
+ grid = lambda META: (triton.cdiv(nheads, META["BLOCK_H"]), triton.cdiv(seqlen, META["BLOCK_M"]), batch) # noqa
154
+ BLOCK_M = 8 if rotary_dim <= 128 else 4
155
+
156
+ # Need this, otherwise Triton tries to launch from cuda:0 and we get
157
+ # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?)
158
+ device_ctx = torch.cuda.device(x.device.index) if x.device.type == 'cuda' else torch.xpu.device(x.device.index)
159
+ with device_ctx:
160
+ torch.library.wrap_triton(rotary_kernel)[grid](
161
+ output, # data ptrs
162
+ x,
163
+ cos,
164
+ sin,
165
+ cu_seqlens,
166
+ seqlen_offsets,
167
+ seqlen, # shapes
168
+ nheads,
169
+ seqlen_ro,
170
+ output.stride(0) if not is_varlen else 0, # batch_strides if not varlen else 0
171
+ output.stride(-3), # seqlen_stride or total_seqlen_stride
172
+ output.stride(-2), # nheads_stride
173
+ output.stride(-1), # headdim_stride
174
+ x.stride(0) if not is_varlen else 0, # batch_strides if not varlen else 0
175
+ x.stride(-3), # seqlen stride or total_seqlen_stride
176
+ x.stride(-2), # nheads stride
177
+ x.stride(-1), # headdim stride
178
+ rotary_dim,
179
+ isinstance(seqlen_offsets, torch.Tensor),
180
+ is_varlen,
181
+ interleaved,
182
+ conjugate,
183
+ BLOCK_M=BLOCK_M,
184
+ BLOCK_H=2,
185
+ )
186
+ return output
build/torch211-cxx11-cu128-aarch64-linux/__init__.py CHANGED
@@ -1,7 +1,5 @@
1
- from typing import List, Optional
2
-
3
  import torch
4
-
5
  from ._ops import ops as flash_attn_ops
6
  from .flash_attn_interface import (
7
  flash_attn_func,
@@ -13,23 +11,6 @@ from .flash_attn_interface import (
13
  flash_attn_with_kvcache,
14
  )
15
 
16
- __all__ = [
17
- # High-level API (with autograd support)
18
- "flash_attn_func",
19
- "flash_attn_kvpacked_func",
20
- "flash_attn_qkvpacked_func",
21
- "flash_attn_varlen_func",
22
- "flash_attn_varlen_kvpacked_func",
23
- "flash_attn_varlen_qkvpacked_func",
24
- "flash_attn_with_kvcache",
25
- # Low-level ops (no autograd)
26
- "fwd",
27
- "varlen_fwd",
28
- "bwd",
29
- "varlen_bwd",
30
- "fwd_kvcache",
31
- ]
32
-
33
 
34
  def fwd(
35
  q: torch.Tensor,
 
1
+ from typing import Optional, List
 
2
  import torch
 
3
  from ._ops import ops as flash_attn_ops
4
  from .flash_attn_interface import (
5
  flash_attn_func,
 
11
  flash_attn_with_kvcache,
12
  )
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  def fwd(
16
  q: torch.Tensor,
build/torch211-cxx11-cu128-aarch64-linux/{_flash_attn2_cuda_a511a4c.abi3.so → _flash_attn2_cuda_f12afc9.abi3.so} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:b3efe9fb19140ae2697b5fc5ab69c628dd0c72108489f66c44e73ab20ca0a892
3
- size 1037997832
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f6ebce5c99d8d2cd4a77d5be6f460b0bb03db6fcbe62c9a1a0cafde62e0d94b
3
+ size 1035975264
build/torch211-cxx11-cu128-aarch64-linux/_ops.py CHANGED
@@ -1,9 +1,9 @@
1
  import torch
2
- from . import _flash_attn2_cuda_a511a4c
3
- ops = torch.ops._flash_attn2_cuda_a511a4c
4
 
5
  def add_op_namespace_prefix(op_name: str):
6
  """
7
  Prefix op by namespace.
8
  """
9
- return f"_flash_attn2_cuda_a511a4c::{op_name}"
 
1
  import torch
2
+ from . import _flash_attn2_cuda_f12afc9
3
+ ops = torch.ops._flash_attn2_cuda_f12afc9
4
 
5
  def add_op_namespace_prefix(op_name: str):
6
  """
7
  Prefix op by namespace.
8
  """
9
+ return f"_flash_attn2_cuda_f12afc9::{op_name}"
build/torch211-cxx11-cu128-aarch64-linux/flash_attn_interface.py CHANGED
@@ -15,12 +15,12 @@ import os
15
  # import flash_attn_2_cuda as flash_attn
16
 
17
 
 
18
  from ._ops import ops as flash_attn
19
  from ._ops import add_op_namespace_prefix
20
 
21
  # # isort: on
22
 
23
-
24
  def maybe_contiguous(x):
25
  return x.contiguous() if x is not None and x.stride(-1) != 1 else x
26
 
@@ -49,9 +49,7 @@ def _get_block_size_n(device, head_dim, is_dropout, is_causal):
49
 
50
  # This should match the block sizes in the CUDA kernel
51
  major, minor = torch.cuda.get_device_capability(device)
52
- is_sm8x = (
53
- major == 8 and minor > 0
54
- ) # Only include sm86 and sm89, exclude sm80 (A100)
55
  is_sm80 = major == 8 and minor == 0
56
  is_sm90 = major == 9 and minor == 0
57
  if head_dim <= 32:
@@ -77,11 +75,30 @@ def round_multiple(x, m):
77
  return (x + m - 1) // m * m
78
 
79
 
80
- @torch.library.custom_op(
81
- add_op_namespace_prefix("_flash_attn_forward"),
82
- mutates_args=(),
83
- device_types=_get_device(),
84
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  def _flash_attn_forward(
86
  q: torch.Tensor,
87
  k: torch.Tensor,
@@ -93,7 +110,7 @@ def _flash_attn_forward(
93
  window_size_right: int,
94
  softcap: float,
95
  alibi_slopes: Optional[torch.Tensor],
96
- return_softmax: bool,
97
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
98
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
99
  out, softmax_lse, S_dmask, rng_state = flash_attn.fwd(
@@ -114,7 +131,7 @@ def _flash_attn_forward(
114
  return out, softmax_lse, S_dmask, rng_state
115
 
116
 
117
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_forward"))
118
  def _flash_attn_forward_fake(
119
  q: torch.Tensor,
120
  k: torch.Tensor,
@@ -126,41 +143,28 @@ def _flash_attn_forward_fake(
126
  window_size_right: int,
127
  softcap: float,
128
  alibi_slopes: Optional[torch.Tensor],
129
- return_softmax: bool,
130
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
131
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
132
  batch_size, seqlen_q, num_heads, head_size = q.shape
133
  seqlen_k = k.shape[1]
134
  out = torch.empty_like(q)
135
- softmax_lse = torch.empty(
136
- (batch_size, num_heads, seqlen_q),
137
- dtype=torch.float32,
138
- device=q.device,
139
- layout=q.layout,
140
- )
141
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
142
  if return_softmax:
143
- p = torch.empty(
144
- (
145
- batch_size,
146
- num_heads,
147
- round_multiple(seqlen_q, 128),
148
- round_multiple(seqlen_k, 128),
149
- ),
150
- dtype=q.dtype,
151
- device=q.device,
152
- layout=q.layout,
153
- )
154
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
155
 
156
  return out, softmax_lse, p, rng_state
157
 
158
 
159
- @torch.library.custom_op(
160
- add_op_namespace_prefix("_flash_attn_varlen_forward"),
161
- mutates_args=(),
162
- device_types=_get_device(),
163
- )
 
 
164
  def _flash_attn_varlen_forward(
165
  q: torch.Tensor,
166
  k: torch.Tensor,
@@ -211,7 +215,7 @@ def _flash_attn_varlen_forward(
211
  return out, softmax_lse, S_dmask, rng_state
212
 
213
 
214
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_varlen_forward"))
215
  def _flash_attn_varlen_forward_fake(
216
  q: torch.Tensor,
217
  k: torch.Tensor,
@@ -237,30 +241,25 @@ def _flash_attn_varlen_forward_fake(
237
  paged_kv = block_table is not None
238
  batch_size = cu_seqlens_q.numel() - 1
239
  total_q, num_heads, _ = q.shape
240
-
241
  out = torch.empty_like(q)
242
- softmax_lse = torch.empty(
243
- (num_heads, total_q), dtype=torch.float32, device=q.device, layout=q.layout
244
- )
245
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
246
  seqlen_q_rounded = round_multiple(max_seqlen_q, 128)
247
  seqlen_k_rounded = round_multiple(max_seqlen_k, 128)
248
  if return_softmax:
249
- p = torch.empty(
250
- (batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded),
251
- dtype=q.dtype,
252
- device=q.device,
253
- layout=q.layout,
254
- )
255
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
256
  return out, softmax_lse, p, rng_state
257
 
258
 
259
- @torch.library.custom_op(
260
- add_op_namespace_prefix("_flash_attn_backward"),
261
- mutates_args=("dq", "dk", "dv"),
262
- device_types=_get_device(),
263
- )
 
 
264
  def _flash_attn_backward(
265
  dout: torch.Tensor,
266
  q: torch.Tensor,
@@ -312,7 +311,7 @@ def _flash_attn_backward(
312
  return softmax_d
313
 
314
 
315
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_backward"))
316
  def _flash_attn_backward_fake(
317
  dout: torch.Tensor,
318
  q: torch.Tensor,
@@ -341,20 +340,18 @@ def _flash_attn_backward_fake(
341
  if dv is None:
342
  dv = torch.empty_like(v)
343
  batch_size, seqlen_q, num_heads, _ = q.shape
344
- softmax_d = torch.empty(
345
- (batch_size, num_heads, round_multiple(seqlen_q, 128)),
346
- device=q.device,
347
- dtype=torch.float32,
348
- )
349
-
350
  return softmax_d
351
 
352
 
353
- @torch.library.custom_op(
354
- add_op_namespace_prefix("_flash_attn_varlen_backward"),
355
- mutates_args=("dq", "dk", "dv"),
356
- device_types=_get_device(),
357
- )
 
 
358
  def _flash_attn_varlen_backward(
359
  dout: torch.Tensor,
360
  q: torch.Tensor,
@@ -418,7 +415,7 @@ def _flash_attn_varlen_backward(
418
  return softmax_d
419
 
420
 
421
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_varlen_backward"))
422
  def _flash_attn_varlen_backward_fake(
423
  dout: torch.Tensor,
424
  q: torch.Tensor,
@@ -454,13 +451,17 @@ def _flash_attn_varlen_backward_fake(
454
  dk = torch.empty_like(k)
455
  if dv is None:
456
  dv = torch.empty_like(v)
457
- softmax_d = torch.empty(
458
- (num_heads, total_q + 128 * batch_size), device=q.device, dtype=torch.float32
459
- )
460
-
461
  return softmax_d
462
 
463
 
 
 
 
 
 
 
464
  class FlashAttnQKVPackedFunc(torch.autograd.Function):
465
  @staticmethod
466
  def forward(
@@ -485,7 +486,7 @@ class FlashAttnQKVPackedFunc(torch.autograd.Function):
485
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
486
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
487
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
488
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_forward(
489
  q,
490
  k,
491
  v,
@@ -519,7 +520,7 @@ class FlashAttnQKVPackedFunc(torch.autograd.Function):
519
  dout_padded = dout
520
  if head_size_og % 8 != 0:
521
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
522
- _flash_attn_backward(
523
  dout_padded,
524
  q,
525
  k,
@@ -569,7 +570,7 @@ class FlashAttnVarlenQKVPackedFunc(torch.autograd.Function):
569
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
570
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
571
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
572
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_varlen_forward(
573
  q,
574
  k,
575
  v,
@@ -588,9 +589,7 @@ class FlashAttnVarlenQKVPackedFunc(torch.autograd.Function):
588
  block_table=None,
589
  )
590
  if is_grad:
591
- ctx.save_for_backward(
592
- q, k, v, out_padded, softmax_lse, cu_seqlens, rng_state
593
- )
594
  ctx.dropout_p = dropout_p
595
  ctx.max_seqlen = max_seqlen
596
  ctx.softmax_scale = softmax_scale
@@ -611,7 +610,7 @@ class FlashAttnVarlenQKVPackedFunc(torch.autograd.Function):
611
  dout_padded = dout
612
  if head_size_og % 8 != 0:
613
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
614
- _flash_attn_varlen_backward(
615
  dout_padded,
616
  q,
617
  k,
@@ -655,7 +654,9 @@ class FlashAttnKVPackedFunc(torch.autograd.Function):
655
  return_softmax,
656
  is_grad_enabled,
657
  ):
658
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, kv])
 
 
659
  if softmax_scale is None:
660
  softmax_scale = q.shape[-1] ** (-0.5)
661
  k, v = kv[:, :, 0].detach(), kv[:, :, 1].detach()
@@ -664,7 +665,7 @@ class FlashAttnKVPackedFunc(torch.autograd.Function):
664
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
665
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
666
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
667
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_forward(
668
  q,
669
  k,
670
  v,
@@ -699,7 +700,7 @@ class FlashAttnKVPackedFunc(torch.autograd.Function):
699
  dout_padded = dout
700
  if head_size_og % 8 != 0:
701
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
702
- _flash_attn_backward(
703
  dout_padded,
704
  q,
705
  k,
@@ -744,7 +745,9 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
744
  return_softmax,
745
  is_grad_enabled,
746
  ):
747
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, kv])
 
 
748
  if softmax_scale is None:
749
  softmax_scale = q.shape[-1] ** (-0.5)
750
  k, v = kv[:, 0].detach(), kv[:, 1].detach()
@@ -753,7 +756,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
753
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
754
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
755
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
756
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_varlen_forward(
757
  q,
758
  k,
759
  v,
@@ -789,9 +792,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
789
 
790
  @staticmethod
791
  def backward(ctx, dout, *args):
792
- q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = (
793
- ctx.saved_tensors
794
- )
795
  dq = torch.empty_like(q)
796
  kv_shape = k.shape[:-2] + (2, *k.shape[-2:])
797
  dkv = torch.empty(kv_shape, dtype=k.dtype, device=k.device)
@@ -799,7 +800,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
799
  dout_padded = dout
800
  if head_size_og % 8 != 0:
801
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
802
- _flash_attn_varlen_backward(
803
  dout_padded,
804
  q,
805
  k,
@@ -825,23 +826,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
825
  )
826
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
827
  dkv = dkv[..., : dout.shape[-1]]
828
- return (
829
- dq,
830
- dkv,
831
- None,
832
- None,
833
- None,
834
- None,
835
- None,
836
- None,
837
- None,
838
- None,
839
- None,
840
- None,
841
- None,
842
- None,
843
- None,
844
- )
845
 
846
 
847
  class FlashAttnFunc(torch.autograd.Function):
@@ -861,7 +846,9 @@ class FlashAttnFunc(torch.autograd.Function):
861
  return_softmax,
862
  is_grad_enabled,
863
  ):
864
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, k, v])
 
 
865
  if softmax_scale is None:
866
  softmax_scale = q.shape[-1] ** (-0.5)
867
  head_size_og = q.size(3)
@@ -869,7 +856,7 @@ class FlashAttnFunc(torch.autograd.Function):
869
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
870
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
871
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
872
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_forward(
873
  q,
874
  k,
875
  v,
@@ -902,7 +889,7 @@ class FlashAttnFunc(torch.autograd.Function):
902
  dout_padded = dout
903
  if head_size_og % 8 != 0:
904
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
905
- _flash_attn_backward(
906
  dout_padded,
907
  q,
908
  k,
@@ -950,7 +937,9 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
950
  block_table,
951
  is_grad_enabled,
952
  ):
953
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, k, v])
 
 
954
  if softmax_scale is None:
955
  softmax_scale = q.shape[-1] ** (-0.5)
956
  head_size_og = q.size(2)
@@ -958,7 +947,7 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
958
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
959
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
960
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
961
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_varlen_forward(
962
  q,
963
  k,
964
  v,
@@ -995,15 +984,13 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
995
 
996
  @staticmethod
997
  def backward(ctx, dout, *args):
998
- q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = (
999
- ctx.saved_tensors
1000
- )
1001
  dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
1002
  head_size_og = dout.size(2)
1003
  dout_padded = dout
1004
  if head_size_og % 8 != 0:
1005
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
1006
- _flash_attn_varlen_backward(
1007
  dout_padded,
1008
  q,
1009
  k,
@@ -1030,25 +1017,7 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
1030
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
1031
  dk = dk[..., : dout.shape[-1]]
1032
  dv = dv[..., : dout.shape[-1]]
1033
- return (
1034
- dq,
1035
- dk,
1036
- dv,
1037
- None,
1038
- None,
1039
- None,
1040
- None,
1041
- None,
1042
- None,
1043
- None,
1044
- None,
1045
- None,
1046
- None,
1047
- None,
1048
- None,
1049
- None,
1050
- None,
1051
- )
1052
 
1053
 
1054
  def flash_attn_qkvpacked_func(
@@ -1196,7 +1165,7 @@ def flash_attn_func(
1196
  softmax_scale=None,
1197
  causal=False,
1198
  window_size=(-1, -1), # -1 means infinite context window
1199
- softcap=0.0, # 0.0 means deactivated
1200
  alibi_slopes=None,
1201
  deterministic=False,
1202
  return_attn_probs=False,
@@ -1273,7 +1242,7 @@ def flash_attn_varlen_qkvpacked_func(
1273
  softmax_scale=None,
1274
  causal=False,
1275
  window_size=(-1, -1), # -1 means infinite context window
1276
- softcap=0.0, # 0.0 means deactivated
1277
  alibi_slopes=None,
1278
  deterministic=False,
1279
  return_attn_probs=False,
@@ -1342,7 +1311,7 @@ def flash_attn_varlen_kvpacked_func(
1342
  softmax_scale=None,
1343
  causal=False,
1344
  window_size=(-1, -1), # -1 means infinite context window
1345
- softcap=0.0, # 0.0 means deactivated
1346
  alibi_slopes=None,
1347
  deterministic=False,
1348
  return_attn_probs=False,
@@ -1435,7 +1404,7 @@ def flash_attn_varlen_func(
1435
  softmax_scale=None,
1436
  causal=False,
1437
  window_size=(-1, -1), # -1 means infinite context window
1438
- softcap=0.0, # 0.0 means deactivated
1439
  alibi_slopes=None,
1440
  deterministic=False,
1441
  return_attn_probs=False,
@@ -1532,7 +1501,7 @@ def flash_attn_with_kvcache(
1532
  softmax_scale=None,
1533
  causal=False,
1534
  window_size=(-1, -1), # -1 means infinite context window
1535
- softcap=0.0, # 0.0 means deactivated
1536
  rotary_interleaved=True,
1537
  alibi_slopes=None,
1538
  num_splits=0,
 
15
  # import flash_attn_2_cuda as flash_attn
16
 
17
 
18
+ from . import _ops
19
  from ._ops import ops as flash_attn
20
  from ._ops import add_op_namespace_prefix
21
 
22
  # # isort: on
23
 
 
24
  def maybe_contiguous(x):
25
  return x.contiguous() if x is not None and x.stride(-1) != 1 else x
26
 
 
49
 
50
  # This should match the block sizes in the CUDA kernel
51
  major, minor = torch.cuda.get_device_capability(device)
52
+ is_sm8x = major == 8 and minor > 0 # Only include sm86 and sm89, exclude sm80 (A100)
 
 
53
  is_sm80 = major == 8 and minor == 0
54
  is_sm90 = major == 9 and minor == 0
55
  if head_dim <= 32:
 
75
  return (x + m - 1) // m * m
76
 
77
 
78
+ # torch.compile() support is only enabled for pytorch >= 2.4
79
+ # The reason for this is that we are using the new custom_op and register_fake
80
+ # APIs, which support inplace modification of inputs in the function itself
81
+ if torch.__version__ >= "2.4.0":
82
+ _torch_custom_op_wrapper = torch.library.custom_op
83
+ _torch_register_fake_wrapper = torch.library.register_fake
84
+ else:
85
+ def noop_custom_op_wrapper(name, fn=None, /, *, mutates_args, device_types=None, schema=None):
86
+ def wrap(func):
87
+ return func
88
+ if fn is None:
89
+ return wrap
90
+ return fn
91
+ def noop_register_fake_wrapper(op, fn=None, /, *, lib=None, _stacklevel=1):
92
+ def wrap(func):
93
+ return func
94
+ if fn is None:
95
+ return wrap
96
+ return fn
97
+ _torch_custom_op_wrapper = noop_custom_op_wrapper
98
+ _torch_register_fake_wrapper = noop_register_fake_wrapper
99
+
100
+
101
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_forward"), mutates_args=(), device_types=_get_device())
102
  def _flash_attn_forward(
103
  q: torch.Tensor,
104
  k: torch.Tensor,
 
110
  window_size_right: int,
111
  softcap: float,
112
  alibi_slopes: Optional[torch.Tensor],
113
+ return_softmax: bool
114
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
115
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
116
  out, softmax_lse, S_dmask, rng_state = flash_attn.fwd(
 
131
  return out, softmax_lse, S_dmask, rng_state
132
 
133
 
134
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_forward"))
135
  def _flash_attn_forward_fake(
136
  q: torch.Tensor,
137
  k: torch.Tensor,
 
143
  window_size_right: int,
144
  softcap: float,
145
  alibi_slopes: Optional[torch.Tensor],
146
+ return_softmax: bool
147
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
148
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
149
  batch_size, seqlen_q, num_heads, head_size = q.shape
150
  seqlen_k = k.shape[1]
151
  out = torch.empty_like(q)
152
+ softmax_lse = torch.empty((batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device, layout=q.layout)
 
 
 
 
 
153
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
154
  if return_softmax:
155
+ p = torch.empty((batch_size, num_heads, round_multiple(seqlen_q, 128), round_multiple(seqlen_k, 128)), dtype=q.dtype, device=q.device, layout=q.layout)
 
 
 
 
 
 
 
 
 
 
156
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
157
 
158
  return out, softmax_lse, p, rng_state
159
 
160
 
161
+ if torch.__version__ >= "2.4.0":
162
+ _wrapped_flash_attn_forward = _ops.ops._flash_attn_forward
163
+ else:
164
+ _wrapped_flash_attn_forward = _flash_attn_forward
165
+
166
+
167
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_varlen_forward"), mutates_args=(), device_types=_get_device())
168
  def _flash_attn_varlen_forward(
169
  q: torch.Tensor,
170
  k: torch.Tensor,
 
215
  return out, softmax_lse, S_dmask, rng_state
216
 
217
 
218
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_varlen_forward"))
219
  def _flash_attn_varlen_forward_fake(
220
  q: torch.Tensor,
221
  k: torch.Tensor,
 
241
  paged_kv = block_table is not None
242
  batch_size = cu_seqlens_q.numel() - 1
243
  total_q, num_heads, _ = q.shape
244
+
245
  out = torch.empty_like(q)
246
+ softmax_lse = torch.empty((num_heads, total_q), dtype=torch.float32, device=q.device, layout=q.layout)
 
 
247
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
248
  seqlen_q_rounded = round_multiple(max_seqlen_q, 128)
249
  seqlen_k_rounded = round_multiple(max_seqlen_k, 128)
250
  if return_softmax:
251
+ p = torch.empty((batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded), dtype=q.dtype, device=q.device, layout=q.layout)
 
 
 
 
 
252
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
253
  return out, softmax_lse, p, rng_state
254
 
255
 
256
+ if torch.__version__ >= "2.4.0":
257
+ _wrapped_flash_attn_varlen_forward = _ops.ops._flash_attn_varlen_forward
258
+ else:
259
+ _wrapped_flash_attn_varlen_forward = _flash_attn_varlen_forward
260
+
261
+
262
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_backward"), mutates_args=("dq", "dk", "dv"), device_types=_get_device())
263
  def _flash_attn_backward(
264
  dout: torch.Tensor,
265
  q: torch.Tensor,
 
311
  return softmax_d
312
 
313
 
314
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_backward"))
315
  def _flash_attn_backward_fake(
316
  dout: torch.Tensor,
317
  q: torch.Tensor,
 
340
  if dv is None:
341
  dv = torch.empty_like(v)
342
  batch_size, seqlen_q, num_heads, _ = q.shape
343
+ softmax_d = torch.empty((batch_size, num_heads, round_multiple(seqlen_q, 128)), device=q.device, dtype=torch.float32)
344
+
 
 
 
 
345
  return softmax_d
346
 
347
 
348
+ if torch.__version__ >= "2.4.0":
349
+ _wrapped_flash_attn_backward = _ops.ops._flash_attn_backward
350
+ else:
351
+ _wrapped_flash_attn_backward = _flash_attn_backward
352
+
353
+
354
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_varlen_backward"), mutates_args=("dq", "dk", "dv"), device_types=_get_device())
355
  def _flash_attn_varlen_backward(
356
  dout: torch.Tensor,
357
  q: torch.Tensor,
 
415
  return softmax_d
416
 
417
 
418
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_varlen_backward"))
419
  def _flash_attn_varlen_backward_fake(
420
  dout: torch.Tensor,
421
  q: torch.Tensor,
 
451
  dk = torch.empty_like(k)
452
  if dv is None:
453
  dv = torch.empty_like(v)
454
+ softmax_d = torch.empty((num_heads, total_q + 128 * batch_size), device=q.device, dtype=torch.float32)
455
+
 
 
456
  return softmax_d
457
 
458
 
459
+ if torch.__version__ >= "2.4.0":
460
+ _wrapped_flash_attn_varlen_backward = _ops.ops._flash_attn_varlen_backward
461
+ else:
462
+ _wrapped_flash_attn_varlen_backward = _flash_attn_varlen_backward
463
+
464
+
465
  class FlashAttnQKVPackedFunc(torch.autograd.Function):
466
  @staticmethod
467
  def forward(
 
486
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
487
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
488
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
489
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward(
490
  q,
491
  k,
492
  v,
 
520
  dout_padded = dout
521
  if head_size_og % 8 != 0:
522
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
523
+ _wrapped_flash_attn_backward(
524
  dout_padded,
525
  q,
526
  k,
 
570
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
571
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
572
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
573
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward(
574
  q,
575
  k,
576
  v,
 
589
  block_table=None,
590
  )
591
  if is_grad:
592
+ ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens, rng_state)
 
 
593
  ctx.dropout_p = dropout_p
594
  ctx.max_seqlen = max_seqlen
595
  ctx.softmax_scale = softmax_scale
 
610
  dout_padded = dout
611
  if head_size_og % 8 != 0:
612
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
613
+ _wrapped_flash_attn_varlen_backward(
614
  dout_padded,
615
  q,
616
  k,
 
654
  return_softmax,
655
  is_grad_enabled,
656
  ):
657
+ is_grad = is_grad_enabled and any(
658
+ x.requires_grad for x in [q, kv]
659
+ )
660
  if softmax_scale is None:
661
  softmax_scale = q.shape[-1] ** (-0.5)
662
  k, v = kv[:, :, 0].detach(), kv[:, :, 1].detach()
 
665
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
666
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
667
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
668
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward(
669
  q,
670
  k,
671
  v,
 
700
  dout_padded = dout
701
  if head_size_og % 8 != 0:
702
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
703
+ _wrapped_flash_attn_backward(
704
  dout_padded,
705
  q,
706
  k,
 
745
  return_softmax,
746
  is_grad_enabled,
747
  ):
748
+ is_grad = is_grad_enabled and any(
749
+ x.requires_grad for x in [q, kv]
750
+ )
751
  if softmax_scale is None:
752
  softmax_scale = q.shape[-1] ** (-0.5)
753
  k, v = kv[:, 0].detach(), kv[:, 1].detach()
 
756
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
757
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
758
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
759
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward(
760
  q,
761
  k,
762
  v,
 
792
 
793
  @staticmethod
794
  def backward(ctx, dout, *args):
795
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors
 
 
796
  dq = torch.empty_like(q)
797
  kv_shape = k.shape[:-2] + (2, *k.shape[-2:])
798
  dkv = torch.empty(kv_shape, dtype=k.dtype, device=k.device)
 
800
  dout_padded = dout
801
  if head_size_og % 8 != 0:
802
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
803
+ _wrapped_flash_attn_varlen_backward(
804
  dout_padded,
805
  q,
806
  k,
 
826
  )
827
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
828
  dkv = dkv[..., : dout.shape[-1]]
829
+ return dq, dkv, None, None, None, None, None, None, None, None, None, None, None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
830
 
831
 
832
  class FlashAttnFunc(torch.autograd.Function):
 
846
  return_softmax,
847
  is_grad_enabled,
848
  ):
849
+ is_grad = is_grad_enabled and any(
850
+ x.requires_grad for x in [q, k, v]
851
+ )
852
  if softmax_scale is None:
853
  softmax_scale = q.shape[-1] ** (-0.5)
854
  head_size_og = q.size(3)
 
856
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
857
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
858
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
859
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward(
860
  q,
861
  k,
862
  v,
 
889
  dout_padded = dout
890
  if head_size_og % 8 != 0:
891
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
892
+ _wrapped_flash_attn_backward(
893
  dout_padded,
894
  q,
895
  k,
 
937
  block_table,
938
  is_grad_enabled,
939
  ):
940
+ is_grad = is_grad_enabled and any(
941
+ x.requires_grad for x in [q, k, v]
942
+ )
943
  if softmax_scale is None:
944
  softmax_scale = q.shape[-1] ** (-0.5)
945
  head_size_og = q.size(2)
 
947
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
948
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
949
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
950
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward(
951
  q,
952
  k,
953
  v,
 
984
 
985
  @staticmethod
986
  def backward(ctx, dout, *args):
987
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors
 
 
988
  dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
989
  head_size_og = dout.size(2)
990
  dout_padded = dout
991
  if head_size_og % 8 != 0:
992
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
993
+ _wrapped_flash_attn_varlen_backward(
994
  dout_padded,
995
  q,
996
  k,
 
1017
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
1018
  dk = dk[..., : dout.shape[-1]]
1019
  dv = dv[..., : dout.shape[-1]]
1020
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1021
 
1022
 
1023
  def flash_attn_qkvpacked_func(
 
1165
  softmax_scale=None,
1166
  causal=False,
1167
  window_size=(-1, -1), # -1 means infinite context window
1168
+ softcap=0.0, # 0.0 means deactivated
1169
  alibi_slopes=None,
1170
  deterministic=False,
1171
  return_attn_probs=False,
 
1242
  softmax_scale=None,
1243
  causal=False,
1244
  window_size=(-1, -1), # -1 means infinite context window
1245
+ softcap=0.0, # 0.0 means deactivated
1246
  alibi_slopes=None,
1247
  deterministic=False,
1248
  return_attn_probs=False,
 
1311
  softmax_scale=None,
1312
  causal=False,
1313
  window_size=(-1, -1), # -1 means infinite context window
1314
+ softcap=0.0, # 0.0 means deactivated
1315
  alibi_slopes=None,
1316
  deterministic=False,
1317
  return_attn_probs=False,
 
1404
  softmax_scale=None,
1405
  causal=False,
1406
  window_size=(-1, -1), # -1 means infinite context window
1407
+ softcap=0.0, # 0.0 means deactivated
1408
  alibi_slopes=None,
1409
  deterministic=False,
1410
  return_attn_probs=False,
 
1501
  softmax_scale=None,
1502
  causal=False,
1503
  window_size=(-1, -1), # -1 means infinite context window
1504
+ softcap=0.0, # 0.0 means deactivated
1505
  rotary_interleaved=True,
1506
  alibi_slopes=None,
1507
  num_splits=0,
build/torch211-cxx11-cu128-aarch64-linux/layers/__init__.py ADDED
File without changes
build/torch211-cxx11-cu128-aarch64-linux/layers/patch_embed.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # We use the same API as https://github.com/rwightman/pytorch-image-models/blob/v0.6.11/timm/models/layers/patch_embed.py
2
+ # But we use nn.Linear instead of Conv2d and it's about 8x faster.
3
+
4
+ from functools import partial
5
+
6
+ import torch.nn as nn
7
+ from einops import rearrange
8
+ from torch import _assert
9
+ from torch.nn.modules.utils import _pair
10
+
11
+ try:
12
+ from flash_attn.ops.fused_dense import FusedDense
13
+ except ImportError:
14
+ FusedDense = None
15
+
16
+
17
+ class PatchEmbed(nn.Module):
18
+ """2D Image to Patch Embedding"""
19
+
20
+ def __init__(
21
+ self,
22
+ img_size=224,
23
+ patch_size=16,
24
+ in_chans=3,
25
+ embed_dim=768,
26
+ norm_layer=None,
27
+ flatten=True,
28
+ bias=True,
29
+ fused_bias_fc=False,
30
+ ):
31
+ super().__init__()
32
+ img_size = _pair(img_size)
33
+ patch_size = _pair(patch_size)
34
+ self.img_size = img_size
35
+ self.patch_size = patch_size
36
+ self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
37
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
38
+ self.flatten = flatten
39
+ if fused_bias_fc and FusedDense is None:
40
+ raise ImportError("fused_dense is not installed")
41
+
42
+ linear_cls = nn.Linear if not fused_bias_fc or not bias else FusedDense
43
+ self.proj = linear_cls(in_chans * patch_size[0] * patch_size[1], embed_dim, bias=bias)
44
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
45
+
46
+ def forward(self, x):
47
+ _, _, H, W = x.shape
48
+ _assert(
49
+ H == self.img_size[0],
50
+ f"Input image height ({H}) doesn't match model ({self.img_size[0]}).",
51
+ )
52
+ _assert(
53
+ W == self.img_size[1],
54
+ f"Input image width ({W}) doesn't match model ({self.img_size[1]}).",
55
+ )
56
+ x = self.proj(
57
+ rearrange(
58
+ x,
59
+ "b c (h p1) (w p2) -> b h w (c p1 p2)",
60
+ p1=self.patch_size[0],
61
+ p2=self.patch_size[1],
62
+ )
63
+ )
64
+ if self.flatten:
65
+ x = rearrange(x, "b h w c -> b (h w) c")
66
+ x = self.norm(x)
67
+ return x
build/torch211-cxx11-cu128-aarch64-linux/layers/rotary.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, Tri Dao
2
+
3
+ import math
4
+ from functools import partial
5
+ from typing import Optional, Tuple, Union
6
+
7
+ import torch
8
+ from torch import Tensor
9
+
10
+ from einops import rearrange, repeat
11
+ # from flash_attn.ops.triton.rotary import apply_rotary
12
+ from ..ops.triton.rotary import apply_rotary
13
+
14
+
15
+ def rotate_half(x, interleaved=False):
16
+ if not interleaved:
17
+ x1, x2 = x.chunk(2, dim=-1)
18
+ return torch.cat((-x2, x1), dim=-1)
19
+ else:
20
+ x1, x2 = x[..., ::2], x[..., 1::2]
21
+ return rearrange(torch.stack((-x2, x1), dim=-1), "... d two -> ... (d two)", two=2)
22
+
23
+
24
+ def apply_rotary_emb_torch(x, cos, sin, interleaved=False):
25
+ """
26
+ x: (batch_size, seqlen, nheads, headdim)
27
+ cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2)
28
+ """
29
+ ro_dim = cos.shape[-1] * 2
30
+ assert ro_dim <= x.shape[-1]
31
+ cos = repeat(cos, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
32
+ sin = repeat(sin, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
33
+ return torch.cat(
34
+ [x[..., :ro_dim] * cos + rotate_half(x[..., :ro_dim], interleaved) * sin, x[..., ro_dim:]],
35
+ dim=-1,
36
+ )
37
+
38
+
39
+ class ApplyRotaryEmb(torch.autograd.Function):
40
+ @staticmethod
41
+ def forward(
42
+ ctx,
43
+ x,
44
+ cos,
45
+ sin,
46
+ interleaved=False,
47
+ inplace=False,
48
+ seqlen_offsets: Union[int, Tensor] = 0,
49
+ cu_seqlens: Optional[Tensor] = None,
50
+ max_seqlen: Optional[int] = None,
51
+ ):
52
+ out = apply_rotary(
53
+ x,
54
+ cos,
55
+ sin,
56
+ seqlen_offsets=seqlen_offsets,
57
+ cu_seqlens=cu_seqlens,
58
+ max_seqlen=max_seqlen,
59
+ interleaved=interleaved,
60
+ inplace=inplace,
61
+ )
62
+ if isinstance(seqlen_offsets, int):
63
+ ctx.save_for_backward(cos, sin, cu_seqlens) # Can't save int with save_for_backward
64
+ ctx.seqlen_offsets = seqlen_offsets
65
+ else:
66
+ ctx.save_for_backward(cos, sin, cu_seqlens, seqlen_offsets)
67
+ ctx.seqlen_offsets = None
68
+ ctx.interleaved = interleaved
69
+ ctx.inplace = inplace
70
+ ctx.max_seqlen = max_seqlen
71
+ return out if not inplace else x
72
+
73
+ @staticmethod
74
+ def backward(ctx, do):
75
+ seqlen_offsets = ctx.seqlen_offsets
76
+ if seqlen_offsets is None:
77
+ cos, sin, cu_seqlens, seqlen_offsets = ctx.saved_tensors
78
+ else:
79
+ cos, sin, cu_seqlens = ctx.saved_tensors
80
+ dx = apply_rotary(
81
+ do,
82
+ cos,
83
+ sin,
84
+ seqlen_offsets=seqlen_offsets,
85
+ cu_seqlens=cu_seqlens,
86
+ max_seqlen=ctx.max_seqlen,
87
+ interleaved=ctx.interleaved,
88
+ inplace=ctx.inplace,
89
+ conjugate=True,
90
+ )
91
+ return dx, None, None, None, None, None, None, None
92
+
93
+
94
+ def apply_rotary_emb(
95
+ x,
96
+ cos,
97
+ sin,
98
+ interleaved=False,
99
+ inplace=False,
100
+ seqlen_offsets: Union[int, Tensor] = 0,
101
+ cu_seqlens: Optional[Tensor] = None,
102
+ max_seqlen: Optional[int] = None,
103
+ ):
104
+ """
105
+ Arguments:
106
+ x: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None
107
+ else (total_seqlen, nheads, headdim)
108
+ cos, sin: (seqlen_rotary, rotary_dim / 2)
109
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
110
+ of 1st half and 2nd half (GPT-NeoX style).
111
+ inplace: if True, apply rotary embedding in-place.
112
+ seqlen_offsets: (batch_size,) or int. Each sequence in x is shifted by this amount.
113
+ Most commonly used in inference when we have KV cache.
114
+ cu_seqlens: (batch + 1,) or None
115
+ max_seqlen: int
116
+ Return:
117
+ out: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None
118
+ else (total_seqlen, nheads, headdim)
119
+ rotary_dim must be <= headdim
120
+ Apply rotary embedding to the first rotary_dim of x.
121
+ """
122
+ return ApplyRotaryEmb.apply(
123
+ x, cos, sin, interleaved, inplace, seqlen_offsets, cu_seqlens, max_seqlen
124
+ )
125
+
126
+
127
+ # For backward compatibility
128
+ apply_rotary_emb_func = apply_rotary_emb
129
+
130
+
131
+ def _apply_rotary_emb_qkv(
132
+ qkv,
133
+ cos,
134
+ sin,
135
+ cos_k=None,
136
+ sin_k=None,
137
+ interleaved=False,
138
+ inplace=False,
139
+ conjugate=False,
140
+ seqlen_offsets: Union[int, Tensor] = 0,
141
+ num_heads_q: Optional[int] = None,
142
+ ):
143
+ apply_rotary_fn = partial(
144
+ apply_rotary,
145
+ interleaved=interleaved,
146
+ inplace=inplace,
147
+ conjugate=conjugate,
148
+ seqlen_offsets=seqlen_offsets
149
+ )
150
+ if cos_k is None and sin_k is None and qkv.is_contiguous():
151
+ # Call 1 kernel instead of 2 kernels
152
+ # We need qkv to be contiguous so that when we reshape to combine (3, nheads)
153
+ # dimensions, we get the same tensor
154
+ if qkv.dim() == 5:
155
+ batch, seqlen, three, nheads, headdim = qkv.shape
156
+ assert three == 3
157
+ # qk = rearrange(qkv[:, :, :2], "b s t h d -> b s (t h) d")
158
+ qk = qkv[:, :, :2].reshape(batch, seqlen, -1, headdim)
159
+ qk = apply_rotary_fn(qk, cos, sin)
160
+ else:
161
+ assert qkv.dim() == 4
162
+ assert num_heads_q is not None
163
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
164
+ assert qkv.shape[2] == num_heads_q + 2 * num_heads_k
165
+ qk = qkv[:, :, :num_heads_q + num_heads_k]
166
+ qk = apply_rotary_fn(qk, cos, sin)
167
+ if not inplace:
168
+ if qkv.dim() == 5:
169
+ qkv = torch.cat([rearrange(qk, "b s (t h) d -> b s t h d", t=2), qkv[:, :, 2:]], dim=2)
170
+ else:
171
+ qkv = torch.cat([qk, qkv[:, :, num_heads_q + num_heads_k :]], dim=2)
172
+ else:
173
+ cos_k = cos if cos_k is None else cos_k
174
+ sin_k = sin if sin_k is None else sin_k
175
+ if qkv.dim() == 5:
176
+ batch, seqlen, three, nheads, headdim = qkv.shape
177
+ assert three == 3
178
+ q, k = qkv[:, :, 0], qkv[:, :, 1]
179
+ else:
180
+ assert qkv.dim() == 4
181
+ assert num_heads_q is not None
182
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
183
+ assert qkv.shape[2] == num_heads_q + 2 * num_heads_k
184
+ q, k = qkv[:, :, :num_heads_q], qkv[:, :, num_heads_q : num_heads_q + num_heads_k]
185
+ q = apply_rotary_fn(q, cos, sin)
186
+ k = apply_rotary_fn(k, cos_k, sin_k)
187
+ if not inplace:
188
+ if qkv.dim() == 5:
189
+ qkv = torch.stack([q, k, qkv[:, :, 2]], dim=2)
190
+ else:
191
+ qkv = torch.cat([q, k, qkv[:, :, num_heads_q + num_heads_k:]], dim=2)
192
+ return qkv
193
+
194
+
195
+ class ApplyRotaryEmbQKV_(torch.autograd.Function):
196
+ @staticmethod
197
+ def forward(
198
+ ctx,
199
+ qkv,
200
+ cos,
201
+ sin,
202
+ cos_k=None,
203
+ sin_k=None,
204
+ interleaved=False,
205
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
206
+ num_heads_q: Optional[int] = None,
207
+ ):
208
+ # apply_rotary_emb_qkv_inplace(
209
+ qkv = _apply_rotary_emb_qkv(
210
+ qkv, cos, sin, cos_k, sin_k, interleaved=interleaved, inplace=True,
211
+ seqlen_offsets=seqlen_offsets, num_heads_q=num_heads_q,
212
+ )
213
+ if isinstance(seqlen_offsets, int):
214
+ ctx.save_for_backward(cos, sin, cos_k, sin_k)
215
+ ctx.seqlen_offsets = seqlen_offsets
216
+ else:
217
+ ctx.save_for_backward(cos, sin, cos_k, sin_k, seqlen_offsets)
218
+ ctx.seqlen_offsets = None
219
+ ctx.interleaved = interleaved
220
+ ctx.num_heads_q = num_heads_q
221
+ return qkv
222
+
223
+ @staticmethod
224
+ def backward(ctx, dqkv):
225
+ seqlen_offsets = ctx.seqlen_offsets
226
+ if seqlen_offsets is None:
227
+ cos, sin, cos_k, sin_k, seqlen_offsets = ctx.saved_tensors
228
+ else:
229
+ cos, sin, cos_k, sin_k = ctx.saved_tensors
230
+ dqkv = _apply_rotary_emb_qkv(
231
+ dqkv, cos, sin, cos_k, sin_k, interleaved=ctx.interleaved, inplace=True,
232
+ seqlen_offsets=seqlen_offsets, num_heads_q=ctx.num_heads_q, conjugate=True,
233
+ )
234
+ return dqkv, None, None, None, None, None, None, None
235
+
236
+
237
+ def apply_rotary_emb_qkv_(
238
+ qkv,
239
+ cos,
240
+ sin,
241
+ cos_k=None,
242
+ sin_k=None,
243
+ interleaved=False,
244
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
245
+ num_heads_q: Optional[int] = None,
246
+ ):
247
+ """
248
+ Arguments:
249
+ qkv: (batch_size, seqlen, 3, nheads, headdim) or (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim).
250
+ If qkv has shape (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim) (e.g. MQA / GQA),
251
+ then num_heads_q must be provided.
252
+ cos, sin: (seqlen, rotary_dim / 2)
253
+ cos_k, sin_k: (seqlen, rotary_dim / 2), optional
254
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of
255
+ 1st half and 2nd half (GPT-NeoX style).
256
+ seqlen_offsets: (batch_size,) or int. Each sequence in Q and K is shifted by this amount.
257
+ Most commonly used in inference when we have KV cache.
258
+ Return:
259
+ qkv: (batch_size, seqlen, 3, nheads, headdim) or (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim)
260
+ rotary_dim must be <= headdim
261
+ Apply rotary embedding *inplace* to the first rotary_dim of Q and K.
262
+ """
263
+ return ApplyRotaryEmbQKV_.apply(
264
+ qkv, cos, sin, cos_k, sin_k, interleaved, seqlen_offsets, num_heads_q
265
+ )
266
+
267
+
268
+ class ApplyRotaryEmbKV_(torch.autograd.Function):
269
+
270
+ @staticmethod
271
+ def forward(ctx, kv, cos, sin, interleaved=False, seqlen_offsets: Union[int, torch.Tensor] = 0):
272
+ batch, seqlen, two, nheads, headdim = kv.shape
273
+ assert two == 2
274
+ k = kv[:, :, 0]
275
+ apply_rotary(
276
+ k, cos, sin, seqlen_offsets=seqlen_offsets, interleaved=interleaved, inplace=True
277
+ )
278
+ if isinstance(seqlen_offsets, int):
279
+ ctx.save_for_backward(cos, sin) # Can't save int with save_for_backward
280
+ ctx.seqlen_offsets = seqlen_offsets
281
+ else:
282
+ ctx.save_for_backward(cos, sin, seqlen_offsets)
283
+ ctx.seqlen_offsets = None
284
+ ctx.interleaved = interleaved
285
+ return kv
286
+
287
+ @staticmethod
288
+ def backward(ctx, dkv):
289
+ seqlen_offsets = ctx.seqlen_offsets
290
+ if seqlen_offsets is None:
291
+ cos, sin, seqlen_offsets = ctx.saved_tensors
292
+ else:
293
+ cos, sin = ctx.saved_tensors
294
+ apply_rotary(
295
+ dkv[:, :, 0],
296
+ cos,
297
+ sin,
298
+ seqlen_offsets=seqlen_offsets,
299
+ interleaved=ctx.interleaved,
300
+ inplace=True,
301
+ conjugate=True,
302
+ )
303
+ return dkv, None, None, None, None
304
+
305
+
306
+ apply_rotary_emb_kv_ = ApplyRotaryEmbKV_.apply
307
+
308
+
309
+ def apply_rotary_emb_kv_(
310
+ kv,
311
+ cos,
312
+ sin,
313
+ interleaved=False,
314
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
315
+ ):
316
+ """
317
+ Arguments:
318
+ kv: (batch_size, seqlen, 2, nheads, headdim)
319
+ cos, sin: (seqlen, rotary_dim / 2)
320
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of
321
+ 1st half and 2nd half (GPT-NeoX style).
322
+ seqlen_offsets: (batch_size,) or int. Each sequence in Q and K is shifted by this amount.
323
+ Most commonly used in inference when we have KV cache.
324
+ Return:
325
+ kv: (batch_size, seqlen, 2, nheads, headdim)
326
+ rotary_dim must be <= headdim
327
+ Apply rotary embedding *inplace* to the first rotary_dim of K.
328
+ """
329
+ return ApplyRotaryEmbKV_.apply(kv, cos, sin, interleaved, seqlen_offsets)
330
+
331
+
332
+ class RotaryEmbedding(torch.nn.Module):
333
+ """
334
+ The rotary position embeddings from RoFormer_ (Su et. al).
335
+ A crucial insight from the method is that the query and keys are
336
+ transformed by rotation matrices which depend on the relative positions.
337
+
338
+ Other implementations are available in the Rotary Transformer repo_ and in
339
+ GPT-NeoX_, GPT-NeoX was an inspiration
340
+
341
+ .. _RoFormer: https://arxiv.org/abs/2104.09864
342
+ .. _repo: https://github.com/ZhuiyiTechnology/roformer
343
+ .. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox
344
+
345
+ If scale_base is not None, this implements XPos (Sun et al., https://arxiv.org/abs/2212.10554).
346
+ A recommended value for scale_base is 512: https://github.com/HazyResearch/flash-attention/issues/96
347
+ Reference: https://github.com/sunyt32/torchscale/blob/main/torchscale/component/xpos_relative_position.py
348
+ """
349
+
350
+ def __init__(
351
+ self,
352
+ dim: int,
353
+ base=10000.0,
354
+ interleaved=False,
355
+ scale_base=None,
356
+ device=None,
357
+ ):
358
+ """
359
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
360
+ of 1st half and 2nd half (GPT-NeoX style).
361
+ """
362
+ super().__init__()
363
+ self.dim = dim
364
+ self.base = float(base)
365
+ # Generate and save the inverse frequency buffer (non trainable)
366
+ inv_freq = self._compute_inv_freq(device)
367
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
368
+ self.interleaved = interleaved
369
+ self.scale_base = scale_base
370
+ scale = (
371
+ (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim)
372
+ if scale_base is not None
373
+ else None
374
+ )
375
+ self.register_buffer("scale", scale, persistent=False)
376
+
377
+ self._seq_len_cached = 0
378
+ self._cos_cached = None
379
+ self._sin_cached = None
380
+ self._cos_k_cached = None
381
+ self._sin_k_cached = None
382
+
383
+ def _compute_inv_freq(self, device=None):
384
+ return 1.0 / (
385
+ self.base
386
+ ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim)
387
+ )
388
+
389
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
390
+ # Reset the tables if the sequence length has changed,
391
+ # if we're on a new device (possibly due to tracing for instance),
392
+ # or if we're switching from inference mode to training
393
+ if (
394
+ seqlen > self._seq_len_cached
395
+ or self._cos_cached is None
396
+ or self._cos_cached.device != device
397
+ or self._cos_cached.dtype != dtype
398
+ or (self.training and self._cos_cached.is_inference())
399
+ ):
400
+ self._seq_len_cached = seqlen
401
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
402
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
403
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
404
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
405
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
406
+ # cos & sin output to change significantly.
407
+ # We want to recompute self.inv_freq if it was not loaded in fp32
408
+ if self.inv_freq.dtype != torch.float32:
409
+ inv_freq = self._compute_inv_freq(device=device)
410
+ else:
411
+ inv_freq = self.inv_freq
412
+ # Don't do einsum, it converts fp32 to bf16 under AMP
413
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
414
+ freqs = torch.outer(t, inv_freq)
415
+ if self.scale is None:
416
+ self._cos_cached = torch.cos(freqs).to(dtype)
417
+ self._sin_cached = torch.sin(freqs).to(dtype)
418
+ else:
419
+ power = (
420
+ torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device)
421
+ - seqlen // 2
422
+ ) / self.scale_base
423
+ scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
424
+ # We want the multiplication by scale to happen in fp32
425
+ self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
426
+ self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
427
+ self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
428
+ self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
429
+
430
+ def forward(
431
+ self,
432
+ qkv: torch.Tensor,
433
+ kv: Optional[torch.Tensor] = None,
434
+ seqlen_offset: Union[int, torch.Tensor] = 0,
435
+ max_seqlen: Optional[int] = None,
436
+ num_heads_q: Optional[int] = None,
437
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
438
+ """
439
+ qkv: (batch, seqlen, 3, nheads, headdim) or (batch, seqlen, num_heads_q + 2 * num_heads_k, headdim)
440
+ if kv is none, else it's just q of shape (batch, seqlen, nheads, headdim).
441
+ If qkv has shape (batch, seqlen, num_heads_q + 2 * num_heads_k, headdim) (e.g. MQA / GQA),
442
+ then num_heads_q must be provided.
443
+ kv: (batch, seqlen, 2, nheads, headdim)
444
+ seqlen_offset: (batch_size,) or int. Each sequence in x is shifted by this amount.
445
+ Most commonly used in inference when we have KV cache.
446
+ If it's a tensor of shape (batch_size,), then to update the cos / sin cache, one
447
+ should pass in max_seqlen, which will update the cos / sin cache up to that length.
448
+ Apply rotary embedding *inplace* to qkv and / or kv.
449
+ """
450
+ seqlen = qkv.shape[1]
451
+ if max_seqlen is not None:
452
+ self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype)
453
+ elif isinstance(seqlen_offset, int):
454
+ self._update_cos_sin_cache(seqlen + seqlen_offset, device=qkv.device, dtype=qkv.dtype)
455
+ if kv is None:
456
+ return apply_rotary_emb_qkv_(
457
+ qkv,
458
+ self._cos_cached,
459
+ self._sin_cached,
460
+ self._cos_k_cached if self.scale is not None else None,
461
+ self._sin_k_cached if self.scale is not None else None,
462
+ interleaved=self.interleaved,
463
+ seqlen_offsets=seqlen_offset,
464
+ num_heads_q=num_heads_q,
465
+ )
466
+ else:
467
+ q = qkv
468
+ q = apply_rotary_emb_func(
469
+ q,
470
+ self._cos_cached,
471
+ self._sin_cached,
472
+ interleaved=self.interleaved,
473
+ inplace=True,
474
+ seqlen_offsets=seqlen_offset,
475
+ )
476
+ kv = apply_rotary_emb_kv_(
477
+ kv,
478
+ self._cos_cached if self.scale is None else self._cos_k_cached,
479
+ self._sin_cached if self.scale is None else self._sin_k_cached,
480
+ interleaved=self.interleaved,
481
+ seqlen_offsets=seqlen_offset,
482
+ )
483
+ return q, kv
build/torch211-cxx11-cu128-aarch64-linux/metadata.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "name": "flash-attn2",
3
- "id": "_flash_attn2_cuda_a511a4c",
4
  "version": 1,
5
  "license": "BSD-3-Clause",
6
  "python-depends": [],
@@ -16,12 +16,27 @@
16
  "digest": {
17
  "algorithm": "sha256",
18
  "files": {
19
- "__init__.py": "pbZ3riEB3GTIymdTvC7023ydYDWalnxEy+Lq0DGeZoQ=",
20
- "_flash_attn2_cuda_a511a4c.abi3.so": "s+/p+xkUCuJpe1/Fq2nGKN0MchCEifZsROc6sgygqJI=",
21
- "_ops.py": "ceg+0r4TQ9sSFsTUNrdsGNcrceyYp1uw3N5C3bS/Q/Y=",
22
  "bert_padding.py": "gF1EmsdJ+HpQ86MRQ4VxDw+Sb/RVISdQALdNnoByHlw=",
23
  "flash_attn2/__init__.py": "DFYPlrhXwYjEqCl/8n0SmWGZV8NFml5DPhMjKfv98GY=",
24
- "flash_attn_interface.py": "pJrnUxC+7qEqFh1C1YbjYggC9FfoG3dblU+XlwaJkEs="
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  }
26
  }
27
  }
 
1
  {
2
  "name": "flash-attn2",
3
+ "id": "_flash_attn2_cuda_f12afc9",
4
  "version": 1,
5
  "license": "BSD-3-Clause",
6
  "python-depends": [],
 
16
  "digest": {
17
  "algorithm": "sha256",
18
  "files": {
19
+ "__init__.py": "Cd9MEdd/WUYnBmfiQpC4SyPqAxrTilTjvsvswNju4zc=",
20
+ "_flash_attn2_cuda_f12afc9.abi3.so": "X2685cmdjSzUp31b5vRgsLsD22/L5iyaGgyv3mLg2Us=",
21
+ "_ops.py": "GQbmTTeSOU+7Q2nI68Hz+1RvEogyfEFccx1ubUYw+2s=",
22
  "bert_padding.py": "gF1EmsdJ+HpQ86MRQ4VxDw+Sb/RVISdQALdNnoByHlw=",
23
  "flash_attn2/__init__.py": "DFYPlrhXwYjEqCl/8n0SmWGZV8NFml5DPhMjKfv98GY=",
24
+ "flash_attn_interface.py": "W7a9bHR2ly6QL3aKqsBqxWA7M7ZWYcZPmtsPJu6rAfY=",
25
+ "layers/__init__.py": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",
26
+ "layers/patch_embed.py": "H58CgME/qSOPTZLOG08wFgrQS1j34pvNwMPrkTj3Ek4=",
27
+ "layers/rotary.py": "rFIdNrZQFNawwLD6d7t5LE2m+M93wwDZ8EuExw+gfD8=",
28
+ "ops/__init__.py": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",
29
+ "ops/activations.py": "t5lzNg1In8LP6bKeTnyeMizwqjv27JGbJ6ylPdGvZYg=",
30
+ "ops/fused_dense.py": "BqT8VTSCGdLJAjh6WBMkCRFYrdVodPeoElWBvH6AIzA=",
31
+ "ops/layer_norm.py": "zr7NXIm+2mtEynTp1CS0fbFGI2Mqdp41dY4AfDWF6EQ=",
32
+ "ops/rms_norm.py": "XEnihcj0a4aSz4LO55m5iKGVn4HKTeKN8TIyHjuDgxI=",
33
+ "ops/triton/__init__.py": "AbpHGcgLb+kRsJGnwFEktk7uzpZOCcBY74+YBdrKVGs=",
34
+ "ops/triton/cross_entropy.py": "y56nmuOtpSNxM7sDZcUSgXKIsIEayfuvrU8bAVog/nw=",
35
+ "ops/triton/k_activations.py": "+Z3vIyO4JkqBMipKsPvhzmxljtBdIhJCsl/M+/ESqBo=",
36
+ "ops/triton/layer_norm.py": "BBQdJiqopbIS12viUqzx3SvOQCNbDSAYLJXhpyMGyC8=",
37
+ "ops/triton/linear.py": "OtRvKz8xdpl+7v3q/ZTaS9fdBt9XrzMyapgRr50uBbM=",
38
+ "ops/triton/mlp.py": "uWA+D7HyuRUsOT+4nhi3vvCDNZnNEXwYcHMQ02UREfQ=",
39
+ "ops/triton/rotary.py": "0YSrlbep0lJmzLpTiANs0slTFeGcQQqR+el6uzbSLvI="
40
  }
41
  }
42
  }
build/torch211-cxx11-cu128-aarch64-linux/metadata.json.sigstore CHANGED
@@ -1 +1 @@
1
- {"mediaType":"application/vnd.dev.sigstore.bundle.v0.3+json","verificationMaterial":{"certificate":{"rawBytes":"MIIHdTCCBvqgAwIBAgIUFjZ2fCgZpVoLqcNy9gA5FuvEjfMwCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjYwNjE4MDY1MzM0WhcNMjYwNjE4MDcwMzM0WjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEwRSvmrd4ZkqPR+wMSBg+ECn67wvM5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C86fCgfCKH4MAoGCCqGSM49BAMDA2kAMGYCMQCtlWSs7hcaoWU4TrgpyuySqZ9IPP9DqFzVFfdg6Z/d11XlIz/Wf/5rEZgM+KAN8D0CMQCQSjGZvJuNt2oxmGm6qI/IliVzrWTt/R0jnaCd5njt4GYB7xYv2b0c44SLi6W40Kg="},"tlogEntries":[{"logIndex":"1857831712","logId":{"keyId":"wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0="},"kindVersion":{"kind":"hashedrekord","version":"0.0.1"},"integratedTime":"1781765614","inclusionPromise":{"signedEntryTimestamp":"MEUCIQDyzK2KWs+qSo9G+9R8gQ0LAD5AH/IB0AsY9wDiWtpl5QIgAL6CzgH/d/4vX84fldHEkM1mg7r7l4OAG6/M3IroaGc="},"inclusionProof":{"logIndex":"1735927450","rootHash":"Lwkik3QWB3YiqVvYz/9RjEk+DFgv9i6EG7EtIKHSY0c=","treeSize":"1735927458","hashes":["HdHXvf27mJZwNFhNjLn9LTZ5fVhg0ugHWEN0/Feendw=","CClmF71kdaD2EAmnIMRknLSxtksI8Kq04jJY4mqDkQo=","hCgUBfZn2zyaT2X2ugwzfRe4JJOid8zhmpv62P6RSGU=","DkUVvFuvw05AHDiVNGc52OhROhY2qhR7u5Psr3/WNBI=","bHdR8bW+lcwm2ov2RzsmzO4kesGFW2AsdMpvBYf852M=","g8j/2jqQeGbh/88B8ZByeTISSOFNez0ATDw+jNWTgy0=","lEUbVmp7zp1JH5t2U63wdSr/RpjRjtFBoJaSNmgqaaM=","YdEOvKbYyUAJqT2KPfx3vRDhtULM3xxmOmlGzZ0R0Vk=","rToNJB/Z/GC9W3boPPGK1mkXX5gOF5sDf7GymqWFiRo=","Ore1A2Ceavap3m5U3ZAHLkUinE8F4IgttCeJDxxaK98=","95goX8Iw4H4P6V4eHvRqTdVdViLbhEhsF6i7ICnz/+A=","sWDh7SjDHbJf3HWKGRxiURh6iIYrOzn4Zs37yIij6OA=","x7kXd4VRJvVmTHoSla2KyPQdKvGKDX26/7ST9OONR78=","U8wMiVDzFlmyqT7Nw1RSZYU9+fftsSkRhjpbyXnXUk8=","mqM7J+i75IpuD09QejiUBjeH85AZa+fSm4RXXFmj3lI=","72FC5FYLhxB4a4iiC956o0B/fT54ip4R41vsw2QBKtU=","lYGQ9ibwC8+smMkPQ6TchJm3H9Nc/aTYLfdRacGFChw=","daxmZaajRpZV+JxHiOYZhJBiSKN5ucqjh2WnGbHhirw=","DOCeoSMovIvLExkhIvisow9AuNXgeWs4ECkyR6EcqYU="],"checkpoint":{"envelope":"rekor.sigstore.dev - 1193050959916656506\n1735927458\nLwkik3QWB3YiqVvYz/9RjEk+DFgv9i6EG7EtIKHSY0c=\n\n— rekor.sigstore.dev wNI9ajBEAiBbFV1+3pZ3EC/b47QeP/v+n3ssL986kMFx8WgxM9TXvwIgfJqPLA7SMMgjoVHQ7vYkNHhbIE84/MWdbTQF6B25Ox8=\n"}},"canonicalizedBody":"eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiIyMzU5MzJlNjlhODk3Mzk1MDRiMDIzM2JkNDg5MDRkYWMyMGI1NzNkMWQyZGQ5OTY4YzZiN2YxNzdkMzM2YzkyIn19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FVUNJUUM2QzBLamJPYStNWVVITEpKYSs5VklvN3p6d2dpTXRsZlVNTE5jZzF2elJBSWdXdGxSZnppUUdJTjUzMzN0bFpDVkNtbURtWnZlbGpFNzJqdGVGdTNuYVVvPSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaGtWRU5EUW5aeFowRjNTVUpCWjBsVlJtcGFNbVpEWjFwd1ZtOU1jV05PZVRsblFUVkdkWFpGYW1aTmQwTm5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6zQW3MFUwPaQ7MDkxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEgMB4GA1UEAxMXc2lnc3RvcmUtdHNhLXNlbGZzaWduZWQCFDoTVC8MkGHuvMFDL8uKjosqI4sMMAoGCCqGSM49BAMCBGcwZQIxAKqSx6n1bwoZZTdNXwcM3GL5IINnSikCAUd1hexuqEVvuSuHzW3cv+OkLKFNBrOY8gIwXgziJfL+Fwzq+fI5OqzboBKAtgDRA2NxcuBfUWyF92H6jIN5uDvo5s5pzWf/7+Op"}]}},"messageSignature":{"messageDigest":{"algorithm":"SHA2_256","digest":"I1ky5pqJc5UEsCM71IkE2sILVz0dLdmWjGt/F30zbJI="},"signature":"MEUCIQC6C0KjbOa+MYUHLJJa+9VIo7zzwgiMtlfUMLNcg1vzRAIgWtlRfziQGIN5333tlZCVCmmDmZveljE72jteFu3naUo="}}
 
1
+ {"mediaType":"application/vnd.dev.sigstore.bundle.v0.3+json", "verificationMaterial":{"certificate":{"rawBytes":"MIIHSjCCBtGgAwIBAgIUTXP0YPkRACdQzHCzbBPwyt/CbnYwCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjYwNjIzMjM0MDQyWhcNMjYwNjIzMjM1MDQyWjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYIBHxpBjz3S87V7Uc7PRsCByiUbIKtsopV0bGdkBNwqKyG85bxIjcgu6yGcOtRUAHHQuVPq5sKVX/4PqafXql6OCBfAwggXsMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQUF6435n7YwCVxTpyvhlQsNgxJ198wHwYDVR0jBBgwFoAU39Ppz1YkEZb5qNjpKFWixi4YZD8wawYDVR0RAQH/BGEwX4ZdaHR0cHM6Ly9naXRodWIuY29tL2h1Z2dpbmdmYWNlL2tlcm5lbHMtY29tbXV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QQKDAgyNTcyMDc0MzBtBgorBgEEAYO/MAESBF8MXWh0dHBzOi8vZ2l0aHViLmNvbS9odWdnaW5nZmFjZS9rZXJuZWxzLWNvbW11bml0eS8uZ2l0aHViL3dvcmtmbG93cy9idWlsZC55YW1sQHJlZnMvaGVhZHMvbWFpbjA4BgorBgEEAYO/MAETBCoMKGYxMmFmYzkyYzQwYmJkNzZkOTkwZDkxMWViYWJmMjhlNDkwYTdiZGUwIQYKKwYBBAGDvzABFAQTDBF3b3JrZmxvd19kaXNwYXRjaDBkBgorBgEEAYO/MAEVBFYMVGh0dHBzOi8vZ2l0aHViLmNvbS9odWdnaW5nZmFjZS9rZXJuZWxzLWNvbW11bml0eS9hY3Rpb25zL3J1bnMvMjgwMzYyNjg5MzUvYXR0ZW1wdHMvMTAWBgorBgEEAYO/MAEWBAgMBnB1YmxpYzBGBgorBgEEAYO/MAEYBDgMNnJlcG86aHVnZ2luZ2ZhY2Uva2VybmVscy1jb21tdW5pdHk6cmVmOnJlZnMvaGVhZHMvbWFpbjCBigYKKwYBBAHWeQIEAgR8BHoAeAB2AN09MGrGxxEyYxkeHJlnNwKiSl643jyt/4eKcoAvKe6OAAABnvbbh48AAAQDAEcwRQIgXi188Z8nwooYW3zeED1fuiSgJfD9lvFWrVEj7+r/nEQCIQDC59dR/OZC4X0CXJbZ20qYL9Btf9HeiiYtzIsVhU3MTjAKBggqhkjOPQQDAwNnADBkAjAOLeOHqZYCiD3126Aq3F05/cHqrAciq+8oL8ckuzScwNHO9OV+43G7C3gfr5Axna4CMAuG7cjlIgvpErHf4P6qH1dscnnpZTPYN8uqfb4oTHxooNz5NtqjxtPJUsgspNhD0A=="}, "tlogEntries":[{"logIndex":"1933039424", "logId":{"keyId":"wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0="}, "kindVersion":{"kind":"hashedrekord", "version":"0.0.1"}, "integratedTime":"1782258043", "inclusionPromise":{"signedEntryTimestamp":"MEUCIQCpbjnlZkzI7PEtkwmQkf1BMkvwek/fH2/5haYYz60jPgIgb/vB9zQ6LD6RrEwseFzRQd6sEezpwMDesKk9spYrl00="}, "inclusionProof":{"logIndex":"1811135162", "rootHash":"q4B2gPr9VUhrNFY6Uz/Ae5Ghy0zlkWLJAlkOXhPe2Kk=", "treeSize":"1811135191", "hashes":["i+TLVttAHYRwCx9xovwZX12c7/3oqZBPin3iwMj/3zo=", "rLhpe7gZhRHUf12DZnrYyu9dsB9RIv+Ab8a5isdR/6U=", "t2YHlmI2WtJYjfnWqPzmv6OiYi8iUleQ1lYZMpuGYu8=", "Ckz51RT5HznFC3ZntJwdZyrXK429Mrp7BHpk3h/BG9E=", "faQSpui6FHHS9m07T5HobnTyppxus7k76qRzwixjkU8=", "AxV3+dqmuxdm0ZwVhcbjvrtDTXJGpXkSLxnPTbp58OM=", "t9ehbaR7xaxG+urfn3oX9xO6He7vHFlzCUHj1Cpe7kc=", "FQILKGmmcKTxlCRQxCi4Glqd2YlZ5AMG0TkLiX9Y80U=", "QVVI+8UorpK5fVvAVaM/9A8oGHpbEDzrgIYi5jMqbqw=", "WD8KwmQq5R8K69koYj5k4K7EKo2VF3LqJcx2xoXcd7o=", "99JTcUz0aJeZZocenAppVOLl8v91qMn0v7CmEjq9lws=", "OSDrt6jTKV6LYAkaG63p2BFz4SmbNmGb3uerhF5pOpQ=", "yehxDZkBWOGIzNDb93qxmQa6VBVo7kacVSoHyXMm3ZI=", "oUh+N71k3jWcTmlDDB6Esa5uqlCnbmzxTmDdut2A16M=", "2BsqkdK2omLvu+CpsFjpwqGi6m22H/7zcwCVkPwslM8=", "S8Oe9ZicoJqbVuL1I0dIdTgVpLc82Cm2CMOcV83sKVs=", "E1O2ilWlpFRLWGdbmJUMDZ2qbGu/eDZ12m6YjQ9/JPA=", "nyv2TDlfkz0XfRwjY98zsbUbOkBZ+Tgz7PML0c2uN14=", "OMfDh4k9YD0E+t4sjqJsh+vg8D1ueo1cC07exyxmr6s=", "+vHKm4wNwGJ46ceyZ8mePD7Vn1SediStNHCStRoTSWQ=", "5HwWjuGNDisetbiWM0cWIXM65TIM3EJlqk13ntCQlcU=", "NDIRlqxO0IaGr94q86MIU7VCAN3yEEgOHS4loya5lu4=", "daxmZaajRpZV+JxHiOYZhJBiSKN5ucqjh2WnGbHhirw=", "DOCeoSMovIvLExkhIvisow9AuNXgeWs4ECkyR6EcqYU="], "checkpoint":{"envelope":"rekor.sigstore.dev - 1193050959916656506\n1811135191\nq4B2gPr9VUhrNFY6Uz/Ae5Ghy0zlkWLJAlkOXhPe2Kk=\n\n— rekor.sigstore.dev wNI9ajBFAiA7EE7n1BPw8pt1hVcSSAQwQxpozL5mbug7wgQBNlf+RAIhAP21MzLaH0NEMgweVjkvhD71tD9m/sSLZDBScawNb6Lk\n"}}, "canonicalizedBody":"eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiIwZjA0NWI4ZWQyNjY2YTczZGJiMmU1YWM3NTZmNzg0YWNmMGM3Yzk2NDcwNDMwNTlmYTNlZTE1MTcxZjM3NzI5In19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FUUNJSDJLVHZ0VFFFTnFqbzF1eEVETVorNWFXalg0MUZyVnJZVnMwZURpdnI0U0FpQmpmWVlvTk1qVUhQdmFvalo0OVFNRm5keHpTVnhTR1huVktOdTN5SThsNmc9PSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaFRha05EUW5SSFowRjNTVUpCWjBsVlZGaFFNRmxRYTFKQlEyUlJla2hEZW1KQ1VIZDVkQzlEWW01WmQwTm5XVWxMYjFwSmVtb3dSVUYzVFhjS1RucEZWazFDVFVkQk1WVkZRMmhOVFdNeWJHNWpNMUoyWTIxVmRWcEhWakpOVW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p1lZ0gIH3KQkIhbrLYWl2+FeM23Dht8BK1C82gAyFfHi+XtP4bqvuMYBcCMFbo85kg4r1wdYaIckVhWf76B1YBofVsf/+HM2gfZwdBXbFEi/M3GzgGX9fX/ZYHDg=="}]}}, "messageSignature":{"messageDigest":{"algorithm":"SHA2_256", "digest":"DwRbjtJmanPbsuWsdW94Ss8MfJZHBDBZ+j7hUXHzdyk="}, "signature":"MEQCIH2KTvtTQENqjo1uxEDMZ+5aWjX41FrVrYVs0eDivr4SAiBjfYYoNMjUHPvaojZ49QMFndxzSVxSGXnVKNu3yI8l6g=="}}
build/torch211-cxx11-cu128-aarch64-linux/ops/__init__.py ADDED
File without changes
build/torch211-cxx11-cu128-aarch64-linux/ops/activations.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/model/layers/activations.py
2
+ import math
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ # 1/sqrt(2*pi)-> 0.3989423
9
+ # 1/sqrt(2) -> 0.70710678
10
+ # sqrt(2/pi) -> 0.79788456
11
+
12
+ # this function is tanh approximation of gelu
13
+ # actual gelu is:
14
+ # x * 0.5 * (1.0 + torch.erf(x * 0.70710678))
15
+ @torch.jit.script
16
+ def bias_gelu(y, bias):
17
+ x = bias + y
18
+ return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=y.dtype)
19
+
20
+
21
+ # gradient of tanh approximation of gelu
22
+ # gradient of actual gelu is:
23
+ # 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x)
24
+ @torch.jit.script
25
+ def bias_gelu_back(g, y, bias):
26
+ """Assume that y has shape (B, D) and bias has shape (D)"""
27
+ x = bias + y
28
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
29
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
30
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (
31
+ 1 + tanh_out
32
+ )
33
+ grad_y = ff * g
34
+ return grad_y.to(dtype=y.dtype), grad_y.sum(dim=(0), dtype=bias.dtype)
35
+
36
+
37
+ class GeLUFunction(torch.autograd.Function):
38
+ @staticmethod
39
+ # bias is an optional argument
40
+ def forward(ctx, input, bias):
41
+ ctx.save_for_backward(input, bias)
42
+ return bias_gelu(input, bias)
43
+
44
+ @staticmethod
45
+ def backward(ctx, grad_output):
46
+ input, bias = ctx.saved_tensors
47
+ tmp = bias_gelu_back(grad_output, input, bias)
48
+ return tmp, tmp
49
+
50
+
51
+ bias_gelu_impl = GeLUFunction.apply
52
+
53
+ # this function is tanh approximation of gelu
54
+ # actual gelu is:
55
+ # x * 0.5 * (1.0 + torch.erf(x * 0.70710678))
56
+ @torch.jit.script
57
+ def gelu_fwd(x):
58
+ return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=x.dtype)
59
+
60
+
61
+ # gradient of tanh approximation of gelu
62
+ # gradient of actual gelu is:
63
+ # 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x)
64
+ @torch.jit.script
65
+ def gelu_bwd(g, x):
66
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
67
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
68
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (
69
+ 1 + tanh_out
70
+ )
71
+ return (ff * g).to(dtype=x.dtype)
72
+
73
+
74
+ class FastGeLUFunction(torch.autograd.Function):
75
+ @staticmethod
76
+ # bias is an optional argument
77
+ def forward(ctx, input):
78
+ ctx.save_for_backward(input)
79
+ return gelu_fwd(input)
80
+
81
+ @staticmethod
82
+ def backward(ctx, grad_output):
83
+ (input,) = ctx.saved_tensors
84
+ tmp = gelu_bwd(grad_output, input)
85
+ return tmp
86
+
87
+
88
+ fast_gelu_impl = FastGeLUFunction.apply
89
+
90
+
91
+ @torch.jit.script
92
+ def relu_bwd(g, x):
93
+ return torch.where(x >= 0, g, 0.0).to(dtype=x.dtype)
94
+
95
+
96
+ @torch.jit.script
97
+ def sqrelu_fwd(x):
98
+ r = F.relu(x)
99
+ return (r * r).to(dtype=x.dtype)
100
+
101
+
102
+ @torch.jit.script
103
+ def sqrelu_bwd(g, x):
104
+ return (2.0 * g * F.relu(x)).to(dtype=x.dtype)
105
+
106
+
107
+ swiglu_fwd_codestring = """
108
+ template <typename T> T swiglu_fwd(T x, T y) {
109
+ return float(x) * float(y) / (1.0f + ::exp(-float(x)));
110
+ }
111
+ """
112
+ swiglu_bwd_codestring = """
113
+ template <typename T> void swiglu_bwd(T x, T y, T g, T& dx, T& dy) {
114
+ float x_sigmoid = 1.0f / (1.0f + ::exp(-float(x)));
115
+ dx = x_sigmoid * (1 + float(x) * (1.0f - x_sigmoid)) * float(g) * float(y);
116
+ dy = float(x) * x_sigmoid * float(g);
117
+ }
118
+ """
119
+ swiglu_fwd = torch.cuda.jiterator._create_jit_fn(swiglu_fwd_codestring)
120
+ swiglu_bwd = torch.cuda.jiterator._create_multi_output_jit_fn(swiglu_bwd_codestring, num_outputs=2)
121
+
122
+
123
+ class SwiGLUFunction(torch.autograd.Function):
124
+
125
+ @staticmethod
126
+ def forward(ctx, x, y):
127
+ ctx.save_for_backward(x, y)
128
+ return swiglu_fwd(x, y)
129
+
130
+ @staticmethod
131
+ def backward(ctx, dout):
132
+ x, y = ctx.saved_tensors
133
+ return swiglu_bwd(x, y, dout)
134
+
135
+ swiglu = SwiGLUFunction.apply
build/torch211-cxx11-cu128-aarch64-linux/ops/fused_dense.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+ # Inspired by https://github.com/NVIDIA/apex/blob/master/apex/fused_dense/fused_dense.py
3
+ # We make it work with pytorch amp and with bfloat16.
4
+ # The TensorParallel linear modules are inspired by https://github.com/NVIDIA/apex/blob/master/apex/transformer/tensor_parallel/layers.py
5
+ from functools import partial
6
+ from typing import Optional
7
+
8
+ # import fused_dense_cuda # from apex
9
+ import fused_dense_lib as fused_dense_cuda
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ from torch import Tensor
14
+ from torch.distributed import ProcessGroup
15
+
16
+ from flash_attn.utils.torch import custom_fwd, custom_bwd
17
+ from flash_attn.ops.activations import gelu_bwd, relu_bwd, sqrelu_bwd, sqrelu_fwd
18
+ from flash_attn.utils.distributed import (
19
+ all_gather_raw,
20
+ all_reduce,
21
+ all_reduce_raw,
22
+ reduce_scatter,
23
+ reduce_scatter_raw,
24
+ )
25
+
26
+
27
+ class FusedDenseFunc(torch.autograd.Function):
28
+ @staticmethod
29
+ @custom_fwd
30
+ def forward(
31
+ ctx, x, weight, bias, return_residual=False, process_group=None, sequence_parallel=True
32
+ ):
33
+ """
34
+ If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel
35
+ with sequence parallelism: we do an all_gather_raw of x before doing the matmul.
36
+ """
37
+ ctx.compute_weight_gradient = weight.requires_grad
38
+ ctx.return_residual = return_residual
39
+ ctx.process_group = process_group
40
+ ctx.sequence_parallel = sequence_parallel
41
+
42
+ if torch.is_autocast_enabled():
43
+ x = x.to(dtype=torch.get_autocast_gpu_dtype())
44
+ x = x.contiguous()
45
+ if process_group is not None and sequence_parallel:
46
+ # We want to kick off the all_gather early, before weight dtype conversion
47
+ total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
48
+ else:
49
+ total_x = x
50
+
51
+ if torch.is_autocast_enabled():
52
+ weight = weight.to(dtype=torch.get_autocast_gpu_dtype())
53
+ bias = bias.to(dtype=torch.get_autocast_gpu_dtype()) if bias is not None else None
54
+ weight = weight.contiguous()
55
+ if process_group is not None and sequence_parallel:
56
+ handle_x.wait()
57
+ batch_shape, n = total_x.shape[:-1], total_x.shape[-1]
58
+ batch_dim = batch_shape.numel()
59
+ # https://github.com/pytorch/pytorch/blob/5b51849b48a7dbccd297286cc0110def4706f9e7/aten/src/ATen/native/cuda/Blas.cpp#L174
60
+ if min(batch_dim, n, *weight.shape) > 65535 * 32:
61
+ raise RuntimeError("fused_dense only supports matrix dims <= 2M")
62
+ output = F.linear(total_x, weight, bias)
63
+ if ctx.compute_weight_gradient:
64
+ ctx.save_for_backward(x, weight)
65
+ else:
66
+ ctx.save_for_backward(weight)
67
+ return output if not return_residual else (output, x)
68
+
69
+ @staticmethod
70
+ @custom_bwd
71
+ def backward(ctx, grad_output, *args):
72
+ grad_output = grad_output.contiguous()
73
+ if ctx.return_residual:
74
+ (grad_input,) = args
75
+ grad_input = grad_input.contiguous()
76
+ process_group = ctx.process_group
77
+ sequence_parallel = ctx.sequence_parallel
78
+ if ctx.compute_weight_gradient:
79
+ x, weight = ctx.saved_tensors
80
+ if process_group is not None and sequence_parallel:
81
+ total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
82
+ else:
83
+ total_x = x
84
+ else:
85
+ (weight,) = ctx.saved_tensors
86
+ total_x = None
87
+ batch_shape = grad_output.shape[:-1]
88
+ batch_dim = batch_shape.numel()
89
+ grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1])
90
+ if ctx.needs_input_grad[0]:
91
+ if not ctx.return_residual:
92
+ grad_input = F.linear(grad_output, weight.t())
93
+ else:
94
+ grad_input = torch.addmm(
95
+ grad_input.reshape(batch_dim, grad_input.shape[-1]), grad_output, weight
96
+ )
97
+ grad_input = grad_input.reshape(*batch_shape, grad_input.shape[-1])
98
+ if process_group is not None:
99
+ reduce_fn = reduce_scatter_raw if sequence_parallel else all_reduce_raw
100
+ grad_input, handle_grad_input = reduce_fn(grad_input, process_group, async_op=True)
101
+ else:
102
+ grad_input = None
103
+ if ctx.needs_input_grad[1]:
104
+ assert ctx.compute_weight_gradient
105
+ if process_group is not None and sequence_parallel:
106
+ handle_x.wait()
107
+ grad_weight, grad_bias = fused_dense_cuda.linear_bias_wgrad(
108
+ total_x.reshape(batch_dim, total_x.shape[-1]), grad_output, ctx.needs_input_grad[2]
109
+ )
110
+ else:
111
+ grad_weight = None
112
+ grad_bias = grad_output if ctx.needs_input_grad[2] else None
113
+ if process_group is not None and ctx.needs_input_grad[0]:
114
+ handle_grad_input.wait()
115
+ return grad_input, grad_weight, grad_bias, None, None, None
116
+
117
+
118
+ def fused_dense_func(
119
+ x: Tensor,
120
+ weight: Tensor,
121
+ bias: Optional[Tensor] = None,
122
+ return_residual: bool = False,
123
+ process_group: Optional[ProcessGroup] = None,
124
+ sequence_parallel: bool = True,
125
+ ):
126
+ dtype_eligible = x.dtype in [torch.float16, torch.bfloat16] or (
127
+ x.dtype == torch.float32 and torch.is_autocast_enabled()
128
+ )
129
+ if x.is_cuda and weight.is_cuda and (bias is None or bias.is_cuda) and dtype_eligible:
130
+ return FusedDenseFunc.apply(
131
+ x, weight, bias, return_residual, process_group, sequence_parallel
132
+ )
133
+ else:
134
+ assert process_group is None
135
+ out = F.linear(x, weight, bias)
136
+ return out if not return_residual else (out, x)
137
+
138
+
139
+ class FusedDense(nn.Linear):
140
+ def __init__(
141
+ self,
142
+ in_features: int,
143
+ out_features: int,
144
+ bias: bool = True,
145
+ return_residual: bool = False,
146
+ device=None,
147
+ dtype=None,
148
+ ) -> None:
149
+ super().__init__(in_features, out_features, bias=bias, device=device, dtype=dtype)
150
+ self.return_residual = return_residual
151
+
152
+ def forward(self, x, process_group=None):
153
+ """
154
+ If process_group is not None, we're doing Tensor Parallel with sequence parallelism:
155
+ we do an all_gather of x before doing the matmul.
156
+ """
157
+ return fused_dense_func(
158
+ x,
159
+ self.weight,
160
+ self.bias,
161
+ return_residual=self.return_residual,
162
+ process_group=process_group,
163
+ )
164
+
165
+
166
+ class ColumnParallelLinear(nn.Linear):
167
+ def __init__(
168
+ self,
169
+ in_features: int,
170
+ out_features: int,
171
+ process_group: ProcessGroup,
172
+ bias: bool = True,
173
+ sequence_parallel=True,
174
+ multiple_of=1,
175
+ device=None,
176
+ dtype=None,
177
+ ) -> None:
178
+ world_size = torch.distributed.get_world_size(process_group)
179
+ if out_features % multiple_of:
180
+ raise ValueError(f"out_features ({out_features}) must be a multiple of {multiple_of}")
181
+ multiple = out_features // multiple_of
182
+ # We want to split @multiple across world_size, but it could be an uneven split
183
+ div = multiple // world_size
184
+ mod = multiple % world_size
185
+ # The first @mod ranks get @div + 1 copies, the rest get @div copies
186
+ local_multiple = div + int(torch.distributed.get_rank(process_group) < mod)
187
+ super().__init__(
188
+ in_features, local_multiple * multiple_of, bias=bias, device=device, dtype=dtype
189
+ )
190
+ self.process_group = process_group
191
+ self.sequence_parallel = sequence_parallel
192
+
193
+ def forward(self, x):
194
+ # If self.sequence_parallel is True, we're doing Tensor Parallel with sequence parallelism:
195
+ # we do an all_gather of x before doing the matmul.
196
+ # If not, then the input is already gathered.
197
+ return fused_dense_func(
198
+ x,
199
+ self.weight,
200
+ self.bias,
201
+ process_group=self.process_group,
202
+ sequence_parallel=self.sequence_parallel,
203
+ )
204
+
205
+
206
+ class RowParallelLinear(nn.Linear):
207
+ def __init__(
208
+ self,
209
+ in_features: int,
210
+ out_features: int,
211
+ process_group: ProcessGroup,
212
+ bias: bool = True,
213
+ sequence_parallel=True,
214
+ multiple_of=1,
215
+ device=None,
216
+ dtype=None,
217
+ ) -> None:
218
+ world_size = torch.distributed.get_world_size(process_group)
219
+ rank = torch.distributed.get_rank(process_group)
220
+ if in_features % multiple_of:
221
+ raise ValueError(f"in_features ({in_features}) must be a multiple of {multiple_of}")
222
+ multiple = in_features // multiple_of
223
+ # We want to split @multiple across world_size, but it could be an uneven split
224
+ div = multiple // world_size
225
+ mod = multiple % world_size
226
+ # The first @mod ranks get @div + 1 copies, the rest get @div copies
227
+ local_multiple = div + int(torch.distributed.get_rank(process_group) < mod)
228
+ # Only rank 0 will have bias
229
+ super().__init__(
230
+ local_multiple * multiple_of,
231
+ out_features,
232
+ bias=bias and rank == 0,
233
+ device=device,
234
+ dtype=dtype,
235
+ )
236
+ self.process_group = process_group
237
+ self.sequence_parallel = sequence_parallel
238
+
239
+ def forward(self, x):
240
+ """
241
+ We're doing Tensor Parallel with sequence parallelism: we do the matmul and then
242
+ a reduce_scatter of the result.
243
+ """
244
+ out = fused_dense_func(x, self.weight, self.bias)
245
+ reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce
246
+ return reduce_fn(out, self.process_group)
247
+
248
+
249
+ class FusedMLPFunc(torch.autograd.Function):
250
+ @staticmethod
251
+ @custom_fwd
252
+ def forward(
253
+ ctx,
254
+ x,
255
+ weight1,
256
+ bias1,
257
+ weight2,
258
+ bias2,
259
+ activation="gelu_approx",
260
+ save_pre_act=True,
261
+ return_residual=False,
262
+ checkpoint_lvl=0,
263
+ heuristic=0,
264
+ process_group=None,
265
+ sequence_parallel=True,
266
+ ):
267
+ """
268
+ If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel
269
+ with sequence parallelism: we do an all_gather of x before doing the matmul.
270
+ If sequence_parallel=False, then the input is already gathered.
271
+
272
+ checkpoint_lvl:
273
+ 0: no recomputation in the bwd
274
+ 1: recompute gelu_out / relu_out in the bwd
275
+ 2: recompute pre_act and gelu_out / relu_out in the bwd
276
+ """
277
+ assert -1 <= heuristic <= 4
278
+ assert activation in ["gelu_approx", "relu", "sqrelu"]
279
+ if activation == "sqrelu":
280
+ assert heuristic == -1
281
+ if not save_pre_act:
282
+ checkpoint_lvl = 2
283
+ assert checkpoint_lvl in [0, 1, 2]
284
+ ctx.return_residual = return_residual
285
+ ctx.process_group = process_group
286
+ ctx.sequence_parallel = sequence_parallel
287
+ ctx.checkpoint_lvl = checkpoint_lvl
288
+ ctx.activation = activation
289
+ ctx.heuristic = heuristic
290
+
291
+ if torch.is_autocast_enabled():
292
+ x = x.to(dtype=torch.get_autocast_gpu_dtype())
293
+ x = x.contiguous()
294
+ if process_group is not None and sequence_parallel:
295
+ # We want to kick off the all_gather early, before weight dtype conversion
296
+ total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
297
+ else:
298
+ total_x = x
299
+
300
+ if torch.is_autocast_enabled():
301
+ dtype = torch.get_autocast_gpu_dtype()
302
+ weight1, weight2 = [a.to(dtype=dtype) for a in [weight1, weight2]]
303
+ bias1 = bias1.to(dtype=dtype) if bias1 is not None else None
304
+ bias2 = bias2.to(dtype=dtype) if bias2 is not None else None
305
+ weight1 = weight1.contiguous()
306
+ bias1 = bias1.contiguous() if bias1 is not None else None
307
+ weight2 = weight2.contiguous()
308
+ bias2 = bias2.contiguous() if bias2 is not None else None
309
+ if process_group is not None and sequence_parallel:
310
+ handle_x.wait()
311
+ batch_shape, n = total_x.shape[:-1], total_x.shape[-1]
312
+ batch_dim = batch_shape.numel()
313
+ # https://github.com/pytorch/pytorch/blob/5b51849b48a7dbccd297286cc0110def4706f9e7/aten/src/ATen/native/cuda/Blas.cpp#L174
314
+ if min(batch_dim, n, *weight1.shape, *weight2.shape) > 65535 * 32:
315
+ raise RuntimeError("fused_dense only supports matrix dims <= 2M")
316
+ if heuristic == -1:
317
+ pre_act = F.linear(total_x, weight1, bias1)
318
+ activation_fn = (
319
+ partial(F.gelu, approximate="tanh")
320
+ if activation == "gelu_approx"
321
+ else (sqrelu_fwd if activation == "sqrelu" else F.relu)
322
+ )
323
+ with torch.jit.fuser("fuser2"):
324
+ output1 = activation_fn(pre_act)
325
+ # This is before adding bias1
326
+ # pre_act = F.linear(total_x.reshape(batch_dim, n), weight1)
327
+ # with torch.jit.fuser('fuser2'):
328
+ # output1 = bias_gelu(pre_act, bias1)
329
+ else:
330
+ is_gelu = activation == "gelu_approx"
331
+ output1, *rest = fused_dense_cuda.linear_act_forward(
332
+ total_x.reshape(batch_dim, n), weight1, bias1, is_gelu, save_pre_act, heuristic
333
+ )
334
+ if save_pre_act:
335
+ pre_act = rest[0]
336
+ output2 = F.linear(output1, weight2, bias2)
337
+ if checkpoint_lvl == 0 or (checkpoint_lvl == 1 and activation == "relu"):
338
+ # For RELU the pre_act is very small (just a bit-mask) so we just save it
339
+ ctx.save_for_backward(x, weight1, weight2, pre_act, output1)
340
+ elif checkpoint_lvl == 1:
341
+ ctx.save_for_backward(x, weight1, weight2, pre_act)
342
+ elif checkpoint_lvl == 2:
343
+ ctx.save_for_backward(x, weight1, weight2, bias1)
344
+ output2 = output2.reshape(*batch_shape, output2.shape[-1])
345
+ return output2 if not return_residual else (output2, x)
346
+
347
+ @staticmethod
348
+ @custom_bwd
349
+ def backward(ctx, grad_output, *args):
350
+ grad_output = grad_output.contiguous()
351
+ checkpoint_lvl = ctx.checkpoint_lvl
352
+ activation = ctx.activation
353
+ activation_fn = (
354
+ partial(F.gelu, approximate="tanh")
355
+ if activation == "gelu_approx"
356
+ else (sqrelu_fwd if activation == "sqrelu" else F.relu)
357
+ )
358
+ if ctx.return_residual:
359
+ (grad_input,) = args
360
+ grad_input = grad_input.contiguous()
361
+ process_group = ctx.process_group
362
+ sequence_parallel = ctx.sequence_parallel
363
+ x, weight1, weight2, *rest = ctx.saved_tensors
364
+ if process_group is None or not sequence_parallel:
365
+ total_x = x
366
+ batch_shape = grad_output.shape[:-1]
367
+ batch_dim = batch_shape.numel()
368
+ if checkpoint_lvl in [0, 1]:
369
+ if process_group is not None and sequence_parallel:
370
+ total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
371
+ if checkpoint_lvl == 0 or (checkpoint_lvl == 1 and activation == "relu"):
372
+ pre_act, output1 = rest
373
+ elif checkpoint_lvl == 1:
374
+ (pre_act,) = rest
375
+ with torch.jit.fuser("fuser2"):
376
+ output1 = activation_fn(pre_act)
377
+ elif checkpoint_lvl == 2:
378
+ (bias1,) = rest
379
+ if process_group is not None and sequence_parallel:
380
+ total_x, _ = all_gather_raw(x, process_group)
381
+ if ctx.heuristic == -1:
382
+ pre_act = F.linear(total_x, weight1, bias1)
383
+ with torch.jit.fuser("fuser2"):
384
+ output1 = activation_fn(pre_act)
385
+ else:
386
+ output1, pre_act = fused_dense_cuda.linear_act_forward(
387
+ total_x.reshape(batch_dim, total_x.shape[-1]),
388
+ weight1,
389
+ bias1,
390
+ activation == "gelu_approx",
391
+ True,
392
+ ctx.heuristic,
393
+ )
394
+
395
+ grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1])
396
+ output1 = output1.reshape(batch_dim, output1.shape[-1])
397
+ pre_act = pre_act.reshape(batch_dim, pre_act.shape[-1])
398
+ if ctx.needs_input_grad[3]:
399
+ grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad(
400
+ output1, grad_output, ctx.needs_input_grad[4]
401
+ )
402
+ else:
403
+ grad_weight2 = None
404
+ grad_bias2 = grad_output if ctx.needs_input_grad[4] else None
405
+ if ctx.heuristic == -1:
406
+ # grad_pre_act = matmul_dgelu(grad_output, weight2, pre_act)
407
+ grad_output1 = F.linear(grad_output, weight2.t())
408
+ activation_grad_fn = (
409
+ gelu_bwd
410
+ if activation == "gelu_approx"
411
+ else (sqrelu_bwd if activation == "sqrelu" else relu_bwd)
412
+ )
413
+ with torch.jit.fuser("fuser2"):
414
+ grad_pre_act = activation_grad_fn(grad_output1, pre_act)
415
+ else:
416
+ # The cublasLt epilogue has to compute both gelu/relu grad and bias grad, we can't
417
+ # just compute gelu/relu grad
418
+ grad_pre_act, grad_bias1 = fused_dense_cuda.bias_act_linear_dgrad_bgrad(
419
+ weight2, grad_output, pre_act, activation == "gelu_approx", ctx.heuristic
420
+ )
421
+ if not ctx.needs_input_grad[2]:
422
+ grad_bias1 = None
423
+ if ctx.needs_input_grad[0]:
424
+ if not ctx.return_residual:
425
+ grad_input = F.linear(grad_pre_act, weight1.t())
426
+ else:
427
+ grad_input = torch.addmm(
428
+ grad_input.reshape(batch_dim, grad_input.shape[-1]), grad_pre_act, weight1
429
+ )
430
+ grad_input = grad_input.reshape(*batch_shape, grad_input.shape[-1])
431
+ if process_group is not None:
432
+ reduce_fn = reduce_scatter_raw if sequence_parallel else all_reduce_raw
433
+ grad_input, handle_grad_input = reduce_fn(grad_input, process_group, async_op=True)
434
+ else:
435
+ grad_input = None
436
+ if ctx.heuristic == -1:
437
+ if ctx.needs_input_grad[1]:
438
+ if process_group is not None and sequence_parallel and checkpoint_lvl != 2:
439
+ handle_x.wait()
440
+ grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_wgrad(
441
+ total_x.reshape(batch_dim, total_x.shape[-1]),
442
+ grad_pre_act,
443
+ ctx.needs_input_grad[2],
444
+ )
445
+ else:
446
+ grad_weight1 = None
447
+ grad_bias1 = grad_pre_act if ctx.needs_input_grad[2] else None
448
+ else:
449
+ if ctx.needs_input_grad[1]:
450
+ if process_group is not None and sequence_parallel and checkpoint_lvl != 2:
451
+ handle_x.wait()
452
+ grad_weight1 = F.linear(
453
+ grad_pre_act.t(), total_x.reshape(batch_dim, total_x.shape[-1]).t()
454
+ )
455
+ else:
456
+ grad_weight1 = None
457
+ if process_group is not None and ctx.needs_input_grad[0]:
458
+ handle_grad_input.wait()
459
+ return (
460
+ grad_input,
461
+ grad_weight1,
462
+ grad_bias1,
463
+ grad_weight2,
464
+ grad_bias2,
465
+ None,
466
+ None,
467
+ None,
468
+ None,
469
+ None,
470
+ None,
471
+ None,
472
+ )
473
+
474
+
475
+ def fused_mlp_func(
476
+ x: Tensor,
477
+ weight1: Tensor,
478
+ weight2: Tensor,
479
+ bias1: Optional[Tensor] = None,
480
+ bias2: Optional[Tensor] = None,
481
+ activation: str = "gelu_approx",
482
+ save_pre_act: bool = True,
483
+ return_residual: bool = False,
484
+ checkpoint_lvl: int = 0,
485
+ heuristic: int = 0,
486
+ process_group: Optional[ProcessGroup] = None,
487
+ sequence_parallel: bool = True,
488
+ ):
489
+ assert activation in ["gelu_approx", "relu", "sqrelu"]
490
+ dtype_eligible = x.dtype in [torch.float16, torch.bfloat16] or (
491
+ x.dtype == torch.float32 and torch.is_autocast_enabled()
492
+ )
493
+ # If we save pre-activation, dimension must be divisible by 128 (relu) or 8 (gelu)
494
+ dim_eligible = not save_pre_act or (x.shape[-1] % (128 if activation == "relu" else 8) == 0)
495
+ if (
496
+ x.is_cuda
497
+ and weight1.is_cuda
498
+ and weight2.is_cuda
499
+ and (bias1 is None or bias1.is_cuda)
500
+ and (bias2 is None or bias2.is_cuda)
501
+ and dtype_eligible
502
+ and dim_eligible
503
+ ):
504
+ return FusedMLPFunc.apply(
505
+ x,
506
+ weight1,
507
+ bias1,
508
+ weight2,
509
+ bias2,
510
+ activation,
511
+ save_pre_act,
512
+ return_residual,
513
+ checkpoint_lvl,
514
+ heuristic,
515
+ process_group,
516
+ sequence_parallel,
517
+ )
518
+ else:
519
+ assert process_group is None
520
+ pre_act = F.linear(x, weight1, bias1)
521
+ activation_fn = (
522
+ partial(F.gelu, approximate="tanh")
523
+ if activation == "gelu_approx"
524
+ else partial(F.relu, inplace=True)
525
+ )
526
+ output1 = activation_fn(pre_act)
527
+ output2 = F.linear(output1, weight2, bias2)
528
+ return output2 if not return_residual else (output2, x)
529
+
530
+
531
+ class FusedMLP(nn.Module):
532
+ def __init__(
533
+ self,
534
+ in_features,
535
+ hidden_features=None,
536
+ out_features=None,
537
+ bias1=True,
538
+ bias2=True,
539
+ activation="gelu_approx",
540
+ return_residual=False,
541
+ checkpoint_lvl=0,
542
+ heuristic="auto",
543
+ device=None,
544
+ dtype=None,
545
+ ):
546
+ """
547
+ If process_group is not None, we're doing Tensor Parallel with sequence parallelism:
548
+ we do an all_gather of x before doing the matmul, gelu, then matmul.
549
+ Finally we do a reduce_scatter of the output.
550
+
551
+ checkpoint_lvl (increasing lvl means slower but more memory saving):
552
+ 0: no recomputation in the bwd
553
+ 1: recompute gelu_out in the bwd
554
+ 2: recompute pre_act and gelu_out in the bwd
555
+ heuristic:
556
+ -1: don't fuse gemm + gelu (separate kernel)
557
+ 0..4: use this heuristic for the algo section in the fused gemm + gelu
558
+ 'auto': heuristic will be picked automatically:
559
+ For CUDA >= 11.8, we set heuristic=0 for both fp16 and bf16 for best perf.
560
+ For CUDA <= 11.7, we set heuristic=1 for fp16 and heuristic=-1 for bf16.
561
+ For H100, we set heuristic=-1 for both fp16 and bf16 as the fused cuBlasLt implementation
562
+ is slower than the unfused version.
563
+ return_residual: whether to return the input x along with the output. This is for
564
+ performance reason: for post-norm architecture, returning the input allows us
565
+ to fuse the backward of nn.Linear with the residual connection.
566
+ """
567
+ assert checkpoint_lvl in [0, 1, 2]
568
+ assert activation in ["gelu_approx", "relu", "sqrelu"]
569
+ factory_kwargs = {"device": device, "dtype": dtype}
570
+ super().__init__()
571
+ out_features = out_features or in_features
572
+ hidden_features = hidden_features or in_features * 4
573
+ self.activation = activation
574
+ self.return_residual = return_residual
575
+ self.checkpoint_lvl = checkpoint_lvl
576
+ self.heuristic = heuristic if activation != "sqrelu" else -1
577
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1, **factory_kwargs)
578
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs)
579
+
580
+ def forward(self, x, process_group=None):
581
+ dtype = x.dtype if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype()
582
+ if self.heuristic == "auto":
583
+ if self.activation == "gelu_approx":
584
+ if torch.cuda.get_device_capability("cuda") == (9, 0):
585
+ heuristic = -1
586
+ else:
587
+ cuda_ver = tuple(map(int, torch.version.cuda.split(".")))
588
+ heuristic = 0 if cuda_ver >= (11, 8) else (1 if dtype == torch.float16 else -1)
589
+ else:
590
+ heuristic = 0
591
+ else:
592
+ heuristic = self.heuristic
593
+ out = fused_mlp_func(
594
+ x,
595
+ self.fc1.weight,
596
+ self.fc2.weight,
597
+ self.fc1.bias,
598
+ self.fc2.bias,
599
+ activation=self.activation,
600
+ save_pre_act=self.training,
601
+ return_residual=self.return_residual,
602
+ checkpoint_lvl=self.checkpoint_lvl,
603
+ heuristic=heuristic,
604
+ process_group=process_group,
605
+ )
606
+ if self.return_residual:
607
+ out, x = out
608
+ if process_group is not None:
609
+ out = reduce_scatter(out, process_group)
610
+ return out if not self.return_residual else (out, x)
611
+
612
+
613
+ class ParallelFusedMLP(nn.Module):
614
+ def __init__(
615
+ self,
616
+ in_features,
617
+ hidden_features=None,
618
+ out_features=None,
619
+ activation="gelu_approx",
620
+ process_group: ProcessGroup = None,
621
+ bias1=True,
622
+ bias2=True,
623
+ sequence_parallel=True,
624
+ checkpoint_lvl=0,
625
+ heuristic="auto",
626
+ device=None,
627
+ dtype=None,
628
+ ):
629
+ """
630
+ process_group is required. We're doing Tensor Parallel with sequence parallelism:
631
+ we do an all_gather of x before doing the matmul, gelu, then matmul.
632
+ Finally we do a reduce_scatter of the output.
633
+
634
+ checkpoint_lvl (increasing lvl means slower but more memory saving):
635
+ 0: no recomputation in the bwd
636
+ 1: recompute gelu_out in the bwd
637
+ 2: recompute pre_act and gelu_out in the bwd
638
+ heuristic:
639
+ -1: don't fuse gemm + gelu (separate kernel)
640
+ 0..4: use this heuristic for the algo section in the fused gemm + gelu
641
+ 'auto': heuristic will be picked automatically:
642
+ For CUDA >= 11.8, we set heuristic=0 for both fp16 and bf16 for best perf.
643
+ For CUDA <= 11.7, we set heuristic=1 for fp16 and heuristic=-1 for bf16.
644
+ """
645
+ assert checkpoint_lvl in [0, 1, 2]
646
+ assert activation in ["gelu_approx", "relu", "sqrelu"]
647
+ assert process_group is not None
648
+ factory_kwargs = {"device": device, "dtype": dtype}
649
+ super().__init__()
650
+ out_features = out_features or in_features
651
+ hidden_features = hidden_features or in_features * 4
652
+ self.activation = activation
653
+ self.process_group = process_group
654
+ self.sequence_parallel = sequence_parallel
655
+ self.checkpoint_lvl = checkpoint_lvl
656
+ self.heuristic = heuristic if activation != "sqrelu" else -1
657
+ self.fc1 = ColumnParallelLinear(
658
+ in_features, hidden_features, process_group, bias=bias1, **factory_kwargs
659
+ )
660
+ self.fc2 = RowParallelLinear(
661
+ hidden_features, out_features, process_group, bias=bias2, **factory_kwargs
662
+ )
663
+
664
+ def forward(self, x):
665
+ dtype = x.dtype if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype()
666
+ if self.heuristic == "auto":
667
+ if self.activation == "gelu_approx":
668
+ cuda_ver = tuple(map(int, torch.version.cuda.split(".")))
669
+ heuristic = 0 if cuda_ver >= (11, 8) else (1 if dtype == torch.float16 else -1)
670
+ else:
671
+ heuristic = 0
672
+ else:
673
+ heuristic = self.heuristic
674
+ out = fused_mlp_func(
675
+ x,
676
+ self.fc1.weight,
677
+ self.fc2.weight,
678
+ self.fc1.bias,
679
+ self.fc2.bias,
680
+ activation=self.activation,
681
+ save_pre_act=self.training,
682
+ checkpoint_lvl=self.checkpoint_lvl,
683
+ heuristic=heuristic,
684
+ process_group=self.process_group,
685
+ sequence_parallel=self.sequence_parallel,
686
+ )
687
+ reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce
688
+ return reduce_fn(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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, Tri Dao.
2
+ # Adapted from https://github.com/NVIDIA/apex/blob/master/apex/contrib/layer_norm/layer_norm.py
3
+
4
+ import dropout_layer_norm
5
+ import torch
6
+ from torch.nn import init
7
+
8
+
9
+ def maybe_align(x, alignment_in_bytes=16):
10
+ """Assume that x already has last dim divisible by alignment_in_bytes"""
11
+ # TD [2023-07-04] I'm not 100% sure that clone will align the memory
12
+ # https://discuss.pytorch.org/t/how-to-ensure-that-tensor-data-ptr-is-aligned-to-16-bytes/183440
13
+ return x if x.data_ptr() % alignment_in_bytes == 0 else x.clone()
14
+
15
+
16
+ def _dropout_add_layer_norm_forward(
17
+ x0,
18
+ residual,
19
+ gamma,
20
+ beta,
21
+ rowscale,
22
+ colscale,
23
+ dropout_p,
24
+ epsilon,
25
+ residual_in_fp32=False,
26
+ is_rms_norm=False,
27
+ ):
28
+ """Assume that arguments are contiguous and aligned to 16 bytes"""
29
+ hidden_size = gamma.numel()
30
+ x0mat = x0.view((-1, hidden_size))
31
+ residualmat = residual.view((-1, hidden_size)) if residual is not None else None
32
+ rowscale = rowscale.view(-1) if rowscale is not None else None
33
+ zmat, xmat, dmask, mu, rsigma = dropout_layer_norm.dropout_add_ln_fwd(
34
+ x0mat,
35
+ residualmat,
36
+ gamma,
37
+ beta,
38
+ rowscale,
39
+ colscale,
40
+ None,
41
+ None,
42
+ dropout_p,
43
+ epsilon,
44
+ 1.0,
45
+ 0,
46
+ None,
47
+ residual_in_fp32,
48
+ is_rms_norm,
49
+ )
50
+ # dmask is None if dropout_p == 0.0
51
+ # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype
52
+ return zmat, xmat if xmat is not None else x0mat, dmask, mu, rsigma
53
+
54
+
55
+ def _dropout_add_layer_norm_backward(
56
+ dz,
57
+ dx,
58
+ x,
59
+ x0,
60
+ dmask,
61
+ mu,
62
+ rsigma,
63
+ gamma,
64
+ rowscale,
65
+ colscale,
66
+ dropout_p,
67
+ has_residual,
68
+ is_rms_norm=False,
69
+ ):
70
+ """Assume that arguments are contiguous and aligned to 16 bytes
71
+ dx == None means that it was a post-norm architecture
72
+ (x = drop(x0) + residual was not returned in the fwd).
73
+ x0 must not be None if we have colscale.
74
+ """
75
+ hidden_size = gamma.numel()
76
+ xmat = x.view((-1, hidden_size))
77
+ dzmat = dz.view(xmat.shape)
78
+ dxmat = dx.view(xmat.shape) if dx is not None else None
79
+ x0mat = x0.view((-1, hidden_size)) if x0 is not None else None
80
+ rowscale = rowscale.view(-1) if rowscale is not None else None
81
+ if colscale is not None:
82
+ assert x0 is not None, "x0 is required to compute the gradient of colscale"
83
+ dx0mat, dresidualmat, dgamma, dbeta, _, _, *rest = dropout_layer_norm.dropout_add_ln_bwd(
84
+ dzmat,
85
+ dxmat,
86
+ xmat,
87
+ x0mat,
88
+ dmask,
89
+ mu,
90
+ rsigma,
91
+ gamma,
92
+ rowscale,
93
+ colscale,
94
+ None,
95
+ None,
96
+ dropout_p,
97
+ 1.0,
98
+ 0,
99
+ has_residual,
100
+ is_rms_norm,
101
+ )
102
+ # dresidualmat is None if not has_residual
103
+ if colscale is None:
104
+ return dx0mat, dresidualmat, dgamma, dbeta
105
+ else:
106
+ dcolscale = rest[0]
107
+ return dx0mat, dresidualmat, dgamma, dbeta, dcolscale
108
+
109
+
110
+ def _dropout_add_layer_norm_subset_forward(
111
+ x0,
112
+ residual,
113
+ gamma,
114
+ beta,
115
+ colscale,
116
+ x0_subset,
117
+ out_subset,
118
+ dropout_p,
119
+ epsilon,
120
+ rowscale_const,
121
+ out_numrows,
122
+ residual_in_fp32=False,
123
+ is_rms_norm=False,
124
+ ):
125
+ """Assume that arguments are contiguous and aligned to 16 bytes"""
126
+ hidden_size = gamma.numel()
127
+ x0mat = x0.view((-1, hidden_size))
128
+ residualmat = residual.view((-1, hidden_size)) if residual is not None else None
129
+ x0_subset = x0_subset.view(-1) if x0_subset is not None else None
130
+ out_subset = out_subset.view(-1) if out_subset is not None else None
131
+ zmat, xmat, dmask, mu, rsigma = dropout_layer_norm.dropout_add_ln_fwd(
132
+ x0mat,
133
+ residualmat,
134
+ gamma,
135
+ beta,
136
+ None,
137
+ colscale,
138
+ x0_subset,
139
+ out_subset,
140
+ dropout_p,
141
+ epsilon,
142
+ rowscale_const,
143
+ out_numrows,
144
+ None,
145
+ residual_in_fp32,
146
+ is_rms_norm,
147
+ )
148
+ # dmask is None if dropout_p == 0.0
149
+ # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype
150
+ return zmat, xmat if xmat is not None else x0mat, dmask, mu, rsigma
151
+
152
+
153
+ def _dropout_add_layer_norm_subset_backward(
154
+ dz,
155
+ dx,
156
+ x,
157
+ x0,
158
+ dmask,
159
+ mu,
160
+ rsigma,
161
+ gamma,
162
+ colscale,
163
+ x0_subset,
164
+ out_subset,
165
+ dropout_p,
166
+ rowscale_const,
167
+ x0_numrows,
168
+ has_residual,
169
+ is_rms_norm=False,
170
+ ):
171
+ """Assume that arguments are contiguous and aligned to 16 bytes
172
+ dx == None means that it was a post-norm architecture
173
+ (x = drop(x0) + residual was not returned in the fwd).
174
+ x0 must not be None if we have colscale.
175
+ """
176
+ hidden_size = gamma.numel()
177
+ xmat = x.view((-1, hidden_size))
178
+ dzmat = dz.view(-1, hidden_size)
179
+ dxmat = dx.view(xmat.shape) if dx is not None else None
180
+ x0mat = x0.view((-1, hidden_size)) if x0 is not None else None
181
+ x0_subset = x0_subset.view(-1) if x0_subset is not None else None
182
+ out_subset = out_subset.view(-1) if out_subset is not None else None
183
+ if colscale is not None:
184
+ assert x0 is not None, "x0 is required to compute the gradient of colscale"
185
+ dx0mat, dresidualmat, dgamma, dbeta, _, _, *rest = dropout_layer_norm.dropout_add_ln_bwd(
186
+ dzmat,
187
+ dxmat,
188
+ xmat,
189
+ x0mat,
190
+ dmask,
191
+ mu,
192
+ rsigma,
193
+ gamma,
194
+ None,
195
+ colscale,
196
+ x0_subset,
197
+ out_subset,
198
+ dropout_p,
199
+ rowscale_const,
200
+ x0_numrows,
201
+ has_residual,
202
+ is_rms_norm,
203
+ )
204
+ # dresidualmat is None if not has_residual
205
+ if colscale is None:
206
+ return dx0mat, dresidualmat, dgamma, dbeta
207
+ else:
208
+ dcolscale = rest[0]
209
+ return dx0mat, dresidualmat, dgamma, dbeta, dcolscale
210
+
211
+
212
+ def _dropout_add_layer_norm_parallel_residual_forward(
213
+ x0,
214
+ x1,
215
+ residual,
216
+ gamma0,
217
+ beta0,
218
+ gamma1,
219
+ beta1,
220
+ dropout_p,
221
+ epsilon,
222
+ residual_in_fp32=False,
223
+ is_rms_norm=False,
224
+ ):
225
+ """Assume that arguments are contiguous and aligned to 16 bytes"""
226
+ hidden_size = gamma0.numel()
227
+ x0mat = x0.view((-1, hidden_size))
228
+ x1mat = x1.view((-1, hidden_size)) if x1 is not None else None
229
+ residualmat = residual.view((-1, hidden_size)) if residual is not None else None
230
+ (
231
+ z0mat,
232
+ z1mat,
233
+ xmat,
234
+ dmask0,
235
+ dmask1,
236
+ mu,
237
+ rsigma,
238
+ ) = dropout_layer_norm.dropout_add_ln_parallel_residual_fwd(
239
+ x0mat,
240
+ x1mat,
241
+ residualmat,
242
+ gamma0,
243
+ beta0,
244
+ gamma1,
245
+ beta1,
246
+ dropout_p,
247
+ epsilon,
248
+ None,
249
+ residual_in_fp32,
250
+ is_rms_norm,
251
+ )
252
+ # dmask0 and dmask1 are None if dropout_p == 0.0
253
+ # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype
254
+ return z0mat, z1mat, xmat if xmat is not None else x0mat, dmask0, dmask1, mu, rsigma
255
+
256
+
257
+ def _dropout_add_layer_norm_parallel_residual_backward(
258
+ dz0,
259
+ dz1,
260
+ dx,
261
+ x,
262
+ dmask0,
263
+ dmask1,
264
+ mu,
265
+ rsigma,
266
+ gamma0,
267
+ gamma1,
268
+ dropout_p,
269
+ has_x1,
270
+ has_residual,
271
+ is_rms_norm=False,
272
+ ):
273
+ """Assume that arguments are contiguous and aligned to 16 bytes
274
+ dx == None means that it was a post-norm architecture
275
+ (x = drop(x0) + residual was not returned in the fwd).
276
+ """
277
+ hidden_size = gamma0.numel()
278
+ xmat = x.view((-1, hidden_size))
279
+ dz0mat = dz0.view(xmat.shape)
280
+ dz1mat = dz1.view(xmat.shape) if dz1 is not None else None
281
+ dxmat = dx.view(xmat.shape) if dx is not None else None
282
+ (
283
+ dx0mat,
284
+ dx1mat,
285
+ dresidualmat,
286
+ dgamma0,
287
+ dbeta0,
288
+ dgamma1,
289
+ dbeta1,
290
+ *rest,
291
+ ) = dropout_layer_norm.dropout_add_ln_parallel_residual_bwd(
292
+ dz0mat,
293
+ dz1mat,
294
+ dxmat,
295
+ xmat,
296
+ dmask0,
297
+ dmask1,
298
+ mu,
299
+ rsigma,
300
+ gamma0,
301
+ gamma1,
302
+ dropout_p,
303
+ has_x1,
304
+ has_residual,
305
+ is_rms_norm,
306
+ )
307
+ # dresidualmat is None if not has_residual
308
+ return dx0mat, dx1mat, dresidualmat, dgamma0, dbeta0, dgamma1, dbeta1
309
+
310
+
311
+ class DropoutAddLayerNormFn(torch.autograd.Function):
312
+ @staticmethod
313
+ def forward(
314
+ ctx,
315
+ x0,
316
+ residual,
317
+ gamma,
318
+ beta,
319
+ rowscale,
320
+ colscale,
321
+ dropout_p,
322
+ epsilon,
323
+ residual_in_fp32=False,
324
+ prenorm=False,
325
+ is_rms_norm=False,
326
+ return_dmask=False,
327
+ ):
328
+ x0 = maybe_align(x0.contiguous(), 16)
329
+ residual = maybe_align(residual.contiguous(), 16) if residual is not None else None
330
+ gamma = maybe_align(gamma.contiguous(), 16)
331
+ beta = maybe_align(beta.contiguous(), 16) if beta is not None else None
332
+ rowscale = maybe_align(rowscale.contiguous(), 16) if rowscale is not None else None
333
+ colscale = maybe_align(colscale.contiguous(), 16) if colscale is not None else None
334
+ zmat, xmat, dmask, mu, rsigma = _dropout_add_layer_norm_forward(
335
+ x0,
336
+ residual,
337
+ gamma,
338
+ beta,
339
+ rowscale,
340
+ colscale,
341
+ dropout_p,
342
+ epsilon,
343
+ residual_in_fp32,
344
+ is_rms_norm,
345
+ )
346
+ # Only need to save x0 if we need to compute gradient wrt colscale
347
+ x0_saved = x0 if colscale is not None else None
348
+ ctx.save_for_backward(
349
+ xmat.view(x0.shape), x0_saved, dmask, gamma, mu, rsigma, rowscale, colscale
350
+ )
351
+ ctx.prenorm = prenorm
352
+ ctx.dropout_p = dropout_p
353
+ ctx.has_residual = residual is not None
354
+ ctx.is_rms_norm = is_rms_norm
355
+ ctx.has_beta = beta is not None
356
+ if not return_dmask:
357
+ return (
358
+ zmat.view(x0.shape) if not prenorm else (zmat.view(x0.shape), xmat.view(x0.shape))
359
+ )
360
+ else:
361
+ dmask = (
362
+ dmask.view(x0.shape)
363
+ if dropout_p > 0.0
364
+ else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)
365
+ )
366
+ ctx.mark_non_differentiable(dmask)
367
+ return (
368
+ (zmat.view(x0.shape), dmask)
369
+ if not prenorm
370
+ else (zmat.view(x0.shape), xmat.view(x0.shape), dmask)
371
+ )
372
+
373
+ @staticmethod
374
+ def backward(ctx, dz, *args):
375
+ # assert dz.is_contiguous()
376
+ dz = maybe_align(dz.contiguous(), 16) # this happens!
377
+ dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None
378
+ x, x0, dmask, gamma, mu, rsigma, rowscale, colscale = ctx.saved_tensors
379
+ # x0 is None if colscale is None
380
+ dropout_p = ctx.dropout_p
381
+ has_residual = ctx.has_residual
382
+ dx0mat, dresidualmat, dgamma, dbeta, *rest = _dropout_add_layer_norm_backward(
383
+ dz,
384
+ dx,
385
+ x,
386
+ x0,
387
+ dmask,
388
+ mu,
389
+ rsigma,
390
+ gamma,
391
+ rowscale,
392
+ colscale,
393
+ dropout_p,
394
+ has_residual,
395
+ ctx.is_rms_norm,
396
+ )
397
+ dx0 = dx0mat.view(x.shape)
398
+ dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None
399
+ dcolscale = rest[0] if colscale is not None else None
400
+ return (
401
+ dx0,
402
+ dresidual,
403
+ dgamma,
404
+ dbeta if ctx.has_beta else None,
405
+ None,
406
+ dcolscale,
407
+ None,
408
+ None,
409
+ None,
410
+ None,
411
+ None,
412
+ None,
413
+ )
414
+
415
+
416
+ class DropoutAddLayerNormSubsetFn(torch.autograd.Function):
417
+ @staticmethod
418
+ def forward(
419
+ ctx,
420
+ x0,
421
+ residual,
422
+ gamma,
423
+ beta,
424
+ colscale,
425
+ x0_subset,
426
+ out_subset,
427
+ dropout_p,
428
+ epsilon,
429
+ rowscale_const,
430
+ out_numrows,
431
+ residual_in_fp32=False,
432
+ prenorm=False,
433
+ is_rms_norm=False,
434
+ return_dmask=False,
435
+ ):
436
+ x0 = maybe_align(x0.contiguous(), 16)
437
+ residual = maybe_align(residual.contiguous(), 16) if residual is not None else None
438
+ gamma = maybe_align(gamma.contiguous(), 16)
439
+ beta = maybe_align(beta.contiguous(), 16) if beta is not None else None
440
+ colscale = maybe_align(colscale.contiguous(), 16) if colscale is not None else None
441
+ zmat, xmat, dmask, mu, rsigma = _dropout_add_layer_norm_subset_forward(
442
+ x0,
443
+ residual,
444
+ gamma,
445
+ beta,
446
+ colscale,
447
+ x0_subset,
448
+ out_subset,
449
+ dropout_p,
450
+ epsilon,
451
+ rowscale_const,
452
+ out_numrows,
453
+ residual_in_fp32,
454
+ is_rms_norm,
455
+ )
456
+ # Only need to save x0 if we need to compute gradient wrt colscale
457
+ x0_saved = x0 if colscale is not None else None
458
+ x_shape = (-1, *x0.shape[1:])
459
+ ctx.save_for_backward(
460
+ xmat.view(x_shape), x0_saved, dmask, gamma, mu, rsigma, colscale, x0_subset, out_subset
461
+ )
462
+ ctx.prenorm = prenorm
463
+ ctx.dropout_p = dropout_p
464
+ ctx.rowscale_const = rowscale_const
465
+ ctx.x0_numrows = x0.shape[:-1].numel()
466
+ ctx.has_residual = residual is not None
467
+ ctx.is_rms_norm = is_rms_norm
468
+ ctx.has_beta = beta is not None
469
+ z_shape = (-1, *x0.shape[1:])
470
+ if not return_dmask:
471
+ return zmat.view(z_shape) if not prenorm else (zmat.view(z_shape), xmat.view(x0.shape))
472
+ else:
473
+ z = zmat.view(z_shape)
474
+ dmask = (
475
+ dmask.view(x0.shape)
476
+ if dropout_p > 0.0
477
+ else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)
478
+ )
479
+ ctx.mark_non_differentiable(dmask)
480
+ return (z, dmask) if not prenorm else (z, xmat.view(x_shape), dmask)
481
+
482
+ @staticmethod
483
+ def backward(ctx, dz, *args):
484
+ # assert dz.is_contiguous()
485
+ dz = maybe_align(dz.contiguous(), 16) # this happens!
486
+ dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None
487
+ x, x0, dmask, gamma, mu, rsigma, colscale, x0_subset, out_subset = ctx.saved_tensors
488
+ # x0 is None if colscale is None
489
+ dropout_p = ctx.dropout_p
490
+ has_residual = ctx.has_residual
491
+ dx0mat, dresidualmat, dgamma, dbeta, *rest = _dropout_add_layer_norm_subset_backward(
492
+ dz,
493
+ dx,
494
+ x,
495
+ x0,
496
+ dmask,
497
+ mu,
498
+ rsigma,
499
+ gamma,
500
+ colscale,
501
+ x0_subset,
502
+ out_subset,
503
+ dropout_p,
504
+ ctx.rowscale_const,
505
+ ctx.x0_numrows,
506
+ has_residual,
507
+ ctx.is_rms_norm,
508
+ )
509
+ dx0 = dx0mat.view(-1, *x.shape[1:])
510
+ dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None
511
+ dcolscale = rest[0] if colscale is not None else None
512
+ return (
513
+ dx0,
514
+ dresidual,
515
+ dgamma,
516
+ dbeta if ctx.has_beta else None,
517
+ dcolscale,
518
+ None,
519
+ None,
520
+ None,
521
+ None,
522
+ None,
523
+ None,
524
+ None,
525
+ None,
526
+ None,
527
+ None,
528
+ )
529
+
530
+
531
+ class DropoutAddLayerNormParallelResidualFn(torch.autograd.Function):
532
+ @staticmethod
533
+ def forward(
534
+ ctx,
535
+ x0,
536
+ x1,
537
+ residual,
538
+ gamma0,
539
+ beta0,
540
+ gamma1,
541
+ beta1,
542
+ dropout_p,
543
+ epsilon,
544
+ residual_in_fp32=False,
545
+ prenorm=False,
546
+ is_rms_norm=False,
547
+ return_dmask=False,
548
+ ):
549
+ x0 = maybe_align(x0.contiguous(), 16)
550
+ x1 = maybe_align(x1.contiguous(), 16) if x1 is not None else None
551
+ residual = maybe_align(residual.contiguous(), 16) if residual is not None else None
552
+ gamma0 = maybe_align(gamma0.contiguous(), 16)
553
+ beta0 = maybe_align(beta0.contiguous(), 16) if beta0 is not None else None
554
+ gamma1 = maybe_align(gamma1.contiguous(), 16) if gamma1 is not None else None
555
+ beta1 = maybe_align(beta1.contiguous(), 16) if beta1 is not None else None
556
+ (
557
+ z0mat,
558
+ z1mat,
559
+ xmat,
560
+ dmask0,
561
+ dmask1,
562
+ mu,
563
+ rsigma,
564
+ ) = _dropout_add_layer_norm_parallel_residual_forward(
565
+ x0,
566
+ x1,
567
+ residual,
568
+ gamma0,
569
+ beta0,
570
+ gamma1,
571
+ beta1,
572
+ dropout_p,
573
+ epsilon,
574
+ residual_in_fp32,
575
+ is_rms_norm,
576
+ )
577
+ ctx.save_for_backward(xmat.view(x0.shape), dmask0, dmask1, gamma0, gamma1, mu, rsigma)
578
+ ctx.prenorm = prenorm
579
+ ctx.dropout_p = dropout_p
580
+ ctx.has_x1 = x1 is not None
581
+ ctx.has_residual = residual is not None
582
+ ctx.is_rms_norm = is_rms_norm
583
+ ctx.has_beta = beta0 is not None
584
+ z = (z0mat.view(x0.shape), z1mat.view(x0.shape) if z1mat is not None else None)
585
+ if not return_dmask:
586
+ return z if not prenorm else (*z, xmat.view(x0.shape))
587
+ else:
588
+ dmask0 = (
589
+ dmask0.view(x0.shape)
590
+ if dropout_p > 0.0
591
+ else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)
592
+ )
593
+ dmask1 = (
594
+ dmask1.view(x0.shape)
595
+ if dropout_p > 0.0 and x1 is not None
596
+ else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device)
597
+ )
598
+ ctx.mark_non_differentiable(dmask0)
599
+ ctx.mark_non_differentiable(dmask1)
600
+ return (
601
+ (*z, dmask0, dmask1) if not prenorm else (*z, xmat.view(x0.shape), dmask0, dmask1)
602
+ )
603
+
604
+ @staticmethod
605
+ def backward(ctx, dz0, dz1, *args):
606
+ dz0 = maybe_align(dz0.contiguous(), 16) # this happens!
607
+ dz1 = maybe_align(dz1.contiguous(), 16) if dz1 is not None else None
608
+ dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None
609
+ x, dmask0, dmask1, gamma0, gamma1, mu, rsigma = ctx.saved_tensors
610
+ dropout_p = ctx.dropout_p
611
+ has_x1 = ctx.has_x1
612
+ has_residual = ctx.has_residual
613
+ (
614
+ dx0mat,
615
+ dx1mat,
616
+ dresidualmat,
617
+ dgamma0,
618
+ dbeta0,
619
+ dgamma1,
620
+ dbeta1,
621
+ ) = _dropout_add_layer_norm_parallel_residual_backward(
622
+ dz0,
623
+ dz1,
624
+ dx,
625
+ x,
626
+ dmask0,
627
+ dmask1,
628
+ mu,
629
+ rsigma,
630
+ gamma0,
631
+ gamma1,
632
+ dropout_p,
633
+ has_x1,
634
+ has_residual,
635
+ ctx.is_rms_norm,
636
+ )
637
+ dx0 = dx0mat.view(x.shape)
638
+ dx1 = dx1mat.view(x.shape) if dx1mat is not None else None
639
+ dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None
640
+ return (
641
+ dx0,
642
+ dx1,
643
+ dresidual,
644
+ dgamma0,
645
+ dbeta0 if ctx.has_beta else None,
646
+ dgamma1,
647
+ dbeta1 if ctx.has_beta else None,
648
+ None,
649
+ None,
650
+ None,
651
+ None,
652
+ None,
653
+ None,
654
+ )
655
+
656
+
657
+ def layer_norm(x, weight, bias, epsilon):
658
+ return DropoutAddLayerNormFn.apply(x, None, weight, bias, None, None, 0.0, epsilon, False)
659
+
660
+
661
+ def dropout_add_layer_norm(
662
+ x0,
663
+ residual,
664
+ weight,
665
+ bias,
666
+ dropout_p,
667
+ epsilon,
668
+ rowscale=None,
669
+ layerscale=None,
670
+ prenorm=False,
671
+ residual_in_fp32=False,
672
+ return_dropout_mask=False,
673
+ ):
674
+ """residual_in_fp32 only has an effect if residual is None.
675
+ Otherwise residual dtype is residual.dtype.
676
+ """
677
+ return DropoutAddLayerNormFn.apply(
678
+ x0,
679
+ residual,
680
+ weight,
681
+ bias,
682
+ rowscale,
683
+ layerscale,
684
+ dropout_p,
685
+ epsilon,
686
+ residual_in_fp32,
687
+ prenorm,
688
+ False,
689
+ return_dropout_mask,
690
+ )
691
+
692
+
693
+ def dropout_add_layer_norm_subset(
694
+ x0,
695
+ residual,
696
+ weight,
697
+ bias,
698
+ dropout_p,
699
+ epsilon,
700
+ layerscale=None,
701
+ x0_subset=None,
702
+ out_subset=None,
703
+ rowscale_const=1.0,
704
+ out_numrows=0,
705
+ prenorm=False,
706
+ residual_in_fp32=False,
707
+ return_dropout_mask=False,
708
+ ):
709
+ """residual_in_fp32 only has an effect if residual is None.
710
+ Otherwise residual dtype is residual.dtype.
711
+ """
712
+ return DropoutAddLayerNormSubsetFn.apply(
713
+ x0,
714
+ residual,
715
+ weight,
716
+ bias,
717
+ layerscale,
718
+ x0_subset,
719
+ out_subset,
720
+ dropout_p,
721
+ epsilon,
722
+ rowscale_const,
723
+ out_numrows,
724
+ residual_in_fp32,
725
+ prenorm,
726
+ False,
727
+ return_dropout_mask,
728
+ )
729
+
730
+
731
+ def dropout_add_layer_norm_parallel_residual(
732
+ x0,
733
+ x1,
734
+ residual,
735
+ weight0,
736
+ bias0,
737
+ weight1,
738
+ bias1,
739
+ dropout_p,
740
+ epsilon,
741
+ prenorm=False,
742
+ residual_in_fp32=False,
743
+ return_dropout_mask=False,
744
+ ):
745
+ """residual_in_fp32 only has an effect if residual is None.
746
+ Otherwise residual dtype is residual.dtype.
747
+ """
748
+ return DropoutAddLayerNormParallelResidualFn.apply(
749
+ x0,
750
+ x1,
751
+ residual,
752
+ weight0,
753
+ bias0,
754
+ weight1,
755
+ bias1,
756
+ dropout_p,
757
+ epsilon,
758
+ residual_in_fp32,
759
+ prenorm,
760
+ False,
761
+ return_dropout_mask,
762
+ )
763
+
764
+
765
+ class DropoutAddLayerNorm(torch.nn.Module):
766
+ def __init__(
767
+ self,
768
+ hidden_size,
769
+ prenorm=False,
770
+ p=0.0,
771
+ eps=1e-5,
772
+ residual_in_fp32=False,
773
+ device=None,
774
+ dtype=None,
775
+ ):
776
+ factory_kwargs = {"device": device, "dtype": dtype}
777
+ super().__init__()
778
+ self.prenorm = prenorm
779
+ self.p = p
780
+ self.eps = eps
781
+ self.residual_in_fp32 = residual_in_fp32
782
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
783
+ self.bias = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
784
+ self.reset_parameters()
785
+
786
+ def reset_parameters(self):
787
+ init.ones_(self.weight)
788
+ init.zeros_(self.bias)
789
+
790
+ def forward(self, x0, residual=None):
791
+ return dropout_add_layer_norm(
792
+ x0,
793
+ residual,
794
+ self.weight,
795
+ self.bias,
796
+ self.p if self.training else 0.0,
797
+ self.eps,
798
+ prenorm=self.prenorm,
799
+ residual_in_fp32=self.residual_in_fp32,
800
+ )
build/torch211-cxx11-cu128-aarch64-linux/ops/rms_norm.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, Tri Dao.
2
+ # Adapted from https://github.com/NVIDIA/apex/blob/master/apex/contrib/layer_norm/layer_norm.py
3
+
4
+ import torch
5
+ from torch.nn import init
6
+
7
+ from flash_attn.ops.layer_norm import (
8
+ DropoutAddLayerNormFn,
9
+ DropoutAddLayerNormParallelResidualFn,
10
+ DropoutAddLayerNormSubsetFn,
11
+ )
12
+
13
+
14
+ def rms_norm(x, weight, epsilon):
15
+ return DropoutAddLayerNormFn.apply(
16
+ x, None, weight, None, None, None, 0.0, epsilon, False, False, True
17
+ )
18
+
19
+
20
+ def dropout_add_rms_norm(
21
+ x0,
22
+ residual,
23
+ weight,
24
+ bias,
25
+ dropout_p,
26
+ epsilon,
27
+ rowscale=None,
28
+ layerscale=None,
29
+ prenorm=False,
30
+ residual_in_fp32=False,
31
+ return_dropout_mask=False,
32
+ ):
33
+ """residual_in_fp32 only has an effect if residual is None.
34
+ Otherwise residual dtype is residual.dtype.
35
+ """
36
+ return DropoutAddLayerNormFn.apply(
37
+ x0,
38
+ residual,
39
+ weight,
40
+ bias,
41
+ rowscale,
42
+ layerscale,
43
+ dropout_p,
44
+ epsilon,
45
+ residual_in_fp32,
46
+ prenorm,
47
+ True,
48
+ return_dropout_mask,
49
+ )
50
+
51
+
52
+ def dropout_add_rms_norm_subset(
53
+ x0,
54
+ residual,
55
+ weight,
56
+ bias,
57
+ dropout_p,
58
+ epsilon,
59
+ layerscale=None,
60
+ x0_subset=None,
61
+ out_subset=None,
62
+ rowscale_const=1.0,
63
+ out_numrows=0,
64
+ prenorm=False,
65
+ residual_in_fp32=False,
66
+ return_dropout_mask=False,
67
+ ):
68
+ """residual_in_fp32 only has an effect if residual is None.
69
+ Otherwise residual dtype is residual.dtype.
70
+ """
71
+ return DropoutAddLayerNormSubsetFn.apply(
72
+ x0,
73
+ residual,
74
+ weight,
75
+ bias,
76
+ layerscale,
77
+ x0_subset,
78
+ out_subset,
79
+ dropout_p,
80
+ epsilon,
81
+ rowscale_const,
82
+ out_numrows,
83
+ residual_in_fp32,
84
+ prenorm,
85
+ True,
86
+ return_dropout_mask,
87
+ )
88
+
89
+
90
+ def dropout_add_rms_norm_parallel_residual(
91
+ x0,
92
+ x1,
93
+ residual,
94
+ weight0,
95
+ bias0,
96
+ weight1,
97
+ bias1,
98
+ dropout_p,
99
+ epsilon,
100
+ prenorm=False,
101
+ residual_in_fp32=False,
102
+ return_dropout_mask=False,
103
+ ):
104
+ """residual_in_fp32 only has an effect if residual is None.
105
+ Otherwise residual dtype is residual.dtype.
106
+ """
107
+ return DropoutAddLayerNormParallelResidualFn.apply(
108
+ x0,
109
+ x1,
110
+ residual,
111
+ weight0,
112
+ bias0,
113
+ weight1,
114
+ bias1,
115
+ dropout_p,
116
+ epsilon,
117
+ residual_in_fp32,
118
+ prenorm,
119
+ True,
120
+ return_dropout_mask,
121
+ )
122
+
123
+
124
+ class RMSNorm(torch.nn.Module):
125
+ def __init__(self, hidden_size, eps=1e-5, device=None, dtype=None):
126
+ factory_kwargs = {"device": device, "dtype": dtype}
127
+ super().__init__()
128
+ self.eps = eps
129
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
130
+ self.register_parameter("bias", None)
131
+ self.reset_parameters()
132
+
133
+ def reset_parameters(self):
134
+ init.ones_(self.weight)
135
+
136
+ def forward(self, x):
137
+ return rms_norm(x, self.weight, self.eps)
138
+
139
+
140
+ class DropoutAddRMSNorm(torch.nn.Module):
141
+ def __init__(
142
+ self,
143
+ hidden_size,
144
+ prenorm=False,
145
+ p=0.0,
146
+ eps=1e-5,
147
+ residual_in_fp32=False,
148
+ device=None,
149
+ dtype=None,
150
+ ):
151
+ factory_kwargs = {"device": device, "dtype": dtype}
152
+ super().__init__()
153
+ self.prenorm = prenorm
154
+ self.p = p
155
+ self.eps = eps
156
+ self.residual_in_fp32 = residual_in_fp32
157
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
158
+ self.register_parameter("bias", None)
159
+ self.reset_parameters()
160
+
161
+ def reset_parameters(self):
162
+ init.ones_(self.weight)
163
+
164
+ def forward(self, x0, residual=None):
165
+ return dropout_add_rms_norm(
166
+ x0,
167
+ residual,
168
+ self.weight,
169
+ None,
170
+ self.p if self.training else 0.0,
171
+ self.eps,
172
+ prenorm=self.prenorm,
173
+ residual_in_fp32=self.residual_in_fp32,
174
+ )
build/torch211-cxx11-cu128-aarch64-linux/ops/triton/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
build/torch211-cxx11-cu128-aarch64-linux/ops/triton/cross_entropy.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ from typing import Tuple, Optional, Union
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+ import triton
9
+ import triton.language as tl
10
+
11
+ # `all_gather_into_tensor` and `reduce_scatter_tensor` are new placeholders for
12
+ # `_all_gather_base` and `_reduce_scatter_base`. They require the most recent
13
+ # version of PyTorch. The following 2 lines are for backward compatibility with
14
+ # older PyTorch.
15
+ if "all_gather_into_tensor" not in dir(torch.distributed):
16
+ torch.distributed.all_gather_into_tensor = torch.distributed._all_gather_base
17
+
18
+
19
+ @triton.heuristics(
20
+ {
21
+ "HAS_SMOOTHING": lambda args: args["smoothing"] > 0.0,
22
+ }
23
+ )
24
+ @triton.jit
25
+ def cross_entropy_fwd_kernel(
26
+ loss_ptr, # data ptrs
27
+ lse_ptr,
28
+ z_loss_ptr,
29
+ logits_ptr,
30
+ labels_ptr,
31
+ smoothing,
32
+ logit_scale,
33
+ lse_square_scale,
34
+ ignore_index,
35
+ total_classes,
36
+ class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes
37
+ n_cols, # shapes
38
+ logits_row_stride, # strides
39
+ BLOCK_SIZE: tl.constexpr,
40
+ HAS_SMOOTHING: tl.constexpr,
41
+ # if SPLIT (e.g. tensor parallel), don't include the LSE in the loss since it's not the final LSE
42
+ SPLIT: tl.constexpr,
43
+ PRECOMPUTED_LSE: tl.constexpr, # If LSE is already computed (also no smoothing and logit_scale == 1.0)
44
+ ):
45
+ row_idx = tl.program_id(0)
46
+ logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64)
47
+ sum_logits = 0.0 # For smoothing
48
+ if not PRECOMPUTED_LSE:
49
+ # Statistics for online softmax
50
+ m_i = -float("inf")
51
+ l_i = 0.0
52
+ for col_offset in range(0, n_cols, BLOCK_SIZE):
53
+ cols = col_offset + tl.arange(0, BLOCK_SIZE)
54
+ logits = tl.load(logits_ptr + cols, mask=cols < n_cols, other=-float("inf")).to(
55
+ tl.float32
56
+ ) * logit_scale
57
+ if HAS_SMOOTHING:
58
+ sum_logits += tl.sum(tl.where(cols < n_cols, logits, 0.0))
59
+ m_i_new = tl.maximum(m_i, tl.max(logits))
60
+ l_i = tl.exp(m_i - m_i_new) * l_i + tl.sum(tl.exp(logits - m_i_new))
61
+ m_i = m_i_new
62
+ lse = tl.log(l_i) + m_i
63
+ tl.store(lse_ptr + row_idx, lse)
64
+ else:
65
+ lse = tl.load(lse_ptr + row_idx)
66
+ label_idx = tl.load(labels_ptr + row_idx)
67
+ if label_idx == ignore_index:
68
+ loss = 0.0
69
+ z_loss = 0.0
70
+ else:
71
+ label_idx -= class_start_idx
72
+ if label_idx >= 0 and label_idx < n_cols:
73
+ logits_label = tl.load(logits_ptr + label_idx) * logit_scale
74
+ if HAS_SMOOTHING:
75
+ loss = (
76
+ (lse if not SPLIT else 0.0)
77
+ - smoothing * sum_logits / total_classes
78
+ - (1 - smoothing) * logits_label
79
+ )
80
+ else:
81
+ loss = (lse if not SPLIT else 0.0) - logits_label
82
+ else:
83
+ # If label is out of bounds, we set the CE loss to 0.0. But we still want the smoothing loss
84
+ if HAS_SMOOTHING:
85
+ loss = smoothing * ((lse if not SPLIT else 0.0) - sum_logits / total_classes)
86
+ else:
87
+ loss = 0.0
88
+ if not SPLIT:
89
+ z_loss = lse_square_scale * lse * lse
90
+ loss += z_loss
91
+ else:
92
+ z_loss = 0.0
93
+ tl.store(loss_ptr + row_idx, loss)
94
+ if not SPLIT:
95
+ tl.store(z_loss_ptr + row_idx, z_loss)
96
+
97
+
98
+ @triton.heuristics(
99
+ {
100
+ "HAS_SMOOTHING": lambda args: args["smoothing"] > 0.0,
101
+ }
102
+ )
103
+ @triton.jit
104
+ def cross_entropy_bwd_kernel(
105
+ dlogits_ptr, # data ptrs
106
+ dloss_ptr,
107
+ logits_ptr,
108
+ lse_ptr,
109
+ labels_ptr,
110
+ smoothing,
111
+ logit_scale,
112
+ lse_square_scale,
113
+ ignore_index,
114
+ total_classes,
115
+ class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes
116
+ n_cols, # shapes
117
+ logits_row_stride, # strides
118
+ dlogits_row_stride,
119
+ dloss_row_stride,
120
+ BLOCK_SIZE: tl.constexpr,
121
+ HAS_SMOOTHING: tl.constexpr,
122
+ ):
123
+ row_idx = tl.program_id(0)
124
+ col_block_idx = tl.program_id(1)
125
+ logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64)
126
+ dlogits_ptr = dlogits_ptr + row_idx * dlogits_row_stride.to(tl.int64)
127
+ col_offsets = col_block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
128
+ label_idx = tl.load(labels_ptr + row_idx)
129
+ if label_idx != ignore_index:
130
+ dloss = tl.load(dloss_ptr + row_idx * dloss_row_stride)
131
+ else:
132
+ dloss = 0.0
133
+ logits = tl.load(logits_ptr + col_offsets, mask=col_offsets < n_cols, other=-float("inf")).to(
134
+ tl.float32
135
+ ) * logit_scale
136
+ lse = tl.load(lse_ptr + row_idx)
137
+ probs = tl.exp(logits - lse)
138
+ probs += 2.0 * lse_square_scale * lse * probs
139
+ label_idx -= class_start_idx
140
+ if HAS_SMOOTHING:
141
+ smooth_positive = 1.0 - smoothing
142
+ smooth_negative = smoothing / total_classes
143
+ probs = tl.where(col_offsets == label_idx, probs - smooth_positive, probs) - smooth_negative
144
+ else:
145
+ probs = tl.where(col_offsets == label_idx, probs - 1.0, probs)
146
+ tl.store(dlogits_ptr + col_offsets, (dloss * logit_scale) * probs, mask=col_offsets < n_cols)
147
+
148
+
149
+ class CrossEntropyLoss(torch.autograd.Function):
150
+
151
+ @staticmethod
152
+ def forward(
153
+ ctx,
154
+ logits,
155
+ labels,
156
+ precomputed_lse=None,
157
+ smoothing=0.0,
158
+ logit_scale=1.0,
159
+ lse_square_scale=0.0,
160
+ ignore_index=-100,
161
+ inplace_backward=False,
162
+ process_group=None,
163
+ ):
164
+ # For some reason Triton generates wrong code when labels has dtype long and its address
165
+ # is not aligned to 16 bytes. The ld.global.b64 seems to load the wrong label index.
166
+ if labels.dtype == torch.long and labels.data_ptr() % 16 != 0:
167
+ labels = F.pad(labels, (0, 1))[..., :-1]
168
+ assert labels.data_ptr() % 16 == 0
169
+ assert logit_scale > 0.0
170
+ n_rows, n_cols = logits.shape
171
+ assert labels.shape == (n_rows,)
172
+ world_size = 1 if process_group is None else torch.distributed.get_world_size(process_group)
173
+ total_classes = world_size * n_cols
174
+ rank = 0 if process_group is None else torch.distributed.get_rank(process_group)
175
+ class_start_idx = rank * n_cols
176
+ use_precomputed_lse = precomputed_lse is not None and logit_scale == 1.0 and smoothing == 0.0
177
+
178
+ if logits.stride(-1) != 1:
179
+ logits = logits.contiguous()
180
+ MAX_BLOCK_SIZE = 16 * 1024
181
+ BLOCK_SIZE = min(triton.next_power_of_2(n_cols), MAX_BLOCK_SIZE)
182
+ num_warps = (
183
+ 4
184
+ if BLOCK_SIZE < 2048
185
+ else (8 if BLOCK_SIZE < 8192 else (16 if BLOCK_SIZE < 128 * 1024 else 32))
186
+ )
187
+ losses = torch.empty(n_rows, dtype=torch.float, device=logits.device)
188
+ if use_precomputed_lse:
189
+ assert precomputed_lse.shape == (n_rows,)
190
+ lse = precomputed_lse.contiguous()
191
+ else:
192
+ lse = torch.empty(n_rows, dtype=torch.float, device=logits.device)
193
+ z_losses = torch.empty(n_rows, dtype=torch.float, device=logits.device)
194
+ # Need this, otherwise Triton tries to launch from cuda:0 and we get
195
+ # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?)
196
+ with torch.cuda.device(logits.device.index):
197
+ cross_entropy_fwd_kernel[(n_rows,)](
198
+ losses, # data ptrs
199
+ lse,
200
+ z_losses,
201
+ logits,
202
+ labels,
203
+ smoothing,
204
+ logit_scale,
205
+ lse_square_scale,
206
+ ignore_index,
207
+ total_classes,
208
+ class_start_idx,
209
+ n_cols, # shapes
210
+ logits.stride(0), # strides
211
+ BLOCK_SIZE=BLOCK_SIZE, # constants
212
+ SPLIT=world_size > 1,
213
+ PRECOMPUTED_LSE=use_precomputed_lse,
214
+ num_warps=num_warps,
215
+ )
216
+
217
+ if world_size > 1:
218
+ # If there's no smoothing, if labels are in the vocab of this partition, losses contains
219
+ # - predicted logit, and 0 otherwise.
220
+ # If there's smoothing=0.1, for labels in the vocab of this partition, losses contains
221
+ # -0.9 * predicted logit - 0.1 * sum logit / total_classes.
222
+ # For labels not in the vocab of this partition, losses contains
223
+ # -0.1 * sum logit / total_classes.
224
+ if world_size > 1:
225
+ lse_allgather = torch.empty(world_size, n_rows, dtype=lse.dtype, device=lse.device)
226
+ torch.distributed.all_gather_into_tensor(lse_allgather, lse, group=process_group)
227
+ handle_losses = torch.distributed.all_reduce(
228
+ losses, op=torch.distributed.ReduceOp.SUM, group=process_group, async_op=True
229
+ )
230
+ lse = torch.logsumexp(lse_allgather, dim=0)
231
+ handle_losses.wait()
232
+ # After the allreduce, if there's no smoothing, the total losses are - predicted_logit,
233
+ # we just have to add the (global) lse.
234
+ # If there's smoothing=0.1, the total losses are
235
+ # -0.9 * predicted_logit - 0.1 * sum logit / total_classes.
236
+ # Again, we just have to add the (global) lse.
237
+ losses += lse
238
+ if lse_square_scale != 0.0:
239
+ z_losses = lse_square_scale * lse.square()
240
+ z_losses.masked_fill_(labels == ignore_index, 0.0)
241
+ losses += z_losses
242
+ else:
243
+ z_losses = torch.zeros_like(losses)
244
+ losses.masked_fill_(labels == ignore_index, 0.0)
245
+
246
+ ctx.save_for_backward(logits, lse, labels)
247
+ ctx.mark_non_differentiable(z_losses)
248
+ ctx.smoothing = smoothing
249
+ ctx.logit_scale = logit_scale
250
+ ctx.lse_square_scale = lse_square_scale
251
+ ctx.ignore_index = ignore_index
252
+ ctx.total_classes = total_classes
253
+ ctx.class_start_idx = class_start_idx
254
+ ctx.inplace_backward = inplace_backward
255
+ return losses, z_losses
256
+
257
+ @staticmethod
258
+ def backward(ctx, grad_losses, grad_z_losses):
259
+ del grad_z_losses # z_losses are only for logging.
260
+
261
+ logits, lse, labels = ctx.saved_tensors
262
+ dlogits = logits if ctx.inplace_backward else torch.empty_like(logits)
263
+ n_rows, n_cols = logits.shape
264
+ BLOCK_SIZE = min(triton.next_power_of_2(n_cols), 4 * 1024)
265
+ num_warps = 4 if BLOCK_SIZE < 2048 else (8 if BLOCK_SIZE < 8192 else 16)
266
+ grid = lambda META: (n_rows, triton.cdiv(n_cols, META["BLOCK_SIZE"])) # noqa
267
+ # Need this, otherwise Triton tries to launch from cuda:0 and we get
268
+ # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?)
269
+ with torch.cuda.device(logits.device.index):
270
+ cross_entropy_bwd_kernel[grid](
271
+ dlogits, # data ptrs
272
+ grad_losses,
273
+ logits,
274
+ lse,
275
+ labels,
276
+ ctx.smoothing,
277
+ ctx.logit_scale,
278
+ ctx.lse_square_scale,
279
+ ctx.ignore_index,
280
+ ctx.total_classes,
281
+ ctx.class_start_idx,
282
+ n_cols, # shapes
283
+ logits.stride(0), # strides
284
+ dlogits.stride(0),
285
+ grad_losses.stride(0),
286
+ BLOCK_SIZE=BLOCK_SIZE, # constants
287
+ num_warps=num_warps,
288
+ )
289
+ return dlogits, None, None, None, None, None, None, None, None, None
290
+
291
+
292
+ def cross_entropy_loss(
293
+ logits: torch.Tensor,
294
+ labels: torch.Tensor,
295
+ precomputed_lse: Optional[torch.Tensor] = None,
296
+ label_smoothing: float = 0.0,
297
+ logit_scale: float = 1.0,
298
+ lse_square_scale: float = 0.0,
299
+ ignore_index=-100,
300
+ inplace_backward: bool = False,
301
+ process_group=None,
302
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
303
+ """
304
+ Arguments:
305
+ logits: (batch, vocab_size)
306
+ labels: (batch,)
307
+ label_smoothing: float
308
+ logit_scale: float. Multiply logits by this scale before calculating the loss.
309
+ lse_square_scale: float. If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss.
310
+ This is also referred to as "z-loss".
311
+ ignore_index: int. If labels == ignore_index, the loss is set to 0.0.
312
+ inplace_backward: bool. If True, we do the backward pass in-place by modifying the logits.
313
+ This saves memory.
314
+ process_group: if not None, we're doing Tensor Parallel: each process is responsible for
315
+ one part of the vocab. The loss will be aggregated across processes.
316
+ Returns:
317
+ losses: (batch,), float
318
+ z_losses: (batch,), float
319
+ """
320
+ return CrossEntropyLoss.apply(
321
+ logits,
322
+ labels,
323
+ precomputed_lse,
324
+ label_smoothing,
325
+ logit_scale,
326
+ lse_square_scale,
327
+ ignore_index,
328
+ inplace_backward,
329
+ process_group,
330
+ )
build/torch211-cxx11-cu128-aarch64-linux/ops/triton/k_activations.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/facebookresearch/xformers/blob/main/xformers/triton/k_activations.py
2
+ # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ from enum import Enum
9
+ from typing import Optional
10
+
11
+ import triton
12
+ import triton.language as tl
13
+
14
+ _sqrt2pi = math.sqrt(2.0 / math.pi)
15
+ _sqrt1_2 = math.sqrt(1.0 / 2)
16
+ _gaussian_pdf_normalization = 1.0 / math.sqrt(2 * math.pi)
17
+
18
+
19
+ class Activation(str, Enum):
20
+ SquaredReLU = "squared_relu"
21
+ GeLU = "gelu"
22
+ GeLUApprox = "gelu_approx"
23
+ LeakyReLU = "leaky_relu"
24
+ ReLU = "relu"
25
+
26
+
27
+ def get_triton_activation_kernel(activation: Optional[Activation]):
28
+ return (
29
+ {
30
+ Activation.ReLU: relu,
31
+ Activation.LeakyReLU: leaky_relu,
32
+ Activation.GeLU: gelu,
33
+ Activation.GeLUApprox: gelu_approx,
34
+ Activation.SquaredReLU: squared_relu,
35
+ }[activation]
36
+ if activation
37
+ else None
38
+ )
39
+
40
+
41
+ def get_triton_activation_bwd_kernel(activation: Optional[Activation]):
42
+ return (
43
+ {
44
+ Activation.ReLU: relu_grad,
45
+ Activation.LeakyReLU: leaky_relu_grad,
46
+ Activation.GeLU: gelu_grad,
47
+ Activation.GeLUApprox: gelu_approx_grad,
48
+ Activation.SquaredReLU: squared_relu_grad,
49
+ }[activation]
50
+ if activation
51
+ else None
52
+ )
53
+
54
+
55
+ @triton.jit
56
+ def tanh(x):
57
+ # Tanh is just a scaled sigmoid
58
+ return 2 * tl.sigmoid(2 * x) - 1
59
+
60
+
61
+ @triton.jit
62
+ def cosh(x):
63
+ exp_x = tl.exp(x)
64
+ return (exp_x + 1.0 / exp_x) * 0.5
65
+
66
+
67
+ # a Triton implementation of the most used activations
68
+ # See for instance http://arxiv.org/abs/1606.08415 for an overview
69
+
70
+ # ReLU
71
+ @triton.jit
72
+ def relu(x):
73
+ """
74
+ ReLU_ activation function
75
+
76
+ .. _ReLU: https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html
77
+ """
78
+ zero = 0.0
79
+ return tl.where(x >= 0, x, zero.to(x.dtype))
80
+
81
+
82
+ @triton.jit
83
+ def relu_grad(x):
84
+ # ReLU is different from other activations
85
+ # in that it does not require the input to retrospectively compute its gradient
86
+ # here the input is the downstream gradient, and we return the upstream gradient directly
87
+ zero = 0.0
88
+ one = 1.0
89
+ return tl.where(x >= 0, one.to(x.dtype), zero.to(x.dtype))
90
+
91
+
92
+ @triton.jit
93
+ def squared_relu(x):
94
+ """
95
+ Squared ReLU activation, as proposed in the Primer_ paper.
96
+
97
+ .. _Primer: https://arxiv.org/abs/2109.08668
98
+ """
99
+ x_ = relu(x)
100
+ return (x_ * x_).to(x.dtype)
101
+
102
+
103
+ @triton.jit
104
+ def squared_relu_grad(x):
105
+ return tl.where(x >= 0, 2.0 * x, 0.0)
106
+
107
+
108
+ # Leaky ReLU
109
+ @triton.jit
110
+ def leaky_relu(x):
111
+ """
112
+ LeakyReLU_ activation
113
+
114
+ .. _LeakyReLU: https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html
115
+ """
116
+ scale = 0.01 + 0.0
117
+ scale = scale.to(x.dtype)
118
+ return tl.where(x >= 0, x, scale * x)
119
+
120
+
121
+ @triton.jit
122
+ def leaky_relu_grad(x):
123
+ min_grad = 0.01
124
+ max_grad = 1
125
+
126
+ min_grad = min_grad.to(x.dtype)
127
+ max_grad = max_grad.to(x.dtype)
128
+
129
+ return tl.where(x >= 0, max_grad, min_grad)
130
+
131
+
132
+ @triton.jit
133
+ def gelu(x):
134
+ """Gaussian Error Linear Unit (GELU)"""
135
+ return x * 0.5 * (1.0 + tl.libdevice.erf(x * _sqrt1_2))
136
+
137
+
138
+ @triton.jit
139
+ def gelu_grad(x):
140
+ cdf = 0.5 * (1.0 + tl.libdevice.erf(x * _sqrt1_2))
141
+ pdf = tl.exp(-0.5 * x * x) * _gaussian_pdf_normalization
142
+ return cdf + x * pdf
143
+
144
+
145
+ @triton.jit
146
+ def gelu_approx(x):
147
+ """
148
+ GeLU_ activation - Gaussian error linear unit, with tanh approximation
149
+
150
+ .. _GeLU: https://arxiv.org/pdf/1606.08415.pdf
151
+ """
152
+ return 0.5 * x * (1.0 + tanh(_sqrt2pi * x * (1.0 + 0.044715 * x * x)))
153
+
154
+
155
+ @triton.jit
156
+ def gelu_approx_grad(x):
157
+ # CREDITS: Fast implementation proposed in
158
+ # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/fused_bias_gelu.py#L30
159
+ tanh_out = tanh(0.79788456 * x * (1 + 0.044715 * x * x))
160
+ return 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (
161
+ 1 + tanh_out
162
+ )
build/torch211-cxx11-cu128-aarch64-linux/ops/triton/layer_norm.py ADDED
@@ -0,0 +1,1254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, Tri Dao.
2
+ # Implement dropout + residual + layer_norm / rms_norm.
3
+
4
+ # Based on the Triton LayerNorm tutorial: https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
5
+ # For the backward pass, we keep weight_grad and bias_grad in registers and accumulate.
6
+ # This is faster for dimensions up to 8k, but after that it's much slower due to register spilling.
7
+ # The models we train have hidden dim up to 8k anyway (e.g. Llama 70B), so this is fine.
8
+
9
+ import math
10
+ from typing import Optional, List
11
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from torch import Tensor
15
+
16
+ import triton
17
+ import triton.language as tl
18
+
19
+ from flash_attn.utils.torch import custom_fwd, custom_bwd
20
+ from flash_attn.utils.library import triton_op
21
+
22
+ from ..._ops import add_op_namespace_prefix
23
+
24
+
25
+ def maybe_contiguous_lastdim(x):
26
+ return x.contiguous() if x is not None and x.stride(-1) != 1 else x
27
+
28
+
29
+ def maybe_contiguous(x):
30
+ return x.contiguous() if x is not None else None
31
+
32
+
33
+ def triton_autotune_configs():
34
+ # Return configs with a valid warp count for the current device
35
+ configs = []
36
+ # Maximum threads per block is architecture-dependent in theory, but in reality all are 1024
37
+ max_threads_per_block = 1024
38
+ # Default to warp size 32 if not defined by device
39
+ warp_size = getattr(torch.cuda.get_device_properties(torch.cuda.current_device()), "warp_size", 32)
40
+ # Autotune for warp counts which are powers of 2 and do not exceed thread per block limit
41
+ return [triton.Config({}, num_warps=warp_count) for warp_count in [1, 2, 4, 8, 16, 32]
42
+ if warp_count * warp_size <= max_threads_per_block]
43
+ # return [triton.Config({}, num_warps=8)]
44
+
45
+
46
+ def layer_norm_ref(
47
+ x,
48
+ weight,
49
+ bias,
50
+ residual=None,
51
+ x1=None,
52
+ weight1=None,
53
+ bias1=None,
54
+ eps=1e-6,
55
+ dropout_p=0.0,
56
+ rowscale=None,
57
+ prenorm=False,
58
+ zero_centered_weight=False,
59
+ dropout_mask=None,
60
+ dropout_mask1=None,
61
+ upcast=False,
62
+ ):
63
+ dtype = x.dtype
64
+ if upcast:
65
+ x = x.float()
66
+ weight = weight.float()
67
+ bias = bias.float() if bias is not None else None
68
+ residual = residual.float() if residual is not None else residual
69
+ x1 = x1.float() if x1 is not None else None
70
+ weight1 = weight1.float() if weight1 is not None else None
71
+ bias1 = bias1.float() if bias1 is not None else None
72
+ if zero_centered_weight:
73
+ weight = weight + 1.0
74
+ if weight1 is not None:
75
+ weight1 = weight1 + 1.0
76
+ if x1 is not None:
77
+ assert rowscale is None, "rowscale is not supported with parallel LayerNorm"
78
+ if rowscale is not None:
79
+ x = x * rowscale[..., None]
80
+ if dropout_p > 0.0:
81
+ if dropout_mask is not None:
82
+ x = x.masked_fill(~dropout_mask, 0.0) / (1.0 - dropout_p)
83
+ else:
84
+ x = F.dropout(x, p=dropout_p)
85
+ if x1 is not None:
86
+ if dropout_mask1 is not None:
87
+ x1 = x1.masked_fill(~dropout_mask1, 0.0) / (1.0 - dropout_p)
88
+ else:
89
+ x1 = F.dropout(x1, p=dropout_p)
90
+ if x1 is not None:
91
+ x = x + x1
92
+ if residual is not None:
93
+ x = (x + residual).to(x.dtype)
94
+ out = F.layer_norm(x.to(weight.dtype), x.shape[-1:], weight=weight, bias=bias, eps=eps).to(
95
+ dtype
96
+ )
97
+ if weight1 is None:
98
+ return out if not prenorm else (out, x)
99
+ else:
100
+ out1 = F.layer_norm(
101
+ x.to(weight1.dtype), x.shape[-1:], weight=weight1, bias=bias1, eps=eps
102
+ ).to(dtype)
103
+ return (out, out1) if not prenorm else (out, out1, x)
104
+
105
+
106
+ def rms_norm_ref(
107
+ x,
108
+ weight,
109
+ bias,
110
+ residual=None,
111
+ x1=None,
112
+ weight1=None,
113
+ bias1=None,
114
+ eps=1e-6,
115
+ dropout_p=0.0,
116
+ rowscale=None,
117
+ prenorm=False,
118
+ zero_centered_weight=False,
119
+ dropout_mask=None,
120
+ dropout_mask1=None,
121
+ upcast=False,
122
+ ):
123
+ dtype = x.dtype
124
+ if upcast:
125
+ x = x.float()
126
+ weight = weight.float()
127
+ bias = bias.float() if bias is not None else None
128
+ residual = residual.float() if residual is not None else residual
129
+ x1 = x1.float() if x1 is not None else None
130
+ weight1 = weight1.float() if weight1 is not None else None
131
+ bias1 = bias1.float() if bias1 is not None else None
132
+ if zero_centered_weight:
133
+ weight = weight + 1.0
134
+ if weight1 is not None:
135
+ weight1 = weight1 + 1.0
136
+ if x1 is not None:
137
+ assert rowscale is None, "rowscale is not supported with parallel LayerNorm"
138
+ if rowscale is not None:
139
+ x = x * rowscale[..., None]
140
+ if dropout_p > 0.0:
141
+ if dropout_mask is not None:
142
+ x = x.masked_fill(~dropout_mask, 0.0) / (1.0 - dropout_p)
143
+ else:
144
+ x = F.dropout(x, p=dropout_p)
145
+ if x1 is not None:
146
+ if dropout_mask1 is not None:
147
+ x1 = x1.masked_fill(~dropout_mask1, 0.0) / (1.0 - dropout_p)
148
+ else:
149
+ x1 = F.dropout(x1, p=dropout_p)
150
+ if x1 is not None:
151
+ x = x + x1
152
+ if residual is not None:
153
+ x = (x + residual).to(x.dtype)
154
+ rstd = 1 / torch.sqrt((x.square()).mean(dim=-1, keepdim=True) + eps)
155
+ out = ((x * rstd * weight) + bias if bias is not None else (x * rstd * weight)).to(dtype)
156
+ if weight1 is None:
157
+ return out if not prenorm else (out, x)
158
+ else:
159
+ out1 = ((x * rstd * weight1) + bias1 if bias1 is not None else (x * rstd * weight1)).to(
160
+ dtype
161
+ )
162
+ return (out, out1) if not prenorm else (out, out1, x)
163
+
164
+
165
+ @triton.autotune(
166
+ configs=triton_autotune_configs(),
167
+ key=["N", "HAS_RESIDUAL", "STORE_RESIDUAL_OUT", "IS_RMS_NORM", "HAS_BIAS", "HAS_X1", "HAS_W1", "HAS_B1"],
168
+ )
169
+ # torch compile doesn't like triton.heuristics, so we set these manually when calling the kernel
170
+ # @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None})
171
+ # @triton.heuristics({"HAS_RESIDUAL": lambda args: args["RESIDUAL"] is not None})
172
+ # @triton.heuristics({"HAS_X1": lambda args: args["X1"] is not None})
173
+ # @triton.heuristics({"HAS_W1": lambda args: args["W1"] is not None})
174
+ # @triton.heuristics({"HAS_B1": lambda args: args["B1"] is not None})
175
+ @triton.jit
176
+ def _layer_norm_fwd_1pass_kernel(
177
+ X, # pointer to the input
178
+ Y, # pointer to the output
179
+ W, # pointer to the weights
180
+ B, # pointer to the biases
181
+ RESIDUAL, # pointer to the residual
182
+ X1,
183
+ W1,
184
+ B1,
185
+ Y1,
186
+ RESIDUAL_OUT, # pointer to the residual
187
+ ROWSCALE,
188
+ SEEDS, # Dropout seeds for each row
189
+ DROPOUT_MASK,
190
+ DROPOUT_MASK1,
191
+ Mean, # pointer to the mean
192
+ Rstd, # pointer to the 1/std
193
+ stride_x_row, # how much to increase the pointer when moving by 1 row
194
+ stride_y_row,
195
+ stride_res_row,
196
+ stride_res_out_row,
197
+ stride_x1_row,
198
+ stride_y1_row,
199
+ M, # number of rows in X
200
+ N, # number of columns in X
201
+ eps, # epsilon to avoid division by zero
202
+ dropout_p, # Dropout probability
203
+ zero_centered_weight, # If true, add 1.0 to the weight
204
+ IS_RMS_NORM: tl.constexpr,
205
+ BLOCK_N: tl.constexpr,
206
+ HAS_RESIDUAL: tl.constexpr,
207
+ STORE_RESIDUAL_OUT: tl.constexpr,
208
+ HAS_BIAS: tl.constexpr,
209
+ HAS_DROPOUT: tl.constexpr,
210
+ STORE_DROPOUT_MASK: tl.constexpr,
211
+ HAS_ROWSCALE: tl.constexpr,
212
+ HAS_X1: tl.constexpr,
213
+ HAS_W1: tl.constexpr,
214
+ HAS_B1: tl.constexpr,
215
+ ):
216
+ # Map the program id to the row of X and Y it should compute.
217
+ row = tl.program_id(0)
218
+ X += row * stride_x_row
219
+ Y += row * stride_y_row
220
+ if HAS_RESIDUAL:
221
+ RESIDUAL += row * stride_res_row
222
+ if STORE_RESIDUAL_OUT:
223
+ RESIDUAL_OUT += row * stride_res_out_row
224
+ if HAS_X1:
225
+ X1 += row * stride_x1_row
226
+ if HAS_W1:
227
+ Y1 += row * stride_y1_row
228
+ # Compute mean and variance
229
+ cols = tl.arange(0, BLOCK_N)
230
+ x = tl.load(X + cols, mask=cols < N, other=0.0).to(tl.float32)
231
+ if HAS_ROWSCALE:
232
+ rowscale = tl.load(ROWSCALE + row).to(tl.float32)
233
+ x *= rowscale
234
+ if HAS_DROPOUT:
235
+ # Compute dropout mask
236
+ # 7 rounds is good enough, and reduces register pressure
237
+ keep_mask = tl.rand(tl.load(SEEDS + row).to(tl.uint32), cols, n_rounds=7) > dropout_p
238
+ x = tl.where(keep_mask, x / (1.0 - dropout_p), 0.0)
239
+ if STORE_DROPOUT_MASK:
240
+ tl.store(DROPOUT_MASK + row * N + cols, keep_mask, mask=cols < N)
241
+ if HAS_X1:
242
+ x1 = tl.load(X1 + cols, mask=cols < N, other=0.0).to(tl.float32)
243
+ if HAS_ROWSCALE:
244
+ rowscale = tl.load(ROWSCALE + M + row).to(tl.float32)
245
+ x1 *= rowscale
246
+ if HAS_DROPOUT:
247
+ # Compute dropout mask
248
+ # 7 rounds is good enough, and reduces register pressure
249
+ keep_mask = (
250
+ tl.rand(tl.load(SEEDS + M + row).to(tl.uint32), cols, n_rounds=7) > dropout_p
251
+ )
252
+ x1 = tl.where(keep_mask, x1 / (1.0 - dropout_p), 0.0)
253
+ if STORE_DROPOUT_MASK:
254
+ tl.store(DROPOUT_MASK1 + row * N + cols, keep_mask, mask=cols < N)
255
+ x += x1
256
+ if HAS_RESIDUAL:
257
+ residual = tl.load(RESIDUAL + cols, mask=cols < N, other=0.0).to(tl.float32)
258
+ x += residual
259
+ if STORE_RESIDUAL_OUT:
260
+ tl.store(RESIDUAL_OUT + cols, x, mask=cols < N)
261
+ if not IS_RMS_NORM:
262
+ mean = tl.sum(x, axis=0) / N
263
+ tl.store(Mean + row, mean)
264
+ xbar = tl.where(cols < N, x - mean, 0.0)
265
+ var = tl.sum(xbar * xbar, axis=0) / N
266
+ else:
267
+ xbar = tl.where(cols < N, x, 0.0)
268
+ var = tl.sum(xbar * xbar, axis=0) / N
269
+ rstd = 1 / tl.sqrt(var + eps)
270
+ tl.store(Rstd + row, rstd)
271
+ # Normalize and apply linear transformation
272
+ mask = cols < N
273
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
274
+ if zero_centered_weight:
275
+ w += 1.0
276
+ if HAS_BIAS:
277
+ b = tl.load(B + cols, mask=mask).to(tl.float32)
278
+ x_hat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
279
+ y = x_hat * w + b if HAS_BIAS else x_hat * w
280
+ # Write output
281
+ tl.store(Y + cols, y, mask=mask)
282
+ if HAS_W1:
283
+ w1 = tl.load(W1 + cols, mask=mask).to(tl.float32)
284
+ if zero_centered_weight:
285
+ w1 += 1.0
286
+ if HAS_B1:
287
+ b1 = tl.load(B1 + cols, mask=mask).to(tl.float32)
288
+ y1 = x_hat * w1 + b1 if HAS_B1 else x_hat * w1
289
+ tl.store(Y1 + cols, y1, mask=mask)
290
+
291
+
292
+ def _layer_norm_fwd(
293
+ x: Tensor,
294
+ weight: Tensor,
295
+ bias: Tensor,
296
+ eps: float,
297
+ residual: Optional[Tensor] = None,
298
+ x1: Optional[Tensor] = None,
299
+ weight1: Optional[Tensor] = None,
300
+ bias1: Optional[Tensor] = None,
301
+ dropout_p: float = 0.0,
302
+ rowscale: Optional[Tensor] = None,
303
+ out_dtype: Optional[torch.dtype] = None,
304
+ residual_dtype: Optional[torch.dtype] = None,
305
+ zero_centered_weight: bool = False,
306
+ is_rms_norm: bool = False,
307
+ return_dropout_mask: bool = False,
308
+ out: Optional[Tensor] = None,
309
+ residual_out: Optional[Tensor] = None
310
+ ) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor):
311
+ # Need to wrap to handle the case where residual_out is a alias of x, which makes torch.library
312
+ # and torch.compile unhappy. Also allocate memory for out and residual_out if they are None
313
+ # so that _layer_norm_fwd_impl doesn't have to return them.
314
+ if out is None:
315
+ out = torch.empty_like(x, dtype=x.dtype if out_dtype is None else out_dtype)
316
+ if residual is not None:
317
+ residual_dtype = residual.dtype
318
+ if residual_out is None and (
319
+ residual is not None
320
+ or (residual_dtype is not None and residual_dtype != x.dtype)
321
+ or dropout_p > 0.0
322
+ or rowscale is not None
323
+ or x1 is not None
324
+ ):
325
+ residual_out = torch.empty_like(
326
+ x, dtype=residual_dtype if residual_dtype is not None else x.dtype
327
+ )
328
+ else:
329
+ residual_out = None
330
+ y1, mean, rstd, seeds, dropout_mask, dropout_mask1 = _layer_norm_fwd_impl(
331
+ x,
332
+ weight,
333
+ bias,
334
+ eps,
335
+ out,
336
+ residual=residual,
337
+ x1=x1,
338
+ weight1=weight1,
339
+ bias1=bias1,
340
+ dropout_p=dropout_p,
341
+ rowscale=rowscale,
342
+ zero_centered_weight=zero_centered_weight,
343
+ is_rms_norm=is_rms_norm,
344
+ return_dropout_mask=return_dropout_mask,
345
+ residual_out=residual_out,
346
+ )
347
+ # residual_out is None if residual is None and residual_dtype == input_dtype and dropout_p == 0.0
348
+ if residual_out is None:
349
+ residual_out = x
350
+ return out, y1, mean, rstd, residual_out, seeds, dropout_mask, dropout_mask1
351
+
352
+
353
+ # [2025-04-28] torch.library.triton_op ignores the schema argument, but here we need the schema
354
+ # since we're returning a tuple of tensors
355
+ @triton_op(add_op_namespace_prefix("layer_norm_fwd_impl"), mutates_args={"out", "residual_out"},
356
+ schema="(Tensor x, Tensor weight, Tensor bias, float eps, Tensor(a!) out, Tensor? residual, Tensor? x1, Tensor? weight1, Tensor? bias1, float dropout_p, Tensor? rowscale, bool zero_centered_weight, bool is_rms_norm, bool return_dropout_mask, Tensor(a!)? residual_out) -> (Tensor y1, Tensor mean, Tensor rstd, Tensor seeds, Tensor dropout_mask, Tensor dropout_mask1)")
357
+ def _layer_norm_fwd_impl(
358
+ x: Tensor,
359
+ weight: Tensor,
360
+ bias: Tensor,
361
+ eps: float,
362
+ out: Tensor,
363
+ residual: Optional[Tensor] = None,
364
+ x1: Optional[Tensor] = None,
365
+ weight1: Optional[Tensor] = None,
366
+ bias1: Optional[Tensor] = None,
367
+ dropout_p: float = 0.0,
368
+ rowscale: Optional[Tensor] = None,
369
+ zero_centered_weight: bool = False,
370
+ is_rms_norm: bool = False,
371
+ return_dropout_mask: bool = False,
372
+ residual_out: Optional[Tensor] = None
373
+ ) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor):
374
+ M, N = x.shape
375
+ assert x.stride(-1) == 1
376
+ if residual is not None:
377
+ assert residual.stride(-1) == 1
378
+ assert residual.shape == (M, N)
379
+ assert weight.shape == (N,)
380
+ assert weight.stride(-1) == 1
381
+ if bias is not None:
382
+ assert bias.stride(-1) == 1
383
+ assert bias.shape == (N,)
384
+ if x1 is not None:
385
+ assert x1.shape == x.shape
386
+ assert rowscale is None
387
+ assert x1.stride(-1) == 1
388
+ if weight1 is not None:
389
+ assert weight1.shape == (N,)
390
+ assert weight1.stride(-1) == 1
391
+ if bias1 is not None:
392
+ assert bias1.shape == (N,)
393
+ assert bias1.stride(-1) == 1
394
+ if rowscale is not None:
395
+ assert rowscale.is_contiguous()
396
+ assert rowscale.shape == (M,)
397
+ assert out.shape == x.shape
398
+ assert out.stride(-1) == 1
399
+ if residual_out is not None:
400
+ assert residual_out.shape == x.shape
401
+ assert residual_out.stride(-1) == 1
402
+ if weight1 is not None:
403
+ y1 = torch.empty_like(out)
404
+ assert y1.stride(-1) == 1
405
+ else:
406
+ y1 = None
407
+ mean = torch.empty((M,), dtype=torch.float32, device=x.device) if not is_rms_norm else None
408
+ rstd = torch.empty((M,), dtype=torch.float32, device=x.device)
409
+ if dropout_p > 0.0:
410
+ seeds = torch.randint(
411
+ 2**32, (M if x1 is None else 2 * M,), device=x.device, dtype=torch.int64
412
+ )
413
+ else:
414
+ seeds = None
415
+ if return_dropout_mask and dropout_p > 0.0:
416
+ dropout_mask = torch.empty(M, N, device=x.device, dtype=torch.bool)
417
+ if x1 is not None:
418
+ dropout_mask1 = torch.empty(M, N, device=x.device, dtype=torch.bool)
419
+ else:
420
+ dropout_mask1 = None
421
+ else:
422
+ dropout_mask, dropout_mask1 = None, None
423
+ # Less than 64KB per feature: enqueue fused kernel
424
+ MAX_FUSED_SIZE = 65536 // x.element_size()
425
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
426
+ if N > BLOCK_N:
427
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
428
+ with torch.cuda.device(x.device.index):
429
+ torch.library.wrap_triton(_layer_norm_fwd_1pass_kernel)[(M,)](
430
+ x,
431
+ out,
432
+ weight,
433
+ bias,
434
+ residual,
435
+ x1,
436
+ weight1,
437
+ bias1,
438
+ y1,
439
+ residual_out,
440
+ rowscale,
441
+ seeds,
442
+ dropout_mask,
443
+ dropout_mask1,
444
+ mean,
445
+ rstd,
446
+ x.stride(0),
447
+ out.stride(0),
448
+ residual.stride(0) if residual is not None else 0,
449
+ residual_out.stride(0) if residual_out is not None else 0,
450
+ x1.stride(0) if x1 is not None else 0,
451
+ y1.stride(0) if y1 is not None else 0,
452
+ M,
453
+ N,
454
+ eps,
455
+ dropout_p,
456
+ # Passing bool make torch inductor very unhappy since it then tries to compare to int_max
457
+ int(zero_centered_weight),
458
+ is_rms_norm,
459
+ BLOCK_N,
460
+ residual is not None,
461
+ residual_out is not None,
462
+ bias is not None,
463
+ dropout_p > 0.0,
464
+ dropout_mask is not None,
465
+ rowscale is not None,
466
+ HAS_X1=x1 is not None,
467
+ HAS_W1=weight1 is not None,
468
+ HAS_B1=bias1 is not None,
469
+ )
470
+ return y1, mean, rstd, seeds, dropout_mask, dropout_mask1
471
+
472
+
473
+ @triton.autotune(
474
+ configs=triton_autotune_configs(),
475
+ key=["N", "HAS_DRESIDUAL", "STORE_DRESIDUAL", "IS_RMS_NORM", "HAS_BIAS", "HAS_DROPOUT"],
476
+ )
477
+ # torch compile doesn't like triton.heuristics, so we set these manually when calling the kernel
478
+ # @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None})
479
+ # @triton.heuristics({"HAS_DRESIDUAL": lambda args: args["DRESIDUAL"] is not None})
480
+ # @triton.heuristics({"STORE_DRESIDUAL": lambda args: args["DRESIDUAL_IN"] is not None})
481
+ # @triton.heuristics({"HAS_ROWSCALE": lambda args: args["ROWSCALE"] is not None})
482
+ # @triton.heuristics({"HAS_DY1": lambda args: args["DY1"] is not None})
483
+ # @triton.heuristics({"HAS_DX1": lambda args: args["DX1"] is not None})
484
+ # @triton.heuristics({"HAS_B1": lambda args: args["DB1"] is not None})
485
+ # @triton.heuristics({"RECOMPUTE_OUTPUT": lambda args: args["Y"] is not None})
486
+ @triton.jit
487
+ def _layer_norm_bwd_kernel(
488
+ X, # pointer to the input
489
+ W, # pointer to the weights
490
+ B, # pointer to the biases
491
+ Y, # pointer to the output to be recomputed
492
+ DY, # pointer to the output gradient
493
+ DX, # pointer to the input gradient
494
+ DW, # pointer to the partial sum of weights gradient
495
+ DB, # pointer to the partial sum of biases gradient
496
+ DRESIDUAL,
497
+ W1,
498
+ DY1,
499
+ DX1,
500
+ DW1,
501
+ DB1,
502
+ DRESIDUAL_IN,
503
+ ROWSCALE,
504
+ SEEDS,
505
+ Mean, # pointer to the mean
506
+ Rstd, # pointer to the 1/std
507
+ stride_x_row, # how much to increase the pointer when moving by 1 row
508
+ stride_y_row,
509
+ stride_dy_row,
510
+ stride_dx_row,
511
+ stride_dres_row,
512
+ stride_dy1_row,
513
+ stride_dx1_row,
514
+ stride_dres_in_row,
515
+ M, # number of rows in X
516
+ N, # number of columns in X
517
+ eps, # epsilon to avoid division by zero
518
+ dropout_p,
519
+ zero_centered_weight,
520
+ rows_per_program,
521
+ IS_RMS_NORM: tl.constexpr,
522
+ BLOCK_N: tl.constexpr,
523
+ HAS_DRESIDUAL: tl.constexpr,
524
+ STORE_DRESIDUAL: tl.constexpr,
525
+ HAS_BIAS: tl.constexpr,
526
+ HAS_DROPOUT: tl.constexpr,
527
+ HAS_ROWSCALE: tl.constexpr,
528
+ HAS_DY1: tl.constexpr,
529
+ HAS_DX1: tl.constexpr,
530
+ HAS_B1: tl.constexpr,
531
+ RECOMPUTE_OUTPUT: tl.constexpr,
532
+ ):
533
+ # Map the program id to the elements of X, DX, and DY it should compute.
534
+ row_block_id = tl.program_id(0)
535
+ row_start = row_block_id * rows_per_program
536
+ # Do not early exit if row_start >= M, because we need to write DW and DB
537
+ cols = tl.arange(0, BLOCK_N)
538
+ mask = cols < N
539
+ X += row_start * stride_x_row
540
+ if HAS_DRESIDUAL:
541
+ DRESIDUAL += row_start * stride_dres_row
542
+ if STORE_DRESIDUAL:
543
+ DRESIDUAL_IN += row_start * stride_dres_in_row
544
+ DY += row_start * stride_dy_row
545
+ DX += row_start * stride_dx_row
546
+ if HAS_DY1:
547
+ DY1 += row_start * stride_dy1_row
548
+ if HAS_DX1:
549
+ DX1 += row_start * stride_dx1_row
550
+ if RECOMPUTE_OUTPUT:
551
+ Y += row_start * stride_y_row
552
+ w = tl.load(W + cols, mask=mask).to(tl.float32)
553
+ if zero_centered_weight:
554
+ w += 1.0
555
+ if RECOMPUTE_OUTPUT and HAS_BIAS:
556
+ b = tl.load(B + cols, mask=mask, other=0.0).to(tl.float32)
557
+ if HAS_DY1:
558
+ w1 = tl.load(W1 + cols, mask=mask).to(tl.float32)
559
+ if zero_centered_weight:
560
+ w1 += 1.0
561
+ dw = tl.zeros((BLOCK_N,), dtype=tl.float32)
562
+ if HAS_BIAS:
563
+ db = tl.zeros((BLOCK_N,), dtype=tl.float32)
564
+ if HAS_DY1:
565
+ dw1 = tl.zeros((BLOCK_N,), dtype=tl.float32)
566
+ if HAS_B1:
567
+ db1 = tl.zeros((BLOCK_N,), dtype=tl.float32)
568
+ row_end = min((row_block_id + 1) * rows_per_program, M)
569
+ for row in range(row_start, row_end):
570
+ # Load data to SRAM
571
+ x = tl.load(X + cols, mask=mask, other=0).to(tl.float32)
572
+ dy = tl.load(DY + cols, mask=mask, other=0).to(tl.float32)
573
+ if HAS_DY1:
574
+ dy1 = tl.load(DY1 + cols, mask=mask, other=0).to(tl.float32)
575
+ if not IS_RMS_NORM:
576
+ mean = tl.load(Mean + row)
577
+ rstd = tl.load(Rstd + row)
578
+ # Compute dx
579
+ xhat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd
580
+ xhat = tl.where(mask, xhat, 0.0)
581
+ if RECOMPUTE_OUTPUT:
582
+ y = xhat * w + b if HAS_BIAS else xhat * w
583
+ tl.store(Y + cols, y, mask=mask)
584
+ wdy = w * dy
585
+ dw += dy * xhat
586
+ if HAS_BIAS:
587
+ db += dy
588
+ if HAS_DY1:
589
+ wdy += w1 * dy1
590
+ dw1 += dy1 * xhat
591
+ if HAS_B1:
592
+ db1 += dy1
593
+ if not IS_RMS_NORM:
594
+ c1 = tl.sum(xhat * wdy, axis=0) / N
595
+ c2 = tl.sum(wdy, axis=0) / N
596
+ dx = (wdy - (xhat * c1 + c2)) * rstd
597
+ else:
598
+ c1 = tl.sum(xhat * wdy, axis=0) / N
599
+ dx = (wdy - xhat * c1) * rstd
600
+ if HAS_DRESIDUAL:
601
+ dres = tl.load(DRESIDUAL + cols, mask=mask, other=0).to(tl.float32)
602
+ dx += dres
603
+ # Write dx
604
+ if STORE_DRESIDUAL:
605
+ tl.store(DRESIDUAL_IN + cols, dx, mask=mask)
606
+ if HAS_DX1:
607
+ if HAS_DROPOUT:
608
+ keep_mask = (
609
+ tl.rand(tl.load(SEEDS + M + row).to(tl.uint32), cols, n_rounds=7) > dropout_p
610
+ )
611
+ dx1 = tl.where(keep_mask, dx / (1.0 - dropout_p), 0.0)
612
+ else:
613
+ dx1 = dx
614
+ tl.store(DX1 + cols, dx1, mask=mask)
615
+ if HAS_DROPOUT:
616
+ keep_mask = tl.rand(tl.load(SEEDS + row).to(tl.uint32), cols, n_rounds=7) > dropout_p
617
+ dx = tl.where(keep_mask, dx / (1.0 - dropout_p), 0.0)
618
+ if HAS_ROWSCALE:
619
+ rowscale = tl.load(ROWSCALE + row).to(tl.float32)
620
+ dx *= rowscale
621
+ tl.store(DX + cols, dx, mask=mask)
622
+
623
+ X += stride_x_row
624
+ if HAS_DRESIDUAL:
625
+ DRESIDUAL += stride_dres_row
626
+ if STORE_DRESIDUAL:
627
+ DRESIDUAL_IN += stride_dres_in_row
628
+ if RECOMPUTE_OUTPUT:
629
+ Y += stride_y_row
630
+ DY += stride_dy_row
631
+ DX += stride_dx_row
632
+ if HAS_DY1:
633
+ DY1 += stride_dy1_row
634
+ if HAS_DX1:
635
+ DX1 += stride_dx1_row
636
+ tl.store(DW + row_block_id * N + cols, dw, mask=mask)
637
+ if HAS_BIAS:
638
+ tl.store(DB + row_block_id * N + cols, db, mask=mask)
639
+ if HAS_DY1:
640
+ tl.store(DW1 + row_block_id * N + cols, dw1, mask=mask)
641
+ if HAS_B1:
642
+ tl.store(DB1 + row_block_id * N + cols, db1, mask=mask)
643
+
644
+
645
+ def _layer_norm_bwd(
646
+ dy: Tensor,
647
+ x: Tensor,
648
+ weight: Tensor,
649
+ bias: Tensor,
650
+ eps: float,
651
+ mean: Tensor,
652
+ rstd: Tensor,
653
+ dresidual: Optional[Tensor] = None,
654
+ dy1: Optional[Tensor] = None,
655
+ weight1: Optional[Tensor] = None,
656
+ bias1: Optional[Tensor] = None,
657
+ seeds: Optional[Tensor] = None,
658
+ dropout_p: float = 0.0,
659
+ rowscale: Optional[Tensor] = None,
660
+ has_residual: bool = False,
661
+ has_x1: bool = False,
662
+ zero_centered_weight: bool = False,
663
+ is_rms_norm: bool = False,
664
+ x_dtype: Optional[torch.dtype] = None,
665
+ recompute_output: bool = False,
666
+ ) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor):
667
+ # Need to wrap to handle the case where dresidual_in or dx1 are aliases of x,
668
+ # which makes torch.library unhappy
669
+ dx, dw, db, dresidual_in, dx1, dw1, db1, y = _layer_norm_bwd_impl(
670
+ dy,
671
+ x,
672
+ weight,
673
+ bias,
674
+ eps,
675
+ mean,
676
+ rstd,
677
+ dresidual,
678
+ dy1,
679
+ weight1,
680
+ bias1,
681
+ seeds,
682
+ dropout_p,
683
+ rowscale,
684
+ has_residual,
685
+ has_x1,
686
+ zero_centered_weight,
687
+ is_rms_norm,
688
+ x_dtype=x_dtype,
689
+ recompute_output=recompute_output,
690
+ )
691
+ # Don't need to compute dresidual_in separately in this case
692
+ if has_residual and dx.dtype == x.dtype and dropout_p == 0.0 and rowscale is None:
693
+ dresidual_in = dx
694
+ if has_x1 and dropout_p == 0.0:
695
+ dx1 = dx
696
+ return dx, dw, db, dresidual_in, dx1, dw1, db1, y
697
+
698
+
699
+
700
+ @triton_op(add_op_namespace_prefix("layer_norm_bwd_impl"), mutates_args={},
701
+ schema="(Tensor dy, Tensor x, Tensor weight, Tensor bias, float eps, Tensor mean, Tensor rstd, Tensor? dresidual, Tensor? dy1, Tensor? weight1, Tensor? bias1, Tensor? seeds, float dropout_p, Tensor? rowscale, bool has_residual, bool has_x1, bool zero_centered_weight, bool is_rms_norm, ScalarType? x_dtype, bool recompute_output) -> (Tensor dx, Tensor dw, Tensor db, Tensor dresidual_in, Tensor dx1, Tensor dw1, Tensor db1, Tensor y)",
702
+ allow_decomposition=False, # Don't let torch.compile trace inside
703
+ )
704
+ def _layer_norm_bwd_impl(
705
+ dy: Tensor,
706
+ x: Tensor,
707
+ weight: Tensor,
708
+ bias: Tensor,
709
+ eps: float,
710
+ mean: Tensor,
711
+ rstd: Tensor,
712
+ dresidual: Optional[Tensor] = None,
713
+ dy1: Optional[Tensor] = None,
714
+ weight1: Optional[Tensor] = None,
715
+ bias1: Optional[Tensor] = None,
716
+ seeds: Optional[Tensor] = None,
717
+ dropout_p: float = 0.0,
718
+ rowscale: Optional[Tensor] = None,
719
+ has_residual: bool = False,
720
+ has_x1: bool = False,
721
+ zero_centered_weight: bool = False,
722
+ is_rms_norm: bool = False,
723
+ x_dtype: Optional[torch.dtype] = None,
724
+ recompute_output: bool = False,
725
+ ) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor):
726
+ M, N = x.shape
727
+ assert x.stride(-1) == 1
728
+ dy = maybe_contiguous_lastdim(dy)
729
+ assert dy.stride(-1) == 1
730
+ assert dy.shape == (M, N)
731
+ if dresidual is not None:
732
+ dresidual = maybe_contiguous_lastdim(dresidual)
733
+ assert dresidual.stride(-1) == 1
734
+ assert dresidual.shape == (M, N)
735
+ assert weight.shape == (N,)
736
+ assert weight.stride(-1) == 1
737
+ if bias is not None:
738
+ assert bias.stride(-1) == 1
739
+ assert bias.shape == (N,)
740
+ if dy1 is not None:
741
+ dy1 = maybe_contiguous_lastdim(dy1)
742
+ assert weight1 is not None
743
+ assert dy1.shape == dy.shape
744
+ assert dy1.stride(-1) == 1
745
+ if weight1 is not None:
746
+ assert weight1.shape == (N,)
747
+ assert weight1.stride(-1) == 1
748
+ if bias1 is not None:
749
+ assert bias1.shape == (N,)
750
+ assert bias1.stride(-1) == 1
751
+ if seeds is not None:
752
+ assert seeds.is_contiguous()
753
+ assert seeds.shape == (M if not has_x1 else M * 2,)
754
+ if rowscale is not None:
755
+ assert rowscale.is_contiguous()
756
+ assert rowscale.shape == (M,)
757
+ # allocate output
758
+ dx = (
759
+ torch.empty_like(x)
760
+ if x_dtype is None
761
+ else torch.empty(M, N, dtype=x_dtype, device=x.device)
762
+ )
763
+ dresidual_in = (
764
+ torch.empty_like(x)
765
+ if has_residual
766
+ and (dx.dtype != x.dtype or dropout_p > 0.0 or rowscale is not None or has_x1)
767
+ else None
768
+ )
769
+ dx1 = torch.empty_like(dx) if (has_x1 and dropout_p > 0.0) else None
770
+ y = torch.empty(M, N, dtype=dy.dtype, device=dy.device) if recompute_output else None
771
+ if recompute_output:
772
+ assert weight1 is None, "recompute_output is not supported with parallel LayerNorm"
773
+
774
+ # Less than 64KB per feature: enqueue fused kernel
775
+ MAX_FUSED_SIZE = 65536 // x.element_size()
776
+ BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N))
777
+ if N > BLOCK_N:
778
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
779
+ # Increasing the multiple (e.g. 8) will allow more thread blocks to be launched and hide the
780
+ # latency of the gmem reads/writes, but will increase the time of summing up dw / db.
781
+ sm_count = torch.cuda.get_device_properties(x.device).multi_processor_count * 8
782
+ _dw = torch.empty((sm_count, N), dtype=torch.float32, device=weight.device)
783
+ _db = (
784
+ torch.empty((sm_count, N), dtype=torch.float32, device=bias.device)
785
+ if bias is not None
786
+ else None
787
+ )
788
+ _dw1 = torch.empty_like(_dw) if weight1 is not None else None
789
+ _db1 = torch.empty_like(_db) if bias1 is not None else None
790
+ rows_per_program = math.ceil(M / sm_count)
791
+ grid = (sm_count,)
792
+ with torch.cuda.device(x.device.index):
793
+ torch.library.wrap_triton(_layer_norm_bwd_kernel)[grid](
794
+ x,
795
+ weight,
796
+ bias,
797
+ y,
798
+ dy,
799
+ dx,
800
+ _dw,
801
+ _db,
802
+ dresidual,
803
+ weight1,
804
+ dy1,
805
+ dx1,
806
+ _dw1,
807
+ _db1,
808
+ dresidual_in,
809
+ rowscale,
810
+ seeds,
811
+ mean,
812
+ rstd,
813
+ x.stride(0),
814
+ 0 if not recompute_output else y.stride(0),
815
+ dy.stride(0),
816
+ dx.stride(0),
817
+ dresidual.stride(0) if dresidual is not None else 0,
818
+ dy1.stride(0) if dy1 is not None else 0,
819
+ dx1.stride(0) if dx1 is not None else 0,
820
+ dresidual_in.stride(0) if dresidual_in is not None else 0,
821
+ M,
822
+ N,
823
+ eps,
824
+ dropout_p,
825
+ # Passing bool make torch inductor very unhappy since it then tries to compare to int_max
826
+ int(zero_centered_weight),
827
+ rows_per_program,
828
+ is_rms_norm,
829
+ BLOCK_N,
830
+ dresidual is not None,
831
+ dresidual_in is not None,
832
+ bias is not None,
833
+ dropout_p > 0.0,
834
+ HAS_ROWSCALE=rowscale is not None,
835
+ HAS_DY1=dy1 is not None,
836
+ HAS_DX1=dx1 is not None,
837
+ HAS_B1=bias1 is not None,
838
+ RECOMPUTE_OUTPUT=y is not None,
839
+ )
840
+ dw = _dw.sum(0).to(weight.dtype)
841
+ db = _db.sum(0).to(bias.dtype) if bias is not None else None
842
+ dw1 = _dw1.sum(0).to(weight1.dtype) if weight1 is not None else None
843
+ db1 = _db1.sum(0).to(bias1.dtype) if bias1 is not None else None
844
+ # dresidual_in and dx1 could be None, the wrapper will handle assigning them from dx
845
+ return dx, dw, db, dresidual_in, dx1, dw1, db1, y
846
+
847
+
848
+ class LayerNormFn(torch.autograd.Function):
849
+
850
+ @staticmethod
851
+ def forward(
852
+ ctx,
853
+ x,
854
+ weight,
855
+ bias,
856
+ residual=None,
857
+ x1=None,
858
+ weight1=None,
859
+ bias1=None,
860
+ eps=1e-6,
861
+ dropout_p=0.0,
862
+ rowscale=None,
863
+ prenorm=False,
864
+ residual_in_fp32=False,
865
+ zero_centered_weight=False,
866
+ is_rms_norm=False,
867
+ return_dropout_mask=False,
868
+ out_dtype=None,
869
+ out=None,
870
+ residual_out=None
871
+ ):
872
+ x_shape_og = x.shape
873
+ # reshape input data into 2D tensor
874
+ x = maybe_contiguous_lastdim(x.reshape(-1, x.shape[-1]))
875
+ if residual is not None:
876
+ assert residual.shape == x_shape_og
877
+ residual = maybe_contiguous_lastdim(residual.reshape(-1, residual.shape[-1]))
878
+ if x1 is not None:
879
+ assert x1.shape == x_shape_og
880
+ assert rowscale is None, "rowscale is not supported with parallel LayerNorm"
881
+ x1 = maybe_contiguous_lastdim(x1.reshape(-1, x1.shape[-1]))
882
+ weight = weight.contiguous()
883
+ bias = maybe_contiguous(bias)
884
+ weight1 = maybe_contiguous(weight1)
885
+ bias1 = maybe_contiguous(bias1)
886
+ if rowscale is not None:
887
+ rowscale = rowscale.reshape(-1).contiguous()
888
+ residual_dtype = (
889
+ residual.dtype
890
+ if residual is not None
891
+ else (torch.float32 if residual_in_fp32 else None)
892
+ )
893
+ if out is not None:
894
+ out = out.reshape(-1, out.shape[-1])
895
+ if residual_out is not None:
896
+ residual_out = residual_out.reshape(-1, residual_out.shape[-1])
897
+ y, y1, mean, rstd, residual_out, seeds, dropout_mask, dropout_mask1 = _layer_norm_fwd(
898
+ x,
899
+ weight,
900
+ bias,
901
+ eps,
902
+ residual,
903
+ x1,
904
+ weight1,
905
+ bias1,
906
+ dropout_p=dropout_p,
907
+ rowscale=rowscale,
908
+ out_dtype=out_dtype,
909
+ residual_dtype=residual_dtype,
910
+ zero_centered_weight=zero_centered_weight,
911
+ is_rms_norm=is_rms_norm,
912
+ return_dropout_mask=return_dropout_mask,
913
+ out=out,
914
+ residual_out=residual_out,
915
+ )
916
+ ctx.save_for_backward(
917
+ residual_out, weight, bias, weight1, bias1, rowscale, seeds, mean, rstd
918
+ )
919
+ ctx.x_shape_og = x_shape_og
920
+ ctx.eps = eps
921
+ ctx.dropout_p = dropout_p
922
+ ctx.is_rms_norm = is_rms_norm
923
+ ctx.has_residual = residual is not None
924
+ ctx.has_x1 = x1 is not None
925
+ ctx.prenorm = prenorm
926
+ ctx.x_dtype = x.dtype
927
+ ctx.zero_centered_weight = zero_centered_weight
928
+ y = y.reshape(x_shape_og)
929
+ y1 = y1.reshape(x_shape_og) if y1 is not None else None
930
+ residual_out = residual_out.reshape(x_shape_og) if residual_out is not None else None
931
+ dropout_mask = dropout_mask.reshape(x_shape_og) if dropout_mask is not None else None
932
+ dropout_mask1 = dropout_mask1.reshape(x_shape_og) if dropout_mask1 is not None else None
933
+ if not return_dropout_mask:
934
+ if weight1 is None:
935
+ return y if not prenorm else (y, residual_out)
936
+ else:
937
+ return (y, y1) if not prenorm else (y, y1, residual_out)
938
+ else:
939
+ if weight1 is None:
940
+ return (
941
+ (y, dropout_mask, dropout_mask1)
942
+ if not prenorm
943
+ else (y, residual_out, dropout_mask, dropout_mask1)
944
+ )
945
+ else:
946
+ return (
947
+ (y, y1, dropout_mask, dropout_mask1)
948
+ if not prenorm
949
+ else (y, y1, residual_out, dropout_mask, dropout_mask1)
950
+ )
951
+
952
+ @staticmethod
953
+ def backward(ctx, dy, *args):
954
+ x, weight, bias, weight1, bias1, rowscale, seeds, mean, rstd = ctx.saved_tensors
955
+ dy = dy.reshape(-1, dy.shape[-1])
956
+ if weight1 is not None:
957
+ dy1, args = args[0], args[1:]
958
+ dy1 = dy1.reshape(-1, dy1.shape[-1])
959
+ assert dy1.shape == x.shape
960
+ else:
961
+ dy1 = None
962
+ if ctx.prenorm:
963
+ dresidual = args[0]
964
+ dresidual = dresidual.reshape(-1, dresidual.shape[-1])
965
+ assert dresidual.shape == x.shape
966
+ else:
967
+ dresidual = None
968
+ dx, dw, db, dresidual_in, dx1, dw1, db1, _ = _layer_norm_bwd(
969
+ dy,
970
+ x,
971
+ weight,
972
+ bias,
973
+ ctx.eps,
974
+ mean,
975
+ rstd,
976
+ dresidual,
977
+ dy1,
978
+ weight1,
979
+ bias1,
980
+ seeds,
981
+ ctx.dropout_p,
982
+ rowscale,
983
+ ctx.has_residual,
984
+ ctx.has_x1,
985
+ ctx.zero_centered_weight,
986
+ ctx.is_rms_norm,
987
+ x_dtype=ctx.x_dtype,
988
+ recompute_output=False,
989
+ )
990
+ return (
991
+ dx.reshape(ctx.x_shape_og),
992
+ dw,
993
+ db,
994
+ dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
995
+ dx1.reshape(ctx.x_shape_og) if dx1 is not None else None,
996
+ dw1,
997
+ db1,
998
+ None,
999
+ None,
1000
+ None,
1001
+ None,
1002
+ None,
1003
+ None,
1004
+ None,
1005
+ None,
1006
+ None,
1007
+ None,
1008
+ None,
1009
+ )
1010
+
1011
+
1012
+ def layer_norm_fn(
1013
+ x,
1014
+ weight,
1015
+ bias,
1016
+ residual=None,
1017
+ x1=None,
1018
+ weight1=None,
1019
+ bias1=None,
1020
+ eps=1e-6,
1021
+ dropout_p=0.0,
1022
+ rowscale=None,
1023
+ prenorm=False,
1024
+ residual_in_fp32=False,
1025
+ zero_centered_weight=False,
1026
+ is_rms_norm=False,
1027
+ return_dropout_mask=False,
1028
+ out_dtype=None,
1029
+ out=None,
1030
+ residual_out=None
1031
+ ):
1032
+ return LayerNormFn.apply(
1033
+ x,
1034
+ weight,
1035
+ bias,
1036
+ residual,
1037
+ x1,
1038
+ weight1,
1039
+ bias1,
1040
+ eps,
1041
+ dropout_p,
1042
+ rowscale,
1043
+ prenorm,
1044
+ residual_in_fp32,
1045
+ zero_centered_weight,
1046
+ is_rms_norm,
1047
+ return_dropout_mask,
1048
+ out_dtype,
1049
+ out,
1050
+ residual_out
1051
+ )
1052
+
1053
+
1054
+ def rms_norm_fn(
1055
+ x,
1056
+ weight,
1057
+ bias,
1058
+ residual=None,
1059
+ x1=None,
1060
+ weight1=None,
1061
+ bias1=None,
1062
+ eps=1e-6,
1063
+ dropout_p=0.0,
1064
+ rowscale=None,
1065
+ prenorm=False,
1066
+ residual_in_fp32=False,
1067
+ zero_centered_weight=False,
1068
+ return_dropout_mask=False,
1069
+ out_dtype=None,
1070
+ out=None,
1071
+ residual_out=None
1072
+ ):
1073
+ return LayerNormFn.apply(
1074
+ x,
1075
+ weight,
1076
+ bias,
1077
+ residual,
1078
+ x1,
1079
+ weight1,
1080
+ bias1,
1081
+ eps,
1082
+ dropout_p,
1083
+ rowscale,
1084
+ prenorm,
1085
+ residual_in_fp32,
1086
+ zero_centered_weight,
1087
+ True,
1088
+ return_dropout_mask,
1089
+ out_dtype,
1090
+ out,
1091
+ residual_out
1092
+ )
1093
+
1094
+
1095
+ class RMSNorm(torch.nn.Module):
1096
+
1097
+ def __init__(self, hidden_size, eps=1e-5, dropout_p=0.0, zero_centered_weight=False,
1098
+ device=None, dtype=None):
1099
+ factory_kwargs = {"device": device, "dtype": dtype}
1100
+ super().__init__()
1101
+ self.eps = eps
1102
+ if dropout_p > 0.0:
1103
+ self.drop = torch.nn.Dropout(dropout_p)
1104
+ else:
1105
+ self.drop = None
1106
+ self.zero_centered_weight = zero_centered_weight
1107
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
1108
+ self.register_parameter("bias", None)
1109
+ self.reset_parameters()
1110
+
1111
+ def reset_parameters(self):
1112
+ if not self.zero_centered_weight:
1113
+ torch.nn.init.ones_(self.weight)
1114
+ else:
1115
+ torch.nn.init.zeros_(self.weight)
1116
+
1117
+ def forward(self, x, residual=None, prenorm=False, residual_in_fp32=False):
1118
+ return rms_norm_fn(
1119
+ x,
1120
+ self.weight,
1121
+ self.bias,
1122
+ residual=residual,
1123
+ eps=self.eps,
1124
+ dropout_p=self.drop.p if self.drop is not None and self.training else 0.0,
1125
+ prenorm=prenorm,
1126
+ residual_in_fp32=residual_in_fp32,
1127
+ zero_centered_weight=self.zero_centered_weight,
1128
+ )
1129
+
1130
+
1131
+ class LayerNormLinearFn(torch.autograd.Function):
1132
+
1133
+ @staticmethod
1134
+ @custom_fwd
1135
+ def forward(
1136
+ ctx,
1137
+ x,
1138
+ norm_weight,
1139
+ norm_bias,
1140
+ linear_weight,
1141
+ linear_bias,
1142
+ residual=None,
1143
+ eps=1e-6,
1144
+ prenorm=False,
1145
+ residual_in_fp32=False,
1146
+ is_rms_norm=False,
1147
+ ):
1148
+ x_shape_og = x.shape
1149
+ # reshape input data into 2D tensor
1150
+ x = maybe_contiguous_lastdim(x.reshape(-1, x.shape[-1]))
1151
+ if residual is not None:
1152
+ assert residual.shape == x_shape_og
1153
+ residual = maybe_contiguous_lastdim(residual.reshape(-1, residual.shape[-1]))
1154
+ norm_weight = norm_weight.contiguous()
1155
+ norm_bias = maybe_contiguous(norm_bias)
1156
+ residual_dtype = (
1157
+ residual.dtype
1158
+ if residual is not None
1159
+ else (torch.float32 if residual_in_fp32 else None)
1160
+ )
1161
+ y, _, mean, rstd, residual_out, *rest = _layer_norm_fwd(
1162
+ x,
1163
+ norm_weight,
1164
+ norm_bias,
1165
+ eps,
1166
+ residual,
1167
+ out_dtype=None if not torch.is_autocast_enabled() else torch.get_autocast_dtype("cuda"),
1168
+ residual_dtype=residual_dtype,
1169
+ is_rms_norm=is_rms_norm,
1170
+ )
1171
+ y = y.reshape(x_shape_og)
1172
+ dtype = torch.get_autocast_dtype("cuda") if torch.is_autocast_enabled() else y.dtype
1173
+ linear_weight = linear_weight.to(dtype)
1174
+ linear_bias = linear_bias.to(dtype) if linear_bias is not None else None
1175
+ out = F.linear(y.to(linear_weight.dtype), linear_weight, linear_bias)
1176
+ # We don't store y, will be recomputed in the backward pass to save memory
1177
+ ctx.save_for_backward(residual_out, norm_weight, norm_bias, linear_weight, mean, rstd)
1178
+ ctx.x_shape_og = x_shape_og
1179
+ ctx.eps = eps
1180
+ ctx.is_rms_norm = is_rms_norm
1181
+ ctx.has_residual = residual is not None
1182
+ ctx.prenorm = prenorm
1183
+ ctx.x_dtype = x.dtype
1184
+ ctx.linear_bias_is_none = linear_bias is None
1185
+ return out if not prenorm else (out, residual_out.reshape(x_shape_og))
1186
+
1187
+ @staticmethod
1188
+ @custom_bwd
1189
+ def backward(ctx, dout, *args):
1190
+ x, norm_weight, norm_bias, linear_weight, mean, rstd = ctx.saved_tensors
1191
+ dout = dout.reshape(-1, dout.shape[-1])
1192
+ dy = F.linear(dout, linear_weight.t())
1193
+ dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0)
1194
+ dy = maybe_contiguous_lastdim(dy)
1195
+ assert dy.shape == x.shape
1196
+ if ctx.prenorm:
1197
+ dresidual = args[0]
1198
+ dresidual = maybe_contiguous_lastdim(dresidual.reshape(-1, dresidual.shape[-1]))
1199
+ assert dresidual.shape == x.shape
1200
+ else:
1201
+ dresidual = None
1202
+ dx, dnorm_weight, dnorm_bias, dresidual_in, _, _, _, y = _layer_norm_bwd(
1203
+ dy,
1204
+ x,
1205
+ norm_weight,
1206
+ norm_bias,
1207
+ ctx.eps,
1208
+ mean,
1209
+ rstd,
1210
+ dresidual=dresidual,
1211
+ has_residual=ctx.has_residual,
1212
+ is_rms_norm=ctx.is_rms_norm,
1213
+ x_dtype=ctx.x_dtype,
1214
+ recompute_output=True,
1215
+ )
1216
+ dlinear_weight = torch.einsum("bo,bi->oi", dout, y)
1217
+ return (
1218
+ dx.reshape(ctx.x_shape_og),
1219
+ dnorm_weight,
1220
+ dnorm_bias,
1221
+ dlinear_weight,
1222
+ dlinear_bias,
1223
+ dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None,
1224
+ None,
1225
+ None,
1226
+ None,
1227
+ None,
1228
+ )
1229
+
1230
+
1231
+ def layer_norm_linear_fn(
1232
+ x,
1233
+ norm_weight,
1234
+ norm_bias,
1235
+ linear_weight,
1236
+ linear_bias,
1237
+ residual=None,
1238
+ eps=1e-6,
1239
+ prenorm=False,
1240
+ residual_in_fp32=False,
1241
+ is_rms_norm=False,
1242
+ ):
1243
+ return LayerNormLinearFn.apply(
1244
+ x,
1245
+ norm_weight,
1246
+ norm_bias,
1247
+ linear_weight,
1248
+ linear_bias,
1249
+ residual,
1250
+ eps,
1251
+ prenorm,
1252
+ residual_in_fp32,
1253
+ is_rms_norm,
1254
+ )
build/torch211-cxx11-cu128-aarch64-linux/ops/triton/linear.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/ELS-RD/kernl/blob/main/src/kernl/implementations/linear_layer.py
2
+ # and https://github.com/openai/triton/blob/master/python/triton/ops/matmul.py
3
+ from typing import Optional
4
+
5
+ import torch
6
+ import triton
7
+ import triton.language as tl
8
+ from triton.ops.matmul_perf_model import early_config_prune, estimate_matmul_time
9
+
10
+ from flash_attn.ops.triton.k_activations import (
11
+ gelu,
12
+ gelu_approx,
13
+ gelu_approx_grad,
14
+ gelu_grad,
15
+ squared_relu,
16
+ squared_relu_grad,
17
+ )
18
+
19
+ # CREDITS: Initially inspired by the Triton tutorial on matrix multiplications
20
+
21
+
22
+ def init_to_zero(name):
23
+ return lambda nargs: nargs[name].zero_()
24
+
25
+
26
+ def get_configs_io_bound():
27
+ configs = []
28
+ for num_stages in [2, 3, 4, 5, 6]:
29
+ for block_m in [16, 32]:
30
+ for block_k in [32, 64]:
31
+ for block_n in [32, 64, 128, 256]:
32
+ num_warps = 2 if block_n <= 64 else 4
33
+ configs.append(
34
+ triton.Config(
35
+ {
36
+ "BLOCK_M": block_m,
37
+ "BLOCK_N": block_n,
38
+ "BLOCK_K": block_k,
39
+ "SPLIT_K": 1,
40
+ },
41
+ num_stages=num_stages,
42
+ num_warps=num_warps,
43
+ )
44
+ )
45
+ # split_k not used
46
+ # for split_k in [2, 4, 8, 16]:
47
+ # configs.append(triton.Config(
48
+ # {'BLOCK_M': block_m, 'BLOCK_N': block_n, 'BLOCK_K': block_k, 'SPLIT_K': split_k},
49
+ # num_stages=num_stages, num_warps=num_warps, pre_hook=init_to_zero('C')))
50
+ return configs
51
+
52
+
53
+ @triton.autotune(
54
+ configs=[
55
+ triton.Config(
56
+ {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8
57
+ ),
58
+ triton.Config(
59
+ {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8
60
+ ),
61
+ triton.Config(
62
+ {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
63
+ ),
64
+ triton.Config(
65
+ {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
66
+ ),
67
+ triton.Config(
68
+ {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
69
+ ),
70
+ triton.Config(
71
+ {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
72
+ ),
73
+ triton.Config(
74
+ {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
75
+ ),
76
+ triton.Config(
77
+ {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
78
+ ),
79
+ triton.Config(
80
+ {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=5, num_warps=2
81
+ ),
82
+ # good for int8
83
+ triton.Config(
84
+ {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1},
85
+ num_stages=3,
86
+ num_warps=8,
87
+ ),
88
+ triton.Config(
89
+ {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1},
90
+ num_stages=3,
91
+ num_warps=8,
92
+ ),
93
+ triton.Config(
94
+ {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4
95
+ ),
96
+ triton.Config(
97
+ {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4
98
+ ),
99
+ triton.Config(
100
+ {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1},
101
+ num_stages=4,
102
+ num_warps=4,
103
+ ),
104
+ triton.Config(
105
+ {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
106
+ ),
107
+ triton.Config(
108
+ {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
109
+ ),
110
+ triton.Config(
111
+ {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
112
+ ),
113
+ triton.Config(
114
+ {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=5, num_warps=2
115
+ ),
116
+ ]
117
+ + get_configs_io_bound(),
118
+ key=["CACHE_KEY_M", "CACHE_KEY_N", "CACHE_KEY_K"],
119
+ prune_configs_by={
120
+ "early_config_prune": early_config_prune,
121
+ "perf_model": estimate_matmul_time,
122
+ "top_k": 10,
123
+ },
124
+ )
125
+ @triton.heuristics(
126
+ {
127
+ "EVEN_K": lambda args: args["K"] % (args["BLOCK_K"] * args["SPLIT_K"]) == 0,
128
+ }
129
+ )
130
+ @triton.jit
131
+ def kernel_fwd(
132
+ C, # Pointers to matrices
133
+ ACT_INPUT,
134
+ A,
135
+ B,
136
+ bias,
137
+ # Matrix dimensions
138
+ M,
139
+ N,
140
+ K,
141
+ CACHE_KEY_M,
142
+ CACHE_KEY_N,
143
+ CACHE_KEY_K,
144
+ # The stride variables represent how much to increase the ptr by when moving by 1
145
+ # element in a particular dimension. E.g. stride_am is how much to increase a_ptr
146
+ # by to get the element one row down (A has M rows)
147
+ stride_cm,
148
+ # stride_cn, # Assume that stride_cn == 1
149
+ stride_am,
150
+ stride_ak,
151
+ stride_bn,
152
+ stride_bk,
153
+ # Meta-parameters
154
+ BLOCK_M: tl.constexpr,
155
+ GROUP_M: tl.constexpr,
156
+ BLOCK_N: tl.constexpr,
157
+ BLOCK_K: tl.constexpr,
158
+ # split k not used, not performant with activation, kept because early_config_prune is expecting it
159
+ SPLIT_K: tl.constexpr,
160
+ EVEN_K: tl.constexpr,
161
+ A_ROWMAJOR: tl.constexpr,
162
+ B_COLMAJOR: tl.constexpr,
163
+ BIAS: tl.constexpr,
164
+ SAVE_ACT_INPUT: tl.constexpr,
165
+ ACTIVATION: tl.constexpr,
166
+ ):
167
+
168
+ """
169
+ Kernel for computing Out = activation(A x W + C)
170
+ - Input has shape (M, K)
171
+ - Weight has shape (K, N)
172
+ - Bias has shape (N,)
173
+ - Output has shape (M, N)
174
+ - ActInputs (optional) has shape (M, N)
175
+ 'ActInputs' optionally saves the A x W + C intermediate for backward computations
176
+ This kernel will consolidate over K
177
+ """
178
+
179
+ pid = tl.program_id(axis=0)
180
+
181
+ grid_m = (M + BLOCK_M - 1) // BLOCK_M
182
+ grid_n = (N + BLOCK_N - 1) // BLOCK_N
183
+ # re-order program ID for better L2 performance
184
+ width = GROUP_M * grid_n
185
+ group_id = pid // width
186
+ group_size = min(grid_m - group_id * GROUP_M, GROUP_M)
187
+ pid_m = group_id * GROUP_M + (pid % group_size)
188
+ pid_n = (pid % width) // (group_size)
189
+
190
+ # now compute the block that each program will go through
191
+ # rm (resp. rn) denotes a range of indices
192
+ # for rows (resp. col) of C
193
+ rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
194
+ rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
195
+ # trick to avoid masking on M and N axis
196
+ ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M)
197
+ rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N)
198
+ rk = tl.arange(0, BLOCK_K)
199
+
200
+ if A_ROWMAJOR:
201
+ A = A + (ram[:, None] * stride_am + rk[None, :])
202
+ else:
203
+ A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak)
204
+ if B_COLMAJOR:
205
+ B = B + (rk[:, None] + rbn[None, :] * stride_bn)
206
+ else:
207
+ B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn)
208
+
209
+ acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
210
+
211
+ for k in range(K, 0, -BLOCK_K):
212
+ if EVEN_K:
213
+ a = tl.load(A)
214
+ b = tl.load(B)
215
+ else:
216
+ a = tl.load(A, mask=rk[None, :] < k, other=0.0)
217
+ b = tl.load(B, mask=rk[:, None] < k, other=0.0)
218
+ acc += tl.dot(a, b)
219
+
220
+ if A_ROWMAJOR:
221
+ A += BLOCK_K
222
+ else:
223
+ A += BLOCK_K * stride_ak
224
+ if B_COLMAJOR:
225
+ B += BLOCK_K
226
+ else:
227
+ B += BLOCK_K * stride_bk
228
+
229
+ # Putting bias after the matmul (instead of before) is faster, idk why
230
+ if BIAS:
231
+ bias = tl.load(bias + rn, mask=rn < N, other=0.0).to(tl.float32)
232
+ acc += bias[None, :]
233
+
234
+ # optional: save the activation inputs
235
+ if SAVE_ACT_INPUT:
236
+ # act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :] * stride_cn
237
+ act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :]
238
+ tl.store(act_in_ptrs, acc)
239
+
240
+ # optional: fused activation (while the data is in shared memory)
241
+ if ACTIVATION == "gelu":
242
+ acc = gelu(acc)
243
+ elif ACTIVATION == "gelu_approx":
244
+ acc = gelu_approx(acc)
245
+ elif ACTIVATION == "squared_relu":
246
+ acc = squared_relu(acc)
247
+ # rematerialize rm and rn to save registers
248
+ rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
249
+ rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
250
+
251
+ # write back result
252
+ # C = C + rm[:, None] * stride_cm + rn[None, :] * stride_cn
253
+ C = C + rm[:, None] * stride_cm + rn[None, :]
254
+ mask = (rm < M)[:, None] & (rn < N)[None, :]
255
+ tl.store(C, acc)
256
+
257
+
258
+ def triton_linear_act(
259
+ x: torch.Tensor,
260
+ weight: torch.Tensor,
261
+ bias: Optional[torch.Tensor] = None,
262
+ activation: str = "id",
263
+ save_act_input: bool = False,
264
+ ) -> torch.Tensor:
265
+ """
266
+ Compute e = activation(x @ weight.T + bias).
267
+ This wrapper kicks the `kernel_fwd` Triton kernel
268
+ :param x: input tensor
269
+ :param weight: weight matrix
270
+ :param bias: an optional bias tensor
271
+ :param activation: Activation name. Needs to be a Triton kernel.
272
+ :param act_input: an optional tensor to save the activation inputs (for backward)
273
+ :return: result tensor
274
+ """
275
+ # if torch.is_autocast_enabled():
276
+ # dtype = torch.get_autocast_gpu_dtype()
277
+ # x, weight, bias = [a.to(dtype=dtype) for a in [x, weight, bias]]
278
+
279
+ assert activation in ["id", "gelu", "gelu_approx", "squared_relu"]
280
+
281
+ batch_shape, n = x.shape[:-1], x.shape[-1]
282
+ batch_dim = batch_shape.numel()
283
+ x_reshaped = x.reshape(batch_dim, n)
284
+
285
+ if x_reshaped.stride(0) > 1 and x_reshaped.stride(1) > 1:
286
+ x_reshaped = x_reshaped.contiguous()
287
+ if weight.stride(0) > 1 and weight.stride(1) > 1:
288
+ weight = weight.contiguous()
289
+ bias = bias.contiguous() if bias is not None else None
290
+
291
+ assert (
292
+ x.dtype == weight.dtype
293
+ ), f"Input and weight must have the same dtype, got {x.dtype} and {weight.dtype}"
294
+ if bias is not None:
295
+ assert (
296
+ x.dtype == bias.dtype
297
+ ), f"Input and bias must have the same dtype, got {x.dtype} and {bias.dtype}"
298
+ assert (
299
+ x_reshaped.shape[1] == weight.shape[1]
300
+ ), f"Incompatible dimensions: {x_reshaped.shape} - {weight.shape}"
301
+
302
+ assert (
303
+ bias is None or bias.shape[0] == weight.shape[0]
304
+ ), "Incompatible dimensions in between weight and bias"
305
+
306
+ M, K = x_reshaped.shape
307
+ N, K = weight.shape
308
+
309
+ output = torch.empty((M, N), device=x.device, dtype=x.dtype)
310
+ act_input = torch.empty_like(output) if save_act_input else None
311
+
312
+ # 1D launch kernel where each block gets its own program.
313
+ grid = lambda META: (triton.cdiv(M, META["BLOCK_M"]) * triton.cdiv(N, META["BLOCK_N"]),) # noqa
314
+
315
+ kernel_fwd[grid](
316
+ output,
317
+ act_input,
318
+ x_reshaped,
319
+ weight, # data ptrs
320
+ bias if bias is not None else x, # auto skip bias if not present
321
+ M, # shapes
322
+ N,
323
+ K,
324
+ M // 32, # key for triton cache (limit number of compilations)
325
+ N // 32,
326
+ K // 32,
327
+ stride_cm=output.stride(0), # strides
328
+ # stride_cn=output.stride(1),
329
+ stride_am=x_reshaped.stride(0),
330
+ stride_ak=x_reshaped.stride(1),
331
+ stride_bk=weight.stride(1),
332
+ stride_bn=weight.stride(0),
333
+ BIAS=bias is not None, # optional fused bias
334
+ SAVE_ACT_INPUT=save_act_input, # optional save activation inputs
335
+ ACTIVATION=activation, # optional fused activation
336
+ A_ROWMAJOR=x_reshaped.stride(1) == 1,
337
+ B_COLMAJOR=weight.stride(1) == 1,
338
+ GROUP_M=8, # speed optimization: group the programs
339
+ )
340
+
341
+ if not save_act_input:
342
+ return output.reshape(*batch_shape, output.shape[-1])
343
+ else:
344
+ return (
345
+ output.reshape(*batch_shape, output.shape[-1]),
346
+ act_input.reshape(*batch_shape, act_input.shape[-1]),
347
+ )
348
+
349
+
350
+ @triton.autotune(
351
+ configs=[
352
+ triton.Config(
353
+ {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8
354
+ ),
355
+ triton.Config(
356
+ {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8
357
+ ),
358
+ triton.Config(
359
+ {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
360
+ ),
361
+ triton.Config(
362
+ {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
363
+ ),
364
+ triton.Config(
365
+ {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
366
+ ),
367
+ triton.Config(
368
+ {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
369
+ ),
370
+ triton.Config(
371
+ {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
372
+ ),
373
+ triton.Config(
374
+ {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4
375
+ ),
376
+ triton.Config(
377
+ {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=5, num_warps=2
378
+ ),
379
+ # good for int8
380
+ triton.Config(
381
+ {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1},
382
+ num_stages=3,
383
+ num_warps=8,
384
+ ),
385
+ triton.Config(
386
+ {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1},
387
+ num_stages=3,
388
+ num_warps=8,
389
+ ),
390
+ triton.Config(
391
+ {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4
392
+ ),
393
+ triton.Config(
394
+ {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4
395
+ ),
396
+ triton.Config(
397
+ {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1},
398
+ num_stages=4,
399
+ num_warps=4,
400
+ ),
401
+ triton.Config(
402
+ {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
403
+ ),
404
+ triton.Config(
405
+ {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
406
+ ),
407
+ triton.Config(
408
+ {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4
409
+ ),
410
+ triton.Config(
411
+ {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=5, num_warps=2
412
+ ),
413
+ ]
414
+ + get_configs_io_bound(),
415
+ key=["CACHE_KEY_M", "CACHE_KEY_N", "CACHE_KEY_K"],
416
+ prune_configs_by={
417
+ "early_config_prune": early_config_prune,
418
+ "perf_model": estimate_matmul_time,
419
+ "top_k": 10,
420
+ },
421
+ )
422
+ @triton.heuristics(
423
+ {
424
+ "EVEN_K": lambda args: args["K"] % (args["BLOCK_K"] * args["SPLIT_K"]) == 0,
425
+ }
426
+ )
427
+ @triton.jit
428
+ def kernel_bwd(
429
+ C, # Pointers to matrices
430
+ ACT_INPUT,
431
+ A,
432
+ B,
433
+ # Matrix dimensions
434
+ M,
435
+ N,
436
+ K,
437
+ CACHE_KEY_M,
438
+ CACHE_KEY_N,
439
+ CACHE_KEY_K,
440
+ # The stride variables represent how much to increase the ptr by when moving by 1
441
+ # element in a particular dimension. E.g. stride_am is how much to increase a_ptr
442
+ # by to get the element one row down (A has M rows)
443
+ stride_cm,
444
+ # stride_cn, # Assume that stride_cn == 1
445
+ stride_am,
446
+ stride_ak,
447
+ stride_bk,
448
+ stride_bn,
449
+ # Meta-parameters
450
+ BLOCK_M: tl.constexpr,
451
+ GROUP_M: tl.constexpr,
452
+ BLOCK_N: tl.constexpr,
453
+ BLOCK_K: tl.constexpr,
454
+ # split k not used, not performant with activation, kept because early_config_prune is expecting it
455
+ SPLIT_K: tl.constexpr,
456
+ EVEN_K: tl.constexpr,
457
+ ACTIVATION: tl.constexpr,
458
+ ):
459
+
460
+ """
461
+ Kernel for computing Out = activation(A x W + C)
462
+ - Input has shape (M, K)
463
+ - Weight has shape (K, N)
464
+ - Output has shape (M, N)
465
+ - ActInputs (optional) has shape (M, N)
466
+ 'ActInputs' optionally saves the A x W + C intermediate for backward computations
467
+ This kernel will consolidate over K
468
+ """
469
+
470
+ pid = tl.program_id(axis=0)
471
+
472
+ grid_m = (M + BLOCK_M - 1) // BLOCK_M
473
+ grid_n = (N + BLOCK_N - 1) // BLOCK_N
474
+ # re-order program ID for better L2 performance
475
+ width = GROUP_M * grid_n
476
+ group_id = pid // width
477
+ group_size = min(grid_m - group_id * GROUP_M, GROUP_M)
478
+ pid_m = group_id * GROUP_M + (pid % group_size)
479
+ pid_n = (pid % width) // (group_size)
480
+
481
+ # now compute the block that each program will go through
482
+ # rm (resp. rn) denotes a range of indices
483
+ # for rows (resp. col) of C
484
+ rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
485
+ rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
486
+ # trick to avoid masking on M and N axis
487
+ ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M)
488
+ rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N)
489
+ rk = tl.arange(0, BLOCK_K)
490
+
491
+ A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak)
492
+ B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn)
493
+
494
+ acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
495
+
496
+ for k in range(K, 0, -BLOCK_K):
497
+ if EVEN_K:
498
+ a = tl.load(A)
499
+ b = tl.load(B)
500
+ else:
501
+ a = tl.load(A, mask=rk[None, :] < k, other=0.0)
502
+ b = tl.load(B, mask=rk[:, None] < k, other=0.0)
503
+ acc += tl.dot(a, b)
504
+
505
+ A += BLOCK_K * stride_ak
506
+ B += BLOCK_K * stride_bk
507
+
508
+ # optional: fused activation (while the data is in shared memory)
509
+ if ACTIVATION != "id":
510
+ act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :]
511
+ act_input = tl.load(act_in_ptrs).to(acc.dtype)
512
+ if ACTIVATION == "gelu":
513
+ acc *= gelu_grad(act_input)
514
+ elif ACTIVATION == "gelu_approx":
515
+ acc *= gelu_approx_grad(act_input)
516
+ elif ACTIVATION == "squared_relu":
517
+ acc *= squared_relu_grad(act_input)
518
+
519
+ # rematerialize rm and rn to save registers
520
+ rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
521
+ rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
522
+
523
+ # write back result
524
+ C = C + rm[:, None] * stride_cm + rn[None, :]
525
+ mask = (rm < M)[:, None] & (rn < N)[None, :]
526
+ tl.store(C, acc, mask=mask)
527
+
528
+
529
+ def triton_dgrad_act(
530
+ grad_output: torch.Tensor,
531
+ weight: torch.Tensor,
532
+ activation: str = "id",
533
+ act_input: Optional[torch.Tensor] = None,
534
+ ) -> torch.Tensor:
535
+ """
536
+ Compute e = activation(grad_output @ weight + bias).
537
+ This wrapper kicks the `kernel_fwd` Triton kernel
538
+ :param grad_output: input tensor
539
+ :param weight: weight matrix
540
+ :param activation: Activation name. Needs to be a Triton kernel.
541
+ :param act_input: an optional tensor to save the activation inputs (for backward)
542
+ :return: result tensor
543
+ """
544
+ assert activation in ["id", "gelu", "gelu_approx", "squared_relu"]
545
+
546
+ batch_shape, n = grad_output.shape[:-1], grad_output.shape[-1]
547
+ batch_dim = batch_shape.numel()
548
+ grad_output_reshaped = grad_output.reshape(batch_dim, n)
549
+
550
+ if grad_output_reshaped.stride(0) > 1 and grad_output_reshaped.stride(1) > 1:
551
+ grad_output_reshaped = grad_output_reshaped.contiguous()
552
+ if weight.stride(0) > 1 and weight.stride(1) > 1:
553
+ weight = weight.contiguous()
554
+
555
+ assert (
556
+ grad_output.dtype == weight.dtype
557
+ ), f"grad_output and weight must have the same dtype, got {grad_output.dtype} and {weight.dtype}"
558
+ assert (
559
+ grad_output_reshaped.shape[1] == weight.shape[0]
560
+ ), f"Incompatible dimensions: {grad_output_reshaped.shape} - {weight.shape}"
561
+ if activation != "id":
562
+ assert act_input is not None, f"act_input is required for activation {activation}"
563
+
564
+ # M, N, K in bwd are different from M, N, K in fwd
565
+ M, K = grad_output_reshaped.shape
566
+ K, N = weight.shape
567
+
568
+ grad_input = torch.empty((M, N), device=grad_output.device, dtype=grad_output.dtype)
569
+
570
+ # 1D launch kernel where each block gets its own program.
571
+ grid = lambda META: (triton.cdiv(M, META["BLOCK_M"]) * triton.cdiv(N, META["BLOCK_N"]),) # noqa
572
+
573
+ kernel_bwd[grid](
574
+ grad_input,
575
+ act_input,
576
+ grad_output_reshaped,
577
+ weight, # data ptrs
578
+ M, # shapes
579
+ N,
580
+ K,
581
+ M // 32, # key for triton cache (limit number of compilations)
582
+ N // 32,
583
+ K // 32,
584
+ stride_cm=grad_input.stride(0), # strides
585
+ # stride_cn=grad_input.stride(1),
586
+ stride_am=grad_output_reshaped.stride(0),
587
+ stride_ak=grad_output_reshaped.stride(1),
588
+ stride_bk=weight.stride(0),
589
+ stride_bn=weight.stride(1),
590
+ ACTIVATION=activation, # optional fused activation
591
+ GROUP_M=8, # speed optimization: group the programs
592
+ )
593
+
594
+ return grad_input.reshape(*batch_shape, grad_input.shape[-1])
build/torch211-cxx11-cu128-aarch64-linux/ops/triton/mlp.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The triton fused matmul + sqrelu is faster for fp16 but slower for bf16, compared
2
+ # to naive implementation.
3
+ import fused_dense_lib as fused_dense_cuda
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ from flash_attn.utils.torch import custom_fwd, custom_bwd
9
+ from flash_attn.ops.activations import sqrelu_bwd, sqrelu_fwd
10
+ from flash_attn.ops.triton.linear import triton_dgrad_act, triton_linear_act
11
+
12
+
13
+ class FusedDenseSqreluDenseFunc(torch.autograd.Function):
14
+ @staticmethod
15
+ @custom_fwd
16
+ def forward(ctx, x, weight1, bias1, weight2, bias2, checkpoint_lvl=0):
17
+ """checkpoint_lvl:
18
+ 0: no recomputation in the bwd
19
+ 1: recompute gelu_out in the bwd
20
+ 2: recompute act_input and gelu_out in the bwd
21
+ """
22
+ if torch.is_autocast_enabled():
23
+ dtype = torch.get_autocast_gpu_dtype()
24
+ x, weight1, bias1, weight2, bias2 = [
25
+ a.to(dtype=dtype) for a in [x, weight1, bias1, weight2, bias2]
26
+ ]
27
+ is_bf16 = x.dtype == torch.bfloat16
28
+ assert checkpoint_lvl in [0, 1, 2]
29
+ x = x.contiguous()
30
+ weight1 = weight1.contiguous()
31
+ bias1 = bias1.contiguous()
32
+ weight2 = weight2.contiguous()
33
+ bias2 = bias2.contiguous()
34
+ batch_shape, n = x.shape[:-1], x.shape[-1]
35
+ batch_dim = batch_shape.numel()
36
+ if is_bf16:
37
+ act_input = fused_dense_cuda.linear_bias_forward(
38
+ x.reshape(batch_dim, n), weight1, bias1
39
+ )
40
+ output1 = sqrelu_fwd(act_input)
41
+ else:
42
+ save_act_input = checkpoint_lvl != 2
43
+ result = triton_linear_act(
44
+ x.reshape(batch_dim, n),
45
+ weight1,
46
+ bias1,
47
+ activation="squared_relu",
48
+ save_act_input=save_act_input,
49
+ )
50
+ if save_act_input:
51
+ output1, act_input = result
52
+ else:
53
+ output1 = result
54
+ output2 = fused_dense_cuda.linear_bias_forward(output1, weight2, bias2)
55
+ ctx.checkpoint_lvl = checkpoint_lvl
56
+ if checkpoint_lvl == 0:
57
+ ctx.save_for_backward(x, weight1, bias1, weight2, act_input, output1)
58
+ elif checkpoint_lvl == 1:
59
+ ctx.save_for_backward(x, weight1, bias1, weight2, act_input)
60
+ elif checkpoint_lvl == 2:
61
+ ctx.save_for_backward(x, weight1, bias1, weight2)
62
+ return output2.reshape(*batch_shape, output2.shape[-1])
63
+
64
+ @staticmethod
65
+ @custom_bwd
66
+ def backward(ctx, grad_output):
67
+ grad_output = grad_output.contiguous()
68
+ checkpoint_lvl = ctx.checkpoint_lvl
69
+ x, weight1, bias1, weight2, *rest = ctx.saved_tensors
70
+ batch_shape, n = x.shape[:-1], x.shape[-1]
71
+ batch_dim = batch_shape.numel()
72
+ is_bf16 = x.dtype == torch.bfloat16
73
+ if checkpoint_lvl == 0:
74
+ act_input, output1 = rest
75
+ elif checkpoint_lvl == 1:
76
+ (act_input,) = rest
77
+ output1 = sqrelu_fwd(act_input)
78
+ elif checkpoint_lvl == 2:
79
+ if is_bf16:
80
+ act_input = fused_dense_cuda.linear_bias_forward(
81
+ x.reshape(batch_dim, n), weight1, bias1
82
+ )
83
+ output1 = sqrelu_fwd(act_input)
84
+ else:
85
+ output1, act_input = triton_linear_act(
86
+ x.reshape(batch_dim, n),
87
+ weight1,
88
+ bias1,
89
+ activation="squared_relu",
90
+ save_act_input=True,
91
+ )
92
+
93
+ if is_bf16:
94
+ grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1])
95
+ grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad(output1, grad_output)
96
+ grad_output1 = grad_output @ weight2
97
+ grad_act_input = sqrelu_bwd(grad_output1, act_input)
98
+ grad_input, grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_backward(
99
+ x.reshape(batch_dim, n), weight1, grad_act_input
100
+ )
101
+ else:
102
+ grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1])
103
+ grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad(output1, grad_output)
104
+ grad_act_input = triton_dgrad_act(
105
+ grad_output, weight2, activation="squared_relu", act_input=act_input
106
+ )
107
+ grad_input, grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_backward(
108
+ x.reshape(batch_dim, n), weight1, grad_act_input
109
+ )
110
+ return grad_input.reshape_as(x), grad_weight1, grad_bias1, grad_weight2, grad_bias2, None
111
+
112
+
113
+ fused_dense_sqrelu_dense_function = FusedDenseSqreluDenseFunc.apply
114
+
115
+
116
+ class FusedDenseSqreluDense(nn.Module):
117
+ def __init__(
118
+ self,
119
+ in_features,
120
+ hidden_features=None,
121
+ out_features=None,
122
+ bias1=True,
123
+ bias2=True,
124
+ checkpoint_lvl=0,
125
+ device=None,
126
+ dtype=None,
127
+ ):
128
+ """
129
+ checkpoint_lvl (increasing lvl means slower but more memory saving):
130
+ 0: no recomputation in the bwd
131
+ 1: recompute gelu_out in the bwd
132
+ 2: recompute gelu_in and gelu_out in the bwd
133
+ """
134
+ assert checkpoint_lvl in [0, 1, 2]
135
+ factory_kwargs = {"device": device, "dtype": dtype}
136
+ super().__init__()
137
+ out_features = out_features or in_features
138
+ hidden_features = hidden_features or in_features * 4
139
+ assert bias1 == True, "DenseSqreluDense module without bias is currently not supported"
140
+ assert bias2 == True, "DenseSqreluDense module without bias is currently not supported"
141
+ self.checkpoint_lvl = checkpoint_lvl
142
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1, **factory_kwargs)
143
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs)
144
+
145
+ def forward(self, x):
146
+ assert x.is_cuda
147
+ return fused_dense_sqrelu_dense_function(
148
+ x, self.fc1.weight, self.fc1.bias, self.fc2.weight, self.fc2.bias, self.checkpoint_lvl
149
+ )
build/torch211-cxx11-cu128-aarch64-linux/ops/triton/rotary.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, Tri Dao.
2
+ # As of 2025-04-23, we require triton >= 3.0
3
+
4
+ from typing import Optional, Union
5
+
6
+ import torch
7
+
8
+ import triton
9
+ import triton.language as tl
10
+
11
+
12
+ @triton.jit
13
+ def rotary_kernel(
14
+ OUT, # Pointers to matrices
15
+ X,
16
+ COS,
17
+ SIN,
18
+ CU_SEQLENS,
19
+ SEQLEN_OFFSETS, # this could be int or a pointer
20
+ # Matrix dimensions
21
+ seqlen,
22
+ nheads,
23
+ seqlen_ro,
24
+ # strides
25
+ stride_out_batch,
26
+ stride_out_seqlen,
27
+ stride_out_nheads,
28
+ stride_out_headdim,
29
+ stride_x_batch,
30
+ stride_x_seqlen,
31
+ stride_x_nheads,
32
+ stride_x_headdim,
33
+ # Meta-parameters
34
+ # We want ROTARY_DIM to be constexpr, otherwise the triton compiler doesn't know that
35
+ # the mask is constant every 8 elements, and it will generate LDG.16 instead of LDG.128
36
+ ROTARY_DIM: tl.constexpr,
37
+ IS_SEQLEN_OFFSETS_TENSOR: tl.constexpr,
38
+ IS_VARLEN: tl.constexpr,
39
+ INTERLEAVED: tl.constexpr,
40
+ CONJUGATE: tl.constexpr,
41
+ BLOCK_H: tl.constexpr,
42
+ BLOCK_M: tl.constexpr,
43
+ ):
44
+ BLOCK_K: tl.constexpr = triton.next_power_of_2(ROTARY_DIM)
45
+ ROTARY_DIM_HALF = ROTARY_DIM // 2
46
+ pid_head = tl.program_id(axis=0)
47
+ pid_m = tl.program_id(axis=1)
48
+ pid_batch = tl.program_id(axis=2)
49
+
50
+ if not IS_VARLEN:
51
+ X = X + pid_batch * stride_x_batch
52
+ OUT = OUT + pid_batch * stride_out_batch
53
+ else:
54
+ start_idx = tl.load(CU_SEQLENS + pid_batch)
55
+ seqlen = tl.load(CU_SEQLENS + pid_batch + 1) - start_idx
56
+ X = X + start_idx * stride_x_seqlen
57
+ OUT = OUT + start_idx * stride_out_seqlen
58
+
59
+ if pid_m * BLOCK_M >= seqlen:
60
+ return
61
+
62
+ rh = pid_head * BLOCK_H + tl.arange(0, BLOCK_H)
63
+ rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
64
+ if not IS_SEQLEN_OFFSETS_TENSOR:
65
+ rm_cs = rm + SEQLEN_OFFSETS
66
+ else:
67
+ rm_cs = rm + tl.load(SEQLEN_OFFSETS + pid_batch)
68
+
69
+ rk_half = tl.arange(0, BLOCK_K // 2)
70
+ COS = COS + (rm_cs[:, None] * ROTARY_DIM_HALF + rk_half[None, :])
71
+ SIN = SIN + (rm_cs[:, None] * ROTARY_DIM_HALF + rk_half[None, :])
72
+ mask_cs = (rm_cs[:, None] < seqlen_ro) & (rk_half[None, :] < ROTARY_DIM_HALF)
73
+ cos = tl.load(COS, mask=mask_cs, other=1.0).to(tl.float32)
74
+ sin = tl.load(SIN, mask=mask_cs, other=0.0).to(tl.float32)
75
+ if CONJUGATE:
76
+ sin = -sin
77
+
78
+ if not INTERLEAVED:
79
+ # Load the 1st and 2nd halves of X, do calculation, then store to 1st and 2nd halves of OUT
80
+ X = X + (rh[:, None, None] * stride_x_nheads + rm[None, :, None] * stride_x_seqlen + rk_half[None, None, :] * stride_x_headdim)
81
+ OUT = OUT + (rh[:, None, None] * stride_out_nheads + rm[None, :, None] * stride_out_seqlen + rk_half[None, None, :] * stride_out_headdim)
82
+ mask = (rh[:, None, None] < nheads) & (rm[None, :, None] < seqlen) & (rk_half[None, None, :] < ROTARY_DIM_HALF)
83
+ x0 = tl.load(X, mask=mask, other=0.0).to(tl.float32)
84
+ x1 = tl.load(X + ROTARY_DIM_HALF * stride_x_headdim, mask=mask, other=0.0,).to(tl.float32)
85
+ o0 = x0 * cos - x1 * sin
86
+ o1 = x0 * sin + x1 * cos
87
+ tl.store(OUT, o0, mask=mask)
88
+ tl.store(OUT + ROTARY_DIM_HALF * stride_out_headdim, o1, mask=mask)
89
+ else:
90
+ rk = tl.arange(0, BLOCK_K)
91
+ X = X + (rh[:, None, None] * stride_x_nheads + rm[None, :, None] * stride_x_seqlen + rk[None, None, :] * stride_x_headdim)
92
+ OUT = OUT + (rh[:, None, None] * stride_out_nheads + rm[None, :, None] * stride_out_seqlen + rk[None, None, :] * stride_out_headdim)
93
+ mask = (rh[:, None, None] < nheads) & (rm[None, :, None] < seqlen) & (rk[None, None, :] < ROTARY_DIM)
94
+ x = tl.load(X, mask=mask, other=0.0).to(tl.float32)
95
+ x0, x1 = tl.split(tl.reshape(x, [BLOCK_H, BLOCK_M, BLOCK_K // 2, 2]))
96
+ o0 = x0 * cos - x1 * sin
97
+ o1 = x0 * sin + x1 * cos
98
+ o = tl.reshape(tl.join(o0, o1), [BLOCK_H, BLOCK_M, BLOCK_K])
99
+ tl.store(OUT, o, mask=mask)
100
+
101
+
102
+ def apply_rotary(
103
+ x: torch.Tensor,
104
+ cos: torch.Tensor,
105
+ sin: torch.Tensor,
106
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
107
+ cu_seqlens: Optional[torch.Tensor] = None,
108
+ max_seqlen: Optional[int] = None,
109
+ interleaved=False,
110
+ inplace=False,
111
+ conjugate=False,
112
+ ) -> torch.Tensor:
113
+ """
114
+ Arguments:
115
+ x: (batch, seqlen, nheads, headdim) if cu_seqlens is None
116
+ else (total_seqlen, nheads, headdim).
117
+ cos: (seqlen_ro, rotary_dim / 2)
118
+ sin: (seqlen_ro, rotary_dim / 2)
119
+ seqlen_offsets: integer or integer tensor of size (batch,)
120
+ cu_seqlens: (batch + 1,) or None
121
+ max_seqlen: int
122
+ Returns:
123
+ y: (batch, seqlen, nheads, headdim)
124
+ """
125
+ is_varlen = cu_seqlens is not None
126
+ if not is_varlen:
127
+ batch, seqlen, nheads, headdim = x.shape
128
+ else:
129
+ assert max_seqlen is not None, "If cu_seqlens is passed in, then max_seqlen must be passed"
130
+ total_seqlen, nheads, headdim = x.shape
131
+ batch_p_1 = cu_seqlens.shape[0]
132
+ batch = batch_p_1 - 1
133
+ seqlen = max_seqlen
134
+ seqlen_ro, rotary_dim = cos.shape
135
+ assert sin.shape == cos.shape
136
+ rotary_dim *= 2
137
+ assert rotary_dim <= headdim, "rotary_dim must be <= headdim"
138
+ assert headdim <= 256, "Only support headdim <= 256"
139
+ assert seqlen_ro >= seqlen, "seqlen_ro must be >= seqlen"
140
+
141
+ cos, sin = cos.contiguous(), sin.contiguous()
142
+ if isinstance(seqlen_offsets, torch.Tensor):
143
+ assert seqlen_offsets.shape == (batch,)
144
+ assert seqlen_offsets.dtype in [torch.int32, torch.int64]
145
+ seqlen_offsets = seqlen_offsets.contiguous()
146
+ else:
147
+ assert seqlen_offsets + seqlen <= seqlen_ro
148
+
149
+ output = torch.empty_like(x) if not inplace else x
150
+ if rotary_dim < headdim and not inplace:
151
+ output[..., rotary_dim:].copy_(x[..., rotary_dim:])
152
+
153
+ grid = lambda META: (triton.cdiv(nheads, META["BLOCK_H"]), triton.cdiv(seqlen, META["BLOCK_M"]), batch) # noqa
154
+ BLOCK_M = 8 if rotary_dim <= 128 else 4
155
+
156
+ # Need this, otherwise Triton tries to launch from cuda:0 and we get
157
+ # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?)
158
+ device_ctx = torch.cuda.device(x.device.index) if x.device.type == 'cuda' else torch.xpu.device(x.device.index)
159
+ with device_ctx:
160
+ torch.library.wrap_triton(rotary_kernel)[grid](
161
+ output, # data ptrs
162
+ x,
163
+ cos,
164
+ sin,
165
+ cu_seqlens,
166
+ seqlen_offsets,
167
+ seqlen, # shapes
168
+ nheads,
169
+ seqlen_ro,
170
+ output.stride(0) if not is_varlen else 0, # batch_strides if not varlen else 0
171
+ output.stride(-3), # seqlen_stride or total_seqlen_stride
172
+ output.stride(-2), # nheads_stride
173
+ output.stride(-1), # headdim_stride
174
+ x.stride(0) if not is_varlen else 0, # batch_strides if not varlen else 0
175
+ x.stride(-3), # seqlen stride or total_seqlen_stride
176
+ x.stride(-2), # nheads stride
177
+ x.stride(-1), # headdim stride
178
+ rotary_dim,
179
+ isinstance(seqlen_offsets, torch.Tensor),
180
+ is_varlen,
181
+ interleaved,
182
+ conjugate,
183
+ BLOCK_M=BLOCK_M,
184
+ BLOCK_H=2,
185
+ )
186
+ return output
build/torch211-cxx11-cu130-aarch64-linux/__init__.py CHANGED
@@ -1,7 +1,5 @@
1
- from typing import List, Optional
2
-
3
  import torch
4
-
5
  from ._ops import ops as flash_attn_ops
6
  from .flash_attn_interface import (
7
  flash_attn_func,
@@ -13,23 +11,6 @@ from .flash_attn_interface import (
13
  flash_attn_with_kvcache,
14
  )
15
 
16
- __all__ = [
17
- # High-level API (with autograd support)
18
- "flash_attn_func",
19
- "flash_attn_kvpacked_func",
20
- "flash_attn_qkvpacked_func",
21
- "flash_attn_varlen_func",
22
- "flash_attn_varlen_kvpacked_func",
23
- "flash_attn_varlen_qkvpacked_func",
24
- "flash_attn_with_kvcache",
25
- # Low-level ops (no autograd)
26
- "fwd",
27
- "varlen_fwd",
28
- "bwd",
29
- "varlen_bwd",
30
- "fwd_kvcache",
31
- ]
32
-
33
 
34
  def fwd(
35
  q: torch.Tensor,
 
1
+ from typing import Optional, List
 
2
  import torch
 
3
  from ._ops import ops as flash_attn_ops
4
  from .flash_attn_interface import (
5
  flash_attn_func,
 
11
  flash_attn_with_kvcache,
12
  )
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  def fwd(
16
  q: torch.Tensor,
build/torch211-cxx11-cu130-aarch64-linux/{_flash_attn2_cuda_a511a4c.abi3.so → _flash_attn2_cuda_f12afc9.abi3.so} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:57f5e30b7e9302ca917387738c7a1ae5547faec9a6ba7dfa99ee4b8c384f63fc
3
- size 1008651464
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a2e2580829f9caf390c941f16b60e4ca57b43838c4edebb254aa099371ecabdf
3
+ size 1006694184
build/torch211-cxx11-cu130-aarch64-linux/_ops.py CHANGED
@@ -1,9 +1,9 @@
1
  import torch
2
- from . import _flash_attn2_cuda_a511a4c
3
- ops = torch.ops._flash_attn2_cuda_a511a4c
4
 
5
  def add_op_namespace_prefix(op_name: str):
6
  """
7
  Prefix op by namespace.
8
  """
9
- return f"_flash_attn2_cuda_a511a4c::{op_name}"
 
1
  import torch
2
+ from . import _flash_attn2_cuda_f12afc9
3
+ ops = torch.ops._flash_attn2_cuda_f12afc9
4
 
5
  def add_op_namespace_prefix(op_name: str):
6
  """
7
  Prefix op by namespace.
8
  """
9
+ return f"_flash_attn2_cuda_f12afc9::{op_name}"
build/torch211-cxx11-cu130-aarch64-linux/flash_attn_interface.py CHANGED
@@ -15,12 +15,12 @@ import os
15
  # import flash_attn_2_cuda as flash_attn
16
 
17
 
 
18
  from ._ops import ops as flash_attn
19
  from ._ops import add_op_namespace_prefix
20
 
21
  # # isort: on
22
 
23
-
24
  def maybe_contiguous(x):
25
  return x.contiguous() if x is not None and x.stride(-1) != 1 else x
26
 
@@ -49,9 +49,7 @@ def _get_block_size_n(device, head_dim, is_dropout, is_causal):
49
 
50
  # This should match the block sizes in the CUDA kernel
51
  major, minor = torch.cuda.get_device_capability(device)
52
- is_sm8x = (
53
- major == 8 and minor > 0
54
- ) # Only include sm86 and sm89, exclude sm80 (A100)
55
  is_sm80 = major == 8 and minor == 0
56
  is_sm90 = major == 9 and minor == 0
57
  if head_dim <= 32:
@@ -77,11 +75,30 @@ def round_multiple(x, m):
77
  return (x + m - 1) // m * m
78
 
79
 
80
- @torch.library.custom_op(
81
- add_op_namespace_prefix("_flash_attn_forward"),
82
- mutates_args=(),
83
- device_types=_get_device(),
84
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  def _flash_attn_forward(
86
  q: torch.Tensor,
87
  k: torch.Tensor,
@@ -93,7 +110,7 @@ def _flash_attn_forward(
93
  window_size_right: int,
94
  softcap: float,
95
  alibi_slopes: Optional[torch.Tensor],
96
- return_softmax: bool,
97
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
98
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
99
  out, softmax_lse, S_dmask, rng_state = flash_attn.fwd(
@@ -114,7 +131,7 @@ def _flash_attn_forward(
114
  return out, softmax_lse, S_dmask, rng_state
115
 
116
 
117
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_forward"))
118
  def _flash_attn_forward_fake(
119
  q: torch.Tensor,
120
  k: torch.Tensor,
@@ -126,41 +143,28 @@ def _flash_attn_forward_fake(
126
  window_size_right: int,
127
  softcap: float,
128
  alibi_slopes: Optional[torch.Tensor],
129
- return_softmax: bool,
130
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
131
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
132
  batch_size, seqlen_q, num_heads, head_size = q.shape
133
  seqlen_k = k.shape[1]
134
  out = torch.empty_like(q)
135
- softmax_lse = torch.empty(
136
- (batch_size, num_heads, seqlen_q),
137
- dtype=torch.float32,
138
- device=q.device,
139
- layout=q.layout,
140
- )
141
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
142
  if return_softmax:
143
- p = torch.empty(
144
- (
145
- batch_size,
146
- num_heads,
147
- round_multiple(seqlen_q, 128),
148
- round_multiple(seqlen_k, 128),
149
- ),
150
- dtype=q.dtype,
151
- device=q.device,
152
- layout=q.layout,
153
- )
154
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
155
 
156
  return out, softmax_lse, p, rng_state
157
 
158
 
159
- @torch.library.custom_op(
160
- add_op_namespace_prefix("_flash_attn_varlen_forward"),
161
- mutates_args=(),
162
- device_types=_get_device(),
163
- )
 
 
164
  def _flash_attn_varlen_forward(
165
  q: torch.Tensor,
166
  k: torch.Tensor,
@@ -211,7 +215,7 @@ def _flash_attn_varlen_forward(
211
  return out, softmax_lse, S_dmask, rng_state
212
 
213
 
214
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_varlen_forward"))
215
  def _flash_attn_varlen_forward_fake(
216
  q: torch.Tensor,
217
  k: torch.Tensor,
@@ -237,30 +241,25 @@ def _flash_attn_varlen_forward_fake(
237
  paged_kv = block_table is not None
238
  batch_size = cu_seqlens_q.numel() - 1
239
  total_q, num_heads, _ = q.shape
240
-
241
  out = torch.empty_like(q)
242
- softmax_lse = torch.empty(
243
- (num_heads, total_q), dtype=torch.float32, device=q.device, layout=q.layout
244
- )
245
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
246
  seqlen_q_rounded = round_multiple(max_seqlen_q, 128)
247
  seqlen_k_rounded = round_multiple(max_seqlen_k, 128)
248
  if return_softmax:
249
- p = torch.empty(
250
- (batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded),
251
- dtype=q.dtype,
252
- device=q.device,
253
- layout=q.layout,
254
- )
255
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
256
  return out, softmax_lse, p, rng_state
257
 
258
 
259
- @torch.library.custom_op(
260
- add_op_namespace_prefix("_flash_attn_backward"),
261
- mutates_args=("dq", "dk", "dv"),
262
- device_types=_get_device(),
263
- )
 
 
264
  def _flash_attn_backward(
265
  dout: torch.Tensor,
266
  q: torch.Tensor,
@@ -312,7 +311,7 @@ def _flash_attn_backward(
312
  return softmax_d
313
 
314
 
315
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_backward"))
316
  def _flash_attn_backward_fake(
317
  dout: torch.Tensor,
318
  q: torch.Tensor,
@@ -341,20 +340,18 @@ def _flash_attn_backward_fake(
341
  if dv is None:
342
  dv = torch.empty_like(v)
343
  batch_size, seqlen_q, num_heads, _ = q.shape
344
- softmax_d = torch.empty(
345
- (batch_size, num_heads, round_multiple(seqlen_q, 128)),
346
- device=q.device,
347
- dtype=torch.float32,
348
- )
349
-
350
  return softmax_d
351
 
352
 
353
- @torch.library.custom_op(
354
- add_op_namespace_prefix("_flash_attn_varlen_backward"),
355
- mutates_args=("dq", "dk", "dv"),
356
- device_types=_get_device(),
357
- )
 
 
358
  def _flash_attn_varlen_backward(
359
  dout: torch.Tensor,
360
  q: torch.Tensor,
@@ -418,7 +415,7 @@ def _flash_attn_varlen_backward(
418
  return softmax_d
419
 
420
 
421
- @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_varlen_backward"))
422
  def _flash_attn_varlen_backward_fake(
423
  dout: torch.Tensor,
424
  q: torch.Tensor,
@@ -454,13 +451,17 @@ def _flash_attn_varlen_backward_fake(
454
  dk = torch.empty_like(k)
455
  if dv is None:
456
  dv = torch.empty_like(v)
457
- softmax_d = torch.empty(
458
- (num_heads, total_q + 128 * batch_size), device=q.device, dtype=torch.float32
459
- )
460
-
461
  return softmax_d
462
 
463
 
 
 
 
 
 
 
464
  class FlashAttnQKVPackedFunc(torch.autograd.Function):
465
  @staticmethod
466
  def forward(
@@ -485,7 +486,7 @@ class FlashAttnQKVPackedFunc(torch.autograd.Function):
485
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
486
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
487
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
488
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_forward(
489
  q,
490
  k,
491
  v,
@@ -519,7 +520,7 @@ class FlashAttnQKVPackedFunc(torch.autograd.Function):
519
  dout_padded = dout
520
  if head_size_og % 8 != 0:
521
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
522
- _flash_attn_backward(
523
  dout_padded,
524
  q,
525
  k,
@@ -569,7 +570,7 @@ class FlashAttnVarlenQKVPackedFunc(torch.autograd.Function):
569
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
570
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
571
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
572
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_varlen_forward(
573
  q,
574
  k,
575
  v,
@@ -588,9 +589,7 @@ class FlashAttnVarlenQKVPackedFunc(torch.autograd.Function):
588
  block_table=None,
589
  )
590
  if is_grad:
591
- ctx.save_for_backward(
592
- q, k, v, out_padded, softmax_lse, cu_seqlens, rng_state
593
- )
594
  ctx.dropout_p = dropout_p
595
  ctx.max_seqlen = max_seqlen
596
  ctx.softmax_scale = softmax_scale
@@ -611,7 +610,7 @@ class FlashAttnVarlenQKVPackedFunc(torch.autograd.Function):
611
  dout_padded = dout
612
  if head_size_og % 8 != 0:
613
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
614
- _flash_attn_varlen_backward(
615
  dout_padded,
616
  q,
617
  k,
@@ -655,7 +654,9 @@ class FlashAttnKVPackedFunc(torch.autograd.Function):
655
  return_softmax,
656
  is_grad_enabled,
657
  ):
658
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, kv])
 
 
659
  if softmax_scale is None:
660
  softmax_scale = q.shape[-1] ** (-0.5)
661
  k, v = kv[:, :, 0].detach(), kv[:, :, 1].detach()
@@ -664,7 +665,7 @@ class FlashAttnKVPackedFunc(torch.autograd.Function):
664
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
665
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
666
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
667
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_forward(
668
  q,
669
  k,
670
  v,
@@ -699,7 +700,7 @@ class FlashAttnKVPackedFunc(torch.autograd.Function):
699
  dout_padded = dout
700
  if head_size_og % 8 != 0:
701
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
702
- _flash_attn_backward(
703
  dout_padded,
704
  q,
705
  k,
@@ -744,7 +745,9 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
744
  return_softmax,
745
  is_grad_enabled,
746
  ):
747
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, kv])
 
 
748
  if softmax_scale is None:
749
  softmax_scale = q.shape[-1] ** (-0.5)
750
  k, v = kv[:, 0].detach(), kv[:, 1].detach()
@@ -753,7 +756,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
753
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
754
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
755
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
756
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_varlen_forward(
757
  q,
758
  k,
759
  v,
@@ -789,9 +792,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
789
 
790
  @staticmethod
791
  def backward(ctx, dout, *args):
792
- q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = (
793
- ctx.saved_tensors
794
- )
795
  dq = torch.empty_like(q)
796
  kv_shape = k.shape[:-2] + (2, *k.shape[-2:])
797
  dkv = torch.empty(kv_shape, dtype=k.dtype, device=k.device)
@@ -799,7 +800,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
799
  dout_padded = dout
800
  if head_size_og % 8 != 0:
801
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
802
- _flash_attn_varlen_backward(
803
  dout_padded,
804
  q,
805
  k,
@@ -825,23 +826,7 @@ class FlashAttnVarlenKVPackedFunc(torch.autograd.Function):
825
  )
826
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
827
  dkv = dkv[..., : dout.shape[-1]]
828
- return (
829
- dq,
830
- dkv,
831
- None,
832
- None,
833
- None,
834
- None,
835
- None,
836
- None,
837
- None,
838
- None,
839
- None,
840
- None,
841
- None,
842
- None,
843
- None,
844
- )
845
 
846
 
847
  class FlashAttnFunc(torch.autograd.Function):
@@ -861,7 +846,9 @@ class FlashAttnFunc(torch.autograd.Function):
861
  return_softmax,
862
  is_grad_enabled,
863
  ):
864
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, k, v])
 
 
865
  if softmax_scale is None:
866
  softmax_scale = q.shape[-1] ** (-0.5)
867
  head_size_og = q.size(3)
@@ -869,7 +856,7 @@ class FlashAttnFunc(torch.autograd.Function):
869
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
870
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
871
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
872
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_forward(
873
  q,
874
  k,
875
  v,
@@ -902,7 +889,7 @@ class FlashAttnFunc(torch.autograd.Function):
902
  dout_padded = dout
903
  if head_size_og % 8 != 0:
904
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
905
- _flash_attn_backward(
906
  dout_padded,
907
  q,
908
  k,
@@ -950,7 +937,9 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
950
  block_table,
951
  is_grad_enabled,
952
  ):
953
- is_grad = is_grad_enabled and any(x.requires_grad for x in [q, k, v])
 
 
954
  if softmax_scale is None:
955
  softmax_scale = q.shape[-1] ** (-0.5)
956
  head_size_og = q.size(2)
@@ -958,7 +947,7 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
958
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
959
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
960
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
961
- out_padded, softmax_lse, S_dmask, rng_state = _flash_attn_varlen_forward(
962
  q,
963
  k,
964
  v,
@@ -995,15 +984,13 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
995
 
996
  @staticmethod
997
  def backward(ctx, dout, *args):
998
- q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = (
999
- ctx.saved_tensors
1000
- )
1001
  dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
1002
  head_size_og = dout.size(2)
1003
  dout_padded = dout
1004
  if head_size_og % 8 != 0:
1005
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
1006
- _flash_attn_varlen_backward(
1007
  dout_padded,
1008
  q,
1009
  k,
@@ -1030,25 +1017,7 @@ class FlashAttnVarlenFunc(torch.autograd.Function):
1030
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
1031
  dk = dk[..., : dout.shape[-1]]
1032
  dv = dv[..., : dout.shape[-1]]
1033
- return (
1034
- dq,
1035
- dk,
1036
- dv,
1037
- None,
1038
- None,
1039
- None,
1040
- None,
1041
- None,
1042
- None,
1043
- None,
1044
- None,
1045
- None,
1046
- None,
1047
- None,
1048
- None,
1049
- None,
1050
- None,
1051
- )
1052
 
1053
 
1054
  def flash_attn_qkvpacked_func(
@@ -1196,7 +1165,7 @@ def flash_attn_func(
1196
  softmax_scale=None,
1197
  causal=False,
1198
  window_size=(-1, -1), # -1 means infinite context window
1199
- softcap=0.0, # 0.0 means deactivated
1200
  alibi_slopes=None,
1201
  deterministic=False,
1202
  return_attn_probs=False,
@@ -1273,7 +1242,7 @@ def flash_attn_varlen_qkvpacked_func(
1273
  softmax_scale=None,
1274
  causal=False,
1275
  window_size=(-1, -1), # -1 means infinite context window
1276
- softcap=0.0, # 0.0 means deactivated
1277
  alibi_slopes=None,
1278
  deterministic=False,
1279
  return_attn_probs=False,
@@ -1342,7 +1311,7 @@ def flash_attn_varlen_kvpacked_func(
1342
  softmax_scale=None,
1343
  causal=False,
1344
  window_size=(-1, -1), # -1 means infinite context window
1345
- softcap=0.0, # 0.0 means deactivated
1346
  alibi_slopes=None,
1347
  deterministic=False,
1348
  return_attn_probs=False,
@@ -1435,7 +1404,7 @@ def flash_attn_varlen_func(
1435
  softmax_scale=None,
1436
  causal=False,
1437
  window_size=(-1, -1), # -1 means infinite context window
1438
- softcap=0.0, # 0.0 means deactivated
1439
  alibi_slopes=None,
1440
  deterministic=False,
1441
  return_attn_probs=False,
@@ -1532,7 +1501,7 @@ def flash_attn_with_kvcache(
1532
  softmax_scale=None,
1533
  causal=False,
1534
  window_size=(-1, -1), # -1 means infinite context window
1535
- softcap=0.0, # 0.0 means deactivated
1536
  rotary_interleaved=True,
1537
  alibi_slopes=None,
1538
  num_splits=0,
 
15
  # import flash_attn_2_cuda as flash_attn
16
 
17
 
18
+ from . import _ops
19
  from ._ops import ops as flash_attn
20
  from ._ops import add_op_namespace_prefix
21
 
22
  # # isort: on
23
 
 
24
  def maybe_contiguous(x):
25
  return x.contiguous() if x is not None and x.stride(-1) != 1 else x
26
 
 
49
 
50
  # This should match the block sizes in the CUDA kernel
51
  major, minor = torch.cuda.get_device_capability(device)
52
+ is_sm8x = major == 8 and minor > 0 # Only include sm86 and sm89, exclude sm80 (A100)
 
 
53
  is_sm80 = major == 8 and minor == 0
54
  is_sm90 = major == 9 and minor == 0
55
  if head_dim <= 32:
 
75
  return (x + m - 1) // m * m
76
 
77
 
78
+ # torch.compile() support is only enabled for pytorch >= 2.4
79
+ # The reason for this is that we are using the new custom_op and register_fake
80
+ # APIs, which support inplace modification of inputs in the function itself
81
+ if torch.__version__ >= "2.4.0":
82
+ _torch_custom_op_wrapper = torch.library.custom_op
83
+ _torch_register_fake_wrapper = torch.library.register_fake
84
+ else:
85
+ def noop_custom_op_wrapper(name, fn=None, /, *, mutates_args, device_types=None, schema=None):
86
+ def wrap(func):
87
+ return func
88
+ if fn is None:
89
+ return wrap
90
+ return fn
91
+ def noop_register_fake_wrapper(op, fn=None, /, *, lib=None, _stacklevel=1):
92
+ def wrap(func):
93
+ return func
94
+ if fn is None:
95
+ return wrap
96
+ return fn
97
+ _torch_custom_op_wrapper = noop_custom_op_wrapper
98
+ _torch_register_fake_wrapper = noop_register_fake_wrapper
99
+
100
+
101
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_forward"), mutates_args=(), device_types=_get_device())
102
  def _flash_attn_forward(
103
  q: torch.Tensor,
104
  k: torch.Tensor,
 
110
  window_size_right: int,
111
  softcap: float,
112
  alibi_slopes: Optional[torch.Tensor],
113
+ return_softmax: bool
114
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
115
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
116
  out, softmax_lse, S_dmask, rng_state = flash_attn.fwd(
 
131
  return out, softmax_lse, S_dmask, rng_state
132
 
133
 
134
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_forward"))
135
  def _flash_attn_forward_fake(
136
  q: torch.Tensor,
137
  k: torch.Tensor,
 
143
  window_size_right: int,
144
  softcap: float,
145
  alibi_slopes: Optional[torch.Tensor],
146
+ return_softmax: bool
147
  ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
148
  q, k, v = [maybe_contiguous(x) for x in (q, k, v)]
149
  batch_size, seqlen_q, num_heads, head_size = q.shape
150
  seqlen_k = k.shape[1]
151
  out = torch.empty_like(q)
152
+ softmax_lse = torch.empty((batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device, layout=q.layout)
 
 
 
 
 
153
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
154
  if return_softmax:
155
+ p = torch.empty((batch_size, num_heads, round_multiple(seqlen_q, 128), round_multiple(seqlen_k, 128)), dtype=q.dtype, device=q.device, layout=q.layout)
 
 
 
 
 
 
 
 
 
 
156
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
157
 
158
  return out, softmax_lse, p, rng_state
159
 
160
 
161
+ if torch.__version__ >= "2.4.0":
162
+ _wrapped_flash_attn_forward = _ops.ops._flash_attn_forward
163
+ else:
164
+ _wrapped_flash_attn_forward = _flash_attn_forward
165
+
166
+
167
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_varlen_forward"), mutates_args=(), device_types=_get_device())
168
  def _flash_attn_varlen_forward(
169
  q: torch.Tensor,
170
  k: torch.Tensor,
 
215
  return out, softmax_lse, S_dmask, rng_state
216
 
217
 
218
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_varlen_forward"))
219
  def _flash_attn_varlen_forward_fake(
220
  q: torch.Tensor,
221
  k: torch.Tensor,
 
241
  paged_kv = block_table is not None
242
  batch_size = cu_seqlens_q.numel() - 1
243
  total_q, num_heads, _ = q.shape
244
+
245
  out = torch.empty_like(q)
246
+ softmax_lse = torch.empty((num_heads, total_q), dtype=torch.float32, device=q.device, layout=q.layout)
 
 
247
  p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout)
248
  seqlen_q_rounded = round_multiple(max_seqlen_q, 128)
249
  seqlen_k_rounded = round_multiple(max_seqlen_k, 128)
250
  if return_softmax:
251
+ p = torch.empty((batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded), dtype=q.dtype, device=q.device, layout=q.layout)
 
 
 
 
 
252
  rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)
253
  return out, softmax_lse, p, rng_state
254
 
255
 
256
+ if torch.__version__ >= "2.4.0":
257
+ _wrapped_flash_attn_varlen_forward = _ops.ops._flash_attn_varlen_forward
258
+ else:
259
+ _wrapped_flash_attn_varlen_forward = _flash_attn_varlen_forward
260
+
261
+
262
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_backward"), mutates_args=("dq", "dk", "dv"), device_types=_get_device())
263
  def _flash_attn_backward(
264
  dout: torch.Tensor,
265
  q: torch.Tensor,
 
311
  return softmax_d
312
 
313
 
314
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_backward"))
315
  def _flash_attn_backward_fake(
316
  dout: torch.Tensor,
317
  q: torch.Tensor,
 
340
  if dv is None:
341
  dv = torch.empty_like(v)
342
  batch_size, seqlen_q, num_heads, _ = q.shape
343
+ softmax_d = torch.empty((batch_size, num_heads, round_multiple(seqlen_q, 128)), device=q.device, dtype=torch.float32)
344
+
 
 
 
 
345
  return softmax_d
346
 
347
 
348
+ if torch.__version__ >= "2.4.0":
349
+ _wrapped_flash_attn_backward = _ops.ops._flash_attn_backward
350
+ else:
351
+ _wrapped_flash_attn_backward = _flash_attn_backward
352
+
353
+
354
+ @_torch_custom_op_wrapper(add_op_namespace_prefix("_flash_attn_varlen_backward"), mutates_args=("dq", "dk", "dv"), device_types=_get_device())
355
  def _flash_attn_varlen_backward(
356
  dout: torch.Tensor,
357
  q: torch.Tensor,
 
415
  return softmax_d
416
 
417
 
418
+ @_torch_register_fake_wrapper(add_op_namespace_prefix("_flash_attn_varlen_backward"))
419
  def _flash_attn_varlen_backward_fake(
420
  dout: torch.Tensor,
421
  q: torch.Tensor,
 
451
  dk = torch.empty_like(k)
452
  if dv is None:
453
  dv = torch.empty_like(v)
454
+ softmax_d = torch.empty((num_heads, total_q + 128 * batch_size), device=q.device, dtype=torch.float32)
455
+
 
 
456
  return softmax_d
457
 
458
 
459
+ if torch.__version__ >= "2.4.0":
460
+ _wrapped_flash_attn_varlen_backward = _ops.ops._flash_attn_varlen_backward
461
+ else:
462
+ _wrapped_flash_attn_varlen_backward = _flash_attn_varlen_backward
463
+
464
+
465
  class FlashAttnQKVPackedFunc(torch.autograd.Function):
466
  @staticmethod
467
  def forward(
 
486
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
487
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
488
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
489
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward(
490
  q,
491
  k,
492
  v,
 
520
  dout_padded = dout
521
  if head_size_og % 8 != 0:
522
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
523
+ _wrapped_flash_attn_backward(
524
  dout_padded,
525
  q,
526
  k,
 
570
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
571
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
572
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
573
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward(
574
  q,
575
  k,
576
  v,
 
589
  block_table=None,
590
  )
591
  if is_grad:
592
+ ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens, rng_state)
 
 
593
  ctx.dropout_p = dropout_p
594
  ctx.max_seqlen = max_seqlen
595
  ctx.softmax_scale = softmax_scale
 
610
  dout_padded = dout
611
  if head_size_og % 8 != 0:
612
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
613
+ _wrapped_flash_attn_varlen_backward(
614
  dout_padded,
615
  q,
616
  k,
 
654
  return_softmax,
655
  is_grad_enabled,
656
  ):
657
+ is_grad = is_grad_enabled and any(
658
+ x.requires_grad for x in [q, kv]
659
+ )
660
  if softmax_scale is None:
661
  softmax_scale = q.shape[-1] ** (-0.5)
662
  k, v = kv[:, :, 0].detach(), kv[:, :, 1].detach()
 
665
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
666
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
667
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
668
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward(
669
  q,
670
  k,
671
  v,
 
700
  dout_padded = dout
701
  if head_size_og % 8 != 0:
702
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
703
+ _wrapped_flash_attn_backward(
704
  dout_padded,
705
  q,
706
  k,
 
745
  return_softmax,
746
  is_grad_enabled,
747
  ):
748
+ is_grad = is_grad_enabled and any(
749
+ x.requires_grad for x in [q, kv]
750
+ )
751
  if softmax_scale is None:
752
  softmax_scale = q.shape[-1] ** (-0.5)
753
  k, v = kv[:, 0].detach(), kv[:, 1].detach()
 
756
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
757
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
758
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
759
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward(
760
  q,
761
  k,
762
  v,
 
792
 
793
  @staticmethod
794
  def backward(ctx, dout, *args):
795
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors
 
 
796
  dq = torch.empty_like(q)
797
  kv_shape = k.shape[:-2] + (2, *k.shape[-2:])
798
  dkv = torch.empty(kv_shape, dtype=k.dtype, device=k.device)
 
800
  dout_padded = dout
801
  if head_size_og % 8 != 0:
802
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
803
+ _wrapped_flash_attn_varlen_backward(
804
  dout_padded,
805
  q,
806
  k,
 
826
  )
827
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
828
  dkv = dkv[..., : dout.shape[-1]]
829
+ return dq, dkv, None, None, None, None, None, None, None, None, None, None, None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
830
 
831
 
832
  class FlashAttnFunc(torch.autograd.Function):
 
846
  return_softmax,
847
  is_grad_enabled,
848
  ):
849
+ is_grad = is_grad_enabled and any(
850
+ x.requires_grad for x in [q, k, v]
851
+ )
852
  if softmax_scale is None:
853
  softmax_scale = q.shape[-1] ** (-0.5)
854
  head_size_og = q.size(3)
 
856
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
857
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
858
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
859
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward(
860
  q,
861
  k,
862
  v,
 
889
  dout_padded = dout
890
  if head_size_og % 8 != 0:
891
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
892
+ _wrapped_flash_attn_backward(
893
  dout_padded,
894
  q,
895
  k,
 
937
  block_table,
938
  is_grad_enabled,
939
  ):
940
+ is_grad = is_grad_enabled and any(
941
+ x.requires_grad for x in [q, k, v]
942
+ )
943
  if softmax_scale is None:
944
  softmax_scale = q.shape[-1] ** (-0.5)
945
  head_size_og = q.size(2)
 
947
  q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8])
948
  k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8])
949
  v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8])
950
+ out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward(
951
  q,
952
  k,
953
  v,
 
984
 
985
  @staticmethod
986
  def backward(ctx, dout, *args):
987
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors
 
 
988
  dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
989
  head_size_og = dout.size(2)
990
  dout_padded = dout
991
  if head_size_og % 8 != 0:
992
  dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8])
993
+ _wrapped_flash_attn_varlen_backward(
994
  dout_padded,
995
  q,
996
  k,
 
1017
  dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension
1018
  dk = dk[..., : dout.shape[-1]]
1019
  dv = dv[..., : dout.shape[-1]]
1020
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1021
 
1022
 
1023
  def flash_attn_qkvpacked_func(
 
1165
  softmax_scale=None,
1166
  causal=False,
1167
  window_size=(-1, -1), # -1 means infinite context window
1168
+ softcap=0.0, # 0.0 means deactivated
1169
  alibi_slopes=None,
1170
  deterministic=False,
1171
  return_attn_probs=False,
 
1242
  softmax_scale=None,
1243
  causal=False,
1244
  window_size=(-1, -1), # -1 means infinite context window
1245
+ softcap=0.0, # 0.0 means deactivated
1246
  alibi_slopes=None,
1247
  deterministic=False,
1248
  return_attn_probs=False,
 
1311
  softmax_scale=None,
1312
  causal=False,
1313
  window_size=(-1, -1), # -1 means infinite context window
1314
+ softcap=0.0, # 0.0 means deactivated
1315
  alibi_slopes=None,
1316
  deterministic=False,
1317
  return_attn_probs=False,
 
1404
  softmax_scale=None,
1405
  causal=False,
1406
  window_size=(-1, -1), # -1 means infinite context window
1407
+ softcap=0.0, # 0.0 means deactivated
1408
  alibi_slopes=None,
1409
  deterministic=False,
1410
  return_attn_probs=False,
 
1501
  softmax_scale=None,
1502
  causal=False,
1503
  window_size=(-1, -1), # -1 means infinite context window
1504
+ softcap=0.0, # 0.0 means deactivated
1505
  rotary_interleaved=True,
1506
  alibi_slopes=None,
1507
  num_splits=0,
build/torch211-cxx11-cu130-aarch64-linux/layers/__init__.py ADDED
File without changes
build/torch211-cxx11-cu130-aarch64-linux/layers/patch_embed.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # We use the same API as https://github.com/rwightman/pytorch-image-models/blob/v0.6.11/timm/models/layers/patch_embed.py
2
+ # But we use nn.Linear instead of Conv2d and it's about 8x faster.
3
+
4
+ from functools import partial
5
+
6
+ import torch.nn as nn
7
+ from einops import rearrange
8
+ from torch import _assert
9
+ from torch.nn.modules.utils import _pair
10
+
11
+ try:
12
+ from flash_attn.ops.fused_dense import FusedDense
13
+ except ImportError:
14
+ FusedDense = None
15
+
16
+
17
+ class PatchEmbed(nn.Module):
18
+ """2D Image to Patch Embedding"""
19
+
20
+ def __init__(
21
+ self,
22
+ img_size=224,
23
+ patch_size=16,
24
+ in_chans=3,
25
+ embed_dim=768,
26
+ norm_layer=None,
27
+ flatten=True,
28
+ bias=True,
29
+ fused_bias_fc=False,
30
+ ):
31
+ super().__init__()
32
+ img_size = _pair(img_size)
33
+ patch_size = _pair(patch_size)
34
+ self.img_size = img_size
35
+ self.patch_size = patch_size
36
+ self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
37
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
38
+ self.flatten = flatten
39
+ if fused_bias_fc and FusedDense is None:
40
+ raise ImportError("fused_dense is not installed")
41
+
42
+ linear_cls = nn.Linear if not fused_bias_fc or not bias else FusedDense
43
+ self.proj = linear_cls(in_chans * patch_size[0] * patch_size[1], embed_dim, bias=bias)
44
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
45
+
46
+ def forward(self, x):
47
+ _, _, H, W = x.shape
48
+ _assert(
49
+ H == self.img_size[0],
50
+ f"Input image height ({H}) doesn't match model ({self.img_size[0]}).",
51
+ )
52
+ _assert(
53
+ W == self.img_size[1],
54
+ f"Input image width ({W}) doesn't match model ({self.img_size[1]}).",
55
+ )
56
+ x = self.proj(
57
+ rearrange(
58
+ x,
59
+ "b c (h p1) (w p2) -> b h w (c p1 p2)",
60
+ p1=self.patch_size[0],
61
+ p2=self.patch_size[1],
62
+ )
63
+ )
64
+ if self.flatten:
65
+ x = rearrange(x, "b h w c -> b (h w) c")
66
+ x = self.norm(x)
67
+ return x
build/torch211-cxx11-cu130-aarch64-linux/layers/rotary.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, Tri Dao
2
+
3
+ import math
4
+ from functools import partial
5
+ from typing import Optional, Tuple, Union
6
+
7
+ import torch
8
+ from torch import Tensor
9
+
10
+ from einops import rearrange, repeat
11
+ # from flash_attn.ops.triton.rotary import apply_rotary
12
+ from ..ops.triton.rotary import apply_rotary
13
+
14
+
15
+ def rotate_half(x, interleaved=False):
16
+ if not interleaved:
17
+ x1, x2 = x.chunk(2, dim=-1)
18
+ return torch.cat((-x2, x1), dim=-1)
19
+ else:
20
+ x1, x2 = x[..., ::2], x[..., 1::2]
21
+ return rearrange(torch.stack((-x2, x1), dim=-1), "... d two -> ... (d two)", two=2)
22
+
23
+
24
+ def apply_rotary_emb_torch(x, cos, sin, interleaved=False):
25
+ """
26
+ x: (batch_size, seqlen, nheads, headdim)
27
+ cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2)
28
+ """
29
+ ro_dim = cos.shape[-1] * 2
30
+ assert ro_dim <= x.shape[-1]
31
+ cos = repeat(cos, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
32
+ sin = repeat(sin, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)")
33
+ return torch.cat(
34
+ [x[..., :ro_dim] * cos + rotate_half(x[..., :ro_dim], interleaved) * sin, x[..., ro_dim:]],
35
+ dim=-1,
36
+ )
37
+
38
+
39
+ class ApplyRotaryEmb(torch.autograd.Function):
40
+ @staticmethod
41
+ def forward(
42
+ ctx,
43
+ x,
44
+ cos,
45
+ sin,
46
+ interleaved=False,
47
+ inplace=False,
48
+ seqlen_offsets: Union[int, Tensor] = 0,
49
+ cu_seqlens: Optional[Tensor] = None,
50
+ max_seqlen: Optional[int] = None,
51
+ ):
52
+ out = apply_rotary(
53
+ x,
54
+ cos,
55
+ sin,
56
+ seqlen_offsets=seqlen_offsets,
57
+ cu_seqlens=cu_seqlens,
58
+ max_seqlen=max_seqlen,
59
+ interleaved=interleaved,
60
+ inplace=inplace,
61
+ )
62
+ if isinstance(seqlen_offsets, int):
63
+ ctx.save_for_backward(cos, sin, cu_seqlens) # Can't save int with save_for_backward
64
+ ctx.seqlen_offsets = seqlen_offsets
65
+ else:
66
+ ctx.save_for_backward(cos, sin, cu_seqlens, seqlen_offsets)
67
+ ctx.seqlen_offsets = None
68
+ ctx.interleaved = interleaved
69
+ ctx.inplace = inplace
70
+ ctx.max_seqlen = max_seqlen
71
+ return out if not inplace else x
72
+
73
+ @staticmethod
74
+ def backward(ctx, do):
75
+ seqlen_offsets = ctx.seqlen_offsets
76
+ if seqlen_offsets is None:
77
+ cos, sin, cu_seqlens, seqlen_offsets = ctx.saved_tensors
78
+ else:
79
+ cos, sin, cu_seqlens = ctx.saved_tensors
80
+ dx = apply_rotary(
81
+ do,
82
+ cos,
83
+ sin,
84
+ seqlen_offsets=seqlen_offsets,
85
+ cu_seqlens=cu_seqlens,
86
+ max_seqlen=ctx.max_seqlen,
87
+ interleaved=ctx.interleaved,
88
+ inplace=ctx.inplace,
89
+ conjugate=True,
90
+ )
91
+ return dx, None, None, None, None, None, None, None
92
+
93
+
94
+ def apply_rotary_emb(
95
+ x,
96
+ cos,
97
+ sin,
98
+ interleaved=False,
99
+ inplace=False,
100
+ seqlen_offsets: Union[int, Tensor] = 0,
101
+ cu_seqlens: Optional[Tensor] = None,
102
+ max_seqlen: Optional[int] = None,
103
+ ):
104
+ """
105
+ Arguments:
106
+ x: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None
107
+ else (total_seqlen, nheads, headdim)
108
+ cos, sin: (seqlen_rotary, rotary_dim / 2)
109
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
110
+ of 1st half and 2nd half (GPT-NeoX style).
111
+ inplace: if True, apply rotary embedding in-place.
112
+ seqlen_offsets: (batch_size,) or int. Each sequence in x is shifted by this amount.
113
+ Most commonly used in inference when we have KV cache.
114
+ cu_seqlens: (batch + 1,) or None
115
+ max_seqlen: int
116
+ Return:
117
+ out: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None
118
+ else (total_seqlen, nheads, headdim)
119
+ rotary_dim must be <= headdim
120
+ Apply rotary embedding to the first rotary_dim of x.
121
+ """
122
+ return ApplyRotaryEmb.apply(
123
+ x, cos, sin, interleaved, inplace, seqlen_offsets, cu_seqlens, max_seqlen
124
+ )
125
+
126
+
127
+ # For backward compatibility
128
+ apply_rotary_emb_func = apply_rotary_emb
129
+
130
+
131
+ def _apply_rotary_emb_qkv(
132
+ qkv,
133
+ cos,
134
+ sin,
135
+ cos_k=None,
136
+ sin_k=None,
137
+ interleaved=False,
138
+ inplace=False,
139
+ conjugate=False,
140
+ seqlen_offsets: Union[int, Tensor] = 0,
141
+ num_heads_q: Optional[int] = None,
142
+ ):
143
+ apply_rotary_fn = partial(
144
+ apply_rotary,
145
+ interleaved=interleaved,
146
+ inplace=inplace,
147
+ conjugate=conjugate,
148
+ seqlen_offsets=seqlen_offsets
149
+ )
150
+ if cos_k is None and sin_k is None and qkv.is_contiguous():
151
+ # Call 1 kernel instead of 2 kernels
152
+ # We need qkv to be contiguous so that when we reshape to combine (3, nheads)
153
+ # dimensions, we get the same tensor
154
+ if qkv.dim() == 5:
155
+ batch, seqlen, three, nheads, headdim = qkv.shape
156
+ assert three == 3
157
+ # qk = rearrange(qkv[:, :, :2], "b s t h d -> b s (t h) d")
158
+ qk = qkv[:, :, :2].reshape(batch, seqlen, -1, headdim)
159
+ qk = apply_rotary_fn(qk, cos, sin)
160
+ else:
161
+ assert qkv.dim() == 4
162
+ assert num_heads_q is not None
163
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
164
+ assert qkv.shape[2] == num_heads_q + 2 * num_heads_k
165
+ qk = qkv[:, :, :num_heads_q + num_heads_k]
166
+ qk = apply_rotary_fn(qk, cos, sin)
167
+ if not inplace:
168
+ if qkv.dim() == 5:
169
+ qkv = torch.cat([rearrange(qk, "b s (t h) d -> b s t h d", t=2), qkv[:, :, 2:]], dim=2)
170
+ else:
171
+ qkv = torch.cat([qk, qkv[:, :, num_heads_q + num_heads_k :]], dim=2)
172
+ else:
173
+ cos_k = cos if cos_k is None else cos_k
174
+ sin_k = sin if sin_k is None else sin_k
175
+ if qkv.dim() == 5:
176
+ batch, seqlen, three, nheads, headdim = qkv.shape
177
+ assert three == 3
178
+ q, k = qkv[:, :, 0], qkv[:, :, 1]
179
+ else:
180
+ assert qkv.dim() == 4
181
+ assert num_heads_q is not None
182
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
183
+ assert qkv.shape[2] == num_heads_q + 2 * num_heads_k
184
+ q, k = qkv[:, :, :num_heads_q], qkv[:, :, num_heads_q : num_heads_q + num_heads_k]
185
+ q = apply_rotary_fn(q, cos, sin)
186
+ k = apply_rotary_fn(k, cos_k, sin_k)
187
+ if not inplace:
188
+ if qkv.dim() == 5:
189
+ qkv = torch.stack([q, k, qkv[:, :, 2]], dim=2)
190
+ else:
191
+ qkv = torch.cat([q, k, qkv[:, :, num_heads_q + num_heads_k:]], dim=2)
192
+ return qkv
193
+
194
+
195
+ class ApplyRotaryEmbQKV_(torch.autograd.Function):
196
+ @staticmethod
197
+ def forward(
198
+ ctx,
199
+ qkv,
200
+ cos,
201
+ sin,
202
+ cos_k=None,
203
+ sin_k=None,
204
+ interleaved=False,
205
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
206
+ num_heads_q: Optional[int] = None,
207
+ ):
208
+ # apply_rotary_emb_qkv_inplace(
209
+ qkv = _apply_rotary_emb_qkv(
210
+ qkv, cos, sin, cos_k, sin_k, interleaved=interleaved, inplace=True,
211
+ seqlen_offsets=seqlen_offsets, num_heads_q=num_heads_q,
212
+ )
213
+ if isinstance(seqlen_offsets, int):
214
+ ctx.save_for_backward(cos, sin, cos_k, sin_k)
215
+ ctx.seqlen_offsets = seqlen_offsets
216
+ else:
217
+ ctx.save_for_backward(cos, sin, cos_k, sin_k, seqlen_offsets)
218
+ ctx.seqlen_offsets = None
219
+ ctx.interleaved = interleaved
220
+ ctx.num_heads_q = num_heads_q
221
+ return qkv
222
+
223
+ @staticmethod
224
+ def backward(ctx, dqkv):
225
+ seqlen_offsets = ctx.seqlen_offsets
226
+ if seqlen_offsets is None:
227
+ cos, sin, cos_k, sin_k, seqlen_offsets = ctx.saved_tensors
228
+ else:
229
+ cos, sin, cos_k, sin_k = ctx.saved_tensors
230
+ dqkv = _apply_rotary_emb_qkv(
231
+ dqkv, cos, sin, cos_k, sin_k, interleaved=ctx.interleaved, inplace=True,
232
+ seqlen_offsets=seqlen_offsets, num_heads_q=ctx.num_heads_q, conjugate=True,
233
+ )
234
+ return dqkv, None, None, None, None, None, None, None
235
+
236
+
237
+ def apply_rotary_emb_qkv_(
238
+ qkv,
239
+ cos,
240
+ sin,
241
+ cos_k=None,
242
+ sin_k=None,
243
+ interleaved=False,
244
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
245
+ num_heads_q: Optional[int] = None,
246
+ ):
247
+ """
248
+ Arguments:
249
+ qkv: (batch_size, seqlen, 3, nheads, headdim) or (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim).
250
+ If qkv has shape (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim) (e.g. MQA / GQA),
251
+ then num_heads_q must be provided.
252
+ cos, sin: (seqlen, rotary_dim / 2)
253
+ cos_k, sin_k: (seqlen, rotary_dim / 2), optional
254
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of
255
+ 1st half and 2nd half (GPT-NeoX style).
256
+ seqlen_offsets: (batch_size,) or int. Each sequence in Q and K is shifted by this amount.
257
+ Most commonly used in inference when we have KV cache.
258
+ Return:
259
+ qkv: (batch_size, seqlen, 3, nheads, headdim) or (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim)
260
+ rotary_dim must be <= headdim
261
+ Apply rotary embedding *inplace* to the first rotary_dim of Q and K.
262
+ """
263
+ return ApplyRotaryEmbQKV_.apply(
264
+ qkv, cos, sin, cos_k, sin_k, interleaved, seqlen_offsets, num_heads_q
265
+ )
266
+
267
+
268
+ class ApplyRotaryEmbKV_(torch.autograd.Function):
269
+
270
+ @staticmethod
271
+ def forward(ctx, kv, cos, sin, interleaved=False, seqlen_offsets: Union[int, torch.Tensor] = 0):
272
+ batch, seqlen, two, nheads, headdim = kv.shape
273
+ assert two == 2
274
+ k = kv[:, :, 0]
275
+ apply_rotary(
276
+ k, cos, sin, seqlen_offsets=seqlen_offsets, interleaved=interleaved, inplace=True
277
+ )
278
+ if isinstance(seqlen_offsets, int):
279
+ ctx.save_for_backward(cos, sin) # Can't save int with save_for_backward
280
+ ctx.seqlen_offsets = seqlen_offsets
281
+ else:
282
+ ctx.save_for_backward(cos, sin, seqlen_offsets)
283
+ ctx.seqlen_offsets = None
284
+ ctx.interleaved = interleaved
285
+ return kv
286
+
287
+ @staticmethod
288
+ def backward(ctx, dkv):
289
+ seqlen_offsets = ctx.seqlen_offsets
290
+ if seqlen_offsets is None:
291
+ cos, sin, seqlen_offsets = ctx.saved_tensors
292
+ else:
293
+ cos, sin = ctx.saved_tensors
294
+ apply_rotary(
295
+ dkv[:, :, 0],
296
+ cos,
297
+ sin,
298
+ seqlen_offsets=seqlen_offsets,
299
+ interleaved=ctx.interleaved,
300
+ inplace=True,
301
+ conjugate=True,
302
+ )
303
+ return dkv, None, None, None, None
304
+
305
+
306
+ apply_rotary_emb_kv_ = ApplyRotaryEmbKV_.apply
307
+
308
+
309
+ def apply_rotary_emb_kv_(
310
+ kv,
311
+ cos,
312
+ sin,
313
+ interleaved=False,
314
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
315
+ ):
316
+ """
317
+ Arguments:
318
+ kv: (batch_size, seqlen, 2, nheads, headdim)
319
+ cos, sin: (seqlen, rotary_dim / 2)
320
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of
321
+ 1st half and 2nd half (GPT-NeoX style).
322
+ seqlen_offsets: (batch_size,) or int. Each sequence in Q and K is shifted by this amount.
323
+ Most commonly used in inference when we have KV cache.
324
+ Return:
325
+ kv: (batch_size, seqlen, 2, nheads, headdim)
326
+ rotary_dim must be <= headdim
327
+ Apply rotary embedding *inplace* to the first rotary_dim of K.
328
+ """
329
+ return ApplyRotaryEmbKV_.apply(kv, cos, sin, interleaved, seqlen_offsets)
330
+
331
+
332
+ class RotaryEmbedding(torch.nn.Module):
333
+ """
334
+ The rotary position embeddings from RoFormer_ (Su et. al).
335
+ A crucial insight from the method is that the query and keys are
336
+ transformed by rotation matrices which depend on the relative positions.
337
+
338
+ Other implementations are available in the Rotary Transformer repo_ and in
339
+ GPT-NeoX_, GPT-NeoX was an inspiration
340
+
341
+ .. _RoFormer: https://arxiv.org/abs/2104.09864
342
+ .. _repo: https://github.com/ZhuiyiTechnology/roformer
343
+ .. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox
344
+
345
+ If scale_base is not None, this implements XPos (Sun et al., https://arxiv.org/abs/2212.10554).
346
+ A recommended value for scale_base is 512: https://github.com/HazyResearch/flash-attention/issues/96
347
+ Reference: https://github.com/sunyt32/torchscale/blob/main/torchscale/component/xpos_relative_position.py
348
+ """
349
+
350
+ def __init__(
351
+ self,
352
+ dim: int,
353
+ base=10000.0,
354
+ interleaved=False,
355
+ scale_base=None,
356
+ device=None,
357
+ ):
358
+ """
359
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
360
+ of 1st half and 2nd half (GPT-NeoX style).
361
+ """
362
+ super().__init__()
363
+ self.dim = dim
364
+ self.base = float(base)
365
+ # Generate and save the inverse frequency buffer (non trainable)
366
+ inv_freq = self._compute_inv_freq(device)
367
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
368
+ self.interleaved = interleaved
369
+ self.scale_base = scale_base
370
+ scale = (
371
+ (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim)
372
+ if scale_base is not None
373
+ else None
374
+ )
375
+ self.register_buffer("scale", scale, persistent=False)
376
+
377
+ self._seq_len_cached = 0
378
+ self._cos_cached = None
379
+ self._sin_cached = None
380
+ self._cos_k_cached = None
381
+ self._sin_k_cached = None
382
+
383
+ def _compute_inv_freq(self, device=None):
384
+ return 1.0 / (
385
+ self.base
386
+ ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim)
387
+ )
388
+
389
+ def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
390
+ # Reset the tables if the sequence length has changed,
391
+ # if we're on a new device (possibly due to tracing for instance),
392
+ # or if we're switching from inference mode to training
393
+ if (
394
+ seqlen > self._seq_len_cached
395
+ or self._cos_cached is None
396
+ or self._cos_cached.device != device
397
+ or self._cos_cached.dtype != dtype
398
+ or (self.training and self._cos_cached.is_inference())
399
+ ):
400
+ self._seq_len_cached = seqlen
401
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
402
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
403
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
404
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
405
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
406
+ # cos & sin output to change significantly.
407
+ # We want to recompute self.inv_freq if it was not loaded in fp32
408
+ if self.inv_freq.dtype != torch.float32:
409
+ inv_freq = self._compute_inv_freq(device=device)
410
+ else:
411
+ inv_freq = self.inv_freq
412
+ # Don't do einsum, it converts fp32 to bf16 under AMP
413
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
414
+ freqs = torch.outer(t, inv_freq)
415
+ if self.scale is None:
416
+ self._cos_cached = torch.cos(freqs).to(dtype)
417
+ self._sin_cached = torch.sin(freqs).to(dtype)
418
+ else:
419
+ power = (
420
+ torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device)
421
+ - seqlen // 2
422
+ ) / self.scale_base
423
+ scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
424
+ # We want the multiplication by scale to happen in fp32
425
+ self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
426
+ self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
427
+ self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
428
+ self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
429
+
430
+ def forward(
431
+ self,
432
+ qkv: torch.Tensor,
433
+ kv: Optional[torch.Tensor] = None,
434
+ seqlen_offset: Union[int, torch.Tensor] = 0,
435
+ max_seqlen: Optional[int] = None,
436
+ num_heads_q: Optional[int] = None,
437
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
438
+ """
439
+ qkv: (batch, seqlen, 3, nheads, headdim) or (batch, seqlen, num_heads_q + 2 * num_heads_k, headdim)
440
+ if kv is none, else it's just q of shape (batch, seqlen, nheads, headdim).
441
+ If qkv has shape (batch, seqlen, num_heads_q + 2 * num_heads_k, headdim) (e.g. MQA / GQA),
442
+ then num_heads_q must be provided.
443
+ kv: (batch, seqlen, 2, nheads, headdim)
444
+ seqlen_offset: (batch_size,) or int. Each sequence in x is shifted by this amount.
445
+ Most commonly used in inference when we have KV cache.
446
+ If it's a tensor of shape (batch_size,), then to update the cos / sin cache, one
447
+ should pass in max_seqlen, which will update the cos / sin cache up to that length.
448
+ Apply rotary embedding *inplace* to qkv and / or kv.
449
+ """
450
+ seqlen = qkv.shape[1]
451
+ if max_seqlen is not None:
452
+ self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype)
453
+ elif isinstance(seqlen_offset, int):
454
+ self._update_cos_sin_cache(seqlen + seqlen_offset, device=qkv.device, dtype=qkv.dtype)
455
+ if kv is None:
456
+ return apply_rotary_emb_qkv_(
457
+ qkv,
458
+ self._cos_cached,
459
+ self._sin_cached,
460
+ self._cos_k_cached if self.scale is not None else None,
461
+ self._sin_k_cached if self.scale is not None else None,
462
+ interleaved=self.interleaved,
463
+ seqlen_offsets=seqlen_offset,
464
+ num_heads_q=num_heads_q,
465
+ )
466
+ else:
467
+ q = qkv
468
+ q = apply_rotary_emb_func(
469
+ q,
470
+ self._cos_cached,
471
+ self._sin_cached,
472
+ interleaved=self.interleaved,
473
+ inplace=True,
474
+ seqlen_offsets=seqlen_offset,
475
+ )
476
+ kv = apply_rotary_emb_kv_(
477
+ kv,
478
+ self._cos_cached if self.scale is None else self._cos_k_cached,
479
+ self._sin_cached if self.scale is None else self._sin_k_cached,
480
+ interleaved=self.interleaved,
481
+ seqlen_offsets=seqlen_offset,
482
+ )
483
+ return q, kv
build/torch211-cxx11-cu130-aarch64-linux/metadata.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "name": "flash-attn2",
3
- "id": "_flash_attn2_cuda_a511a4c",
4
  "version": 1,
5
  "license": "BSD-3-Clause",
6
  "python-depends": [],
@@ -16,12 +16,27 @@
16
  "digest": {
17
  "algorithm": "sha256",
18
  "files": {
19
- "__init__.py": "pbZ3riEB3GTIymdTvC7023ydYDWalnxEy+Lq0DGeZoQ=",
20
- "_flash_attn2_cuda_a511a4c.abi3.so": "V/XjC36TAsqRc4dzjHoa5VR/rsmmun36me5LjDhPY/w=",
21
- "_ops.py": "ceg+0r4TQ9sSFsTUNrdsGNcrceyYp1uw3N5C3bS/Q/Y=",
22
  "bert_padding.py": "gF1EmsdJ+HpQ86MRQ4VxDw+Sb/RVISdQALdNnoByHlw=",
23
  "flash_attn2/__init__.py": "DFYPlrhXwYjEqCl/8n0SmWGZV8NFml5DPhMjKfv98GY=",
24
- "flash_attn_interface.py": "pJrnUxC+7qEqFh1C1YbjYggC9FfoG3dblU+XlwaJkEs="
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  }
26
  }
27
  }
 
1
  {
2
  "name": "flash-attn2",
3
+ "id": "_flash_attn2_cuda_f12afc9",
4
  "version": 1,
5
  "license": "BSD-3-Clause",
6
  "python-depends": [],
 
16
  "digest": {
17
  "algorithm": "sha256",
18
  "files": {
19
+ "__init__.py": "Cd9MEdd/WUYnBmfiQpC4SyPqAxrTilTjvsvswNju4zc=",
20
+ "_flash_attn2_cuda_f12afc9.abi3.so": "ouJYCCn5yvOQyUHxa2Dkyle0ODjE7euyVKoJk3Hsq98=",
21
+ "_ops.py": "GQbmTTeSOU+7Q2nI68Hz+1RvEogyfEFccx1ubUYw+2s=",
22
  "bert_padding.py": "gF1EmsdJ+HpQ86MRQ4VxDw+Sb/RVISdQALdNnoByHlw=",
23
  "flash_attn2/__init__.py": "DFYPlrhXwYjEqCl/8n0SmWGZV8NFml5DPhMjKfv98GY=",
24
+ "flash_attn_interface.py": "W7a9bHR2ly6QL3aKqsBqxWA7M7ZWYcZPmtsPJu6rAfY=",
25
+ "layers/__init__.py": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",
26
+ "layers/patch_embed.py": "H58CgME/qSOPTZLOG08wFgrQS1j34pvNwMPrkTj3Ek4=",
27
+ "layers/rotary.py": "rFIdNrZQFNawwLD6d7t5LE2m+M93wwDZ8EuExw+gfD8=",
28
+ "ops/__init__.py": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=",
29
+ "ops/activations.py": "t5lzNg1In8LP6bKeTnyeMizwqjv27JGbJ6ylPdGvZYg=",
30
+ "ops/fused_dense.py": "BqT8VTSCGdLJAjh6WBMkCRFYrdVodPeoElWBvH6AIzA=",
31
+ "ops/layer_norm.py": "zr7NXIm+2mtEynTp1CS0fbFGI2Mqdp41dY4AfDWF6EQ=",
32
+ "ops/rms_norm.py": "XEnihcj0a4aSz4LO55m5iKGVn4HKTeKN8TIyHjuDgxI=",
33
+ "ops/triton/__init__.py": "AbpHGcgLb+kRsJGnwFEktk7uzpZOCcBY74+YBdrKVGs=",
34
+ "ops/triton/cross_entropy.py": "y56nmuOtpSNxM7sDZcUSgXKIsIEayfuvrU8bAVog/nw=",
35
+ "ops/triton/k_activations.py": "+Z3vIyO4JkqBMipKsPvhzmxljtBdIhJCsl/M+/ESqBo=",
36
+ "ops/triton/layer_norm.py": "BBQdJiqopbIS12viUqzx3SvOQCNbDSAYLJXhpyMGyC8=",
37
+ "ops/triton/linear.py": "OtRvKz8xdpl+7v3q/ZTaS9fdBt9XrzMyapgRr50uBbM=",
38
+ "ops/triton/mlp.py": "uWA+D7HyuRUsOT+4nhi3vvCDNZnNEXwYcHMQ02UREfQ=",
39
+ "ops/triton/rotary.py": "0YSrlbep0lJmzLpTiANs0slTFeGcQQqR+el6uzbSLvI="
40
  }
41
  }
42
  }