PoPE-pytorch 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: PoPE-pytorch
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: PoPE
5
5
  Project-URL: Homepage, https://pypi.org/project/PoPE-pytorch/
6
6
  Project-URL: Repository, https://codeberg.org/lucidrains/PoPE-pytorch
@@ -36,7 +36,7 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
36
36
  Requires-Python: >=3.10
37
37
  Requires-Dist: einops>=0.8.1
38
38
  Requires-Dist: einx[torch]>=0.3.0
39
- Requires-Dist: torch-einops-utils>=0.1.0
39
+ Requires-Dist: torch-einops-utils>=0.2.10
40
40
  Requires-Dist: torch>=2.5
41
41
  Provides-Extra: examples
42
42
  Provides-Extra: test
@@ -1,12 +1,18 @@
1
1
  import torch
2
2
  import torch.nn.functional as F
3
- from torch import is_tensor, einsum
3
+ from torch import einsum
4
+
4
5
  from PoPE_pytorch.pope import apply_pope_to_qk
5
6
 
6
- from torch_einops_utils import and_masks
7
+ from torch_einops_utils import (
8
+ pad_right_at_dim_to,
9
+ repeat_interleave_to_match,
10
+ slice_left_at_dim
11
+ )
12
+ from torch_einops_utils.shape import shape, size, is_shape
7
13
 
8
14
  import einx
9
- from einops import rearrange, repeat
15
+ from einops import rearrange
10
16
 
11
17
  # triton available
12
18
 
@@ -25,14 +31,11 @@ def exists(v):
25
31
  def default(v, d):
26
32
  return v if exists(v) else d
27
33
 
28
- def divisible_by(num, den):
29
- return (num % den) == 0
30
-
31
- def pad_freqs_for_mixed_positions(freqs, indices, seq_len, device):
34
+ def pad_freqs_for_mixed_positions(freqs, indices, seq_len):
32
35
  if not exists(freqs):
33
36
  return freqs
34
37
 
35
- padded_freqs = freqs.new_zeros((seq_len, freqs.shape[-1]))
38
+ padded_freqs = freqs.new_zeros(shape(freqs, 'n d').replace(n = seq_len))
36
39
  padded_freqs[indices] = freqs
37
40
  return padded_freqs
38
41
 
@@ -49,15 +52,15 @@ def compute_attn_similarity_non_fused(
49
52
  q = rearrange(q, 'b n h d -> b h n d')
50
53
  k = rearrange(k, 'b n h d -> b h n d')
51
54
 
52
- q_heads, k_heads, q_len, device = q.shape[1], k.shape[1], q.shape[2], q.device
55
+ heads, q_len = shape(q, 'b [h n] d')
53
56
 
54
- groups = q_heads // k_heads
55
- k = repeat(k, 'b h ... -> b (g h) ...', g = groups)
57
+ k = repeat_interleave_to_match(k, q, dim = 1)
56
58
 
57
59
  freqs, bias = pope
60
+ bias = repeat_interleave_to_match(bias, heads, dim = 0)
58
61
 
59
62
  if exists(pope_pos_emb_indices):
60
- freqs = pad_freqs_for_mixed_positions(freqs, pope_pos_emb_indices, q_len, device)
63
+ freqs = pad_freqs_for_mixed_positions(freqs, pope_pos_emb_indices, q_len)
61
64
 
62
65
  pope = (freqs, bias)
63
66
  q_pope, k_pope = apply_pope_to_qk(pope, q, k, to_magnitude = F.softplus)
@@ -82,27 +85,23 @@ def compute_attn_similarity(
82
85
  allow_tf32 = True,
83
86
  head_dimension_at_first = True
84
87
  ):
85
- head_idx = 1 if head_dimension_at_first else 2
86
- q_heads, k_heads = q.shape[head_idx], k.shape[head_idx]
87
- assert divisible_by(q_heads, k_heads)
88
-
89
88
  freqs, bias = pope
90
- head_dim = q.shape[-1]
91
-
92
- assert head_dim in {32, 48, 64, 128, 256}, f"head_dim {head_dim} not in common sizes"
93
89
 
94
90
  is_cuda = q.is_cuda and k.is_cuda and freqs.is_cuda and bias.is_cuda
95
91
 
96
- if TRITON_AVAILABLE and is_cuda:
92
+ # fallthrough to non-fused for mixed pos
93
+
94
+ if TRITON_AVAILABLE and is_cuda and not exists(pope_pos_emb_indices):
95
+ head_dim = size(q, '... [d]')
96
+ assert head_dim in {32, 48, 64, 128, 256}, f'head_dim {head_dim} not in common sizes'
97
+
97
98
  if not head_dimension_at_first:
98
99
  q = rearrange(q, 'b n h d -> b h n d')
99
100
  k = rearrange(k, 'b n h d -> b h n d')
100
101
 
101
- rotate_dim = freqs.shape[-1]
102
-
103
- # fallthrough to non-fused for mixed pos
104
- if not exists(pope_pos_emb_indices):
105
- return triton_compute_qk_similarity(q, k, freqs, bias, rotate_dim, allow_tf32 = allow_tf32)
102
+ rotate_dim = size(freqs, '... [r]')
103
+
104
+ return triton_compute_qk_similarity(q, k, freqs, bias, rotate_dim, allow_tf32 = allow_tf32)
106
105
 
107
106
  return compute_attn_similarity_non_fused(q, k, pope, pope_pos_emb_indices = pope_pos_emb_indices, head_dimension_at_first = head_dimension_at_first)
108
107
 
@@ -119,38 +118,47 @@ def flash_attn_with_pope(
119
118
  head_dimension_at_first = True,
120
119
  dropout = 0.
121
120
  ):
122
- seq_dim = 2 if head_dimension_at_first else 1
123
- head_idx = 1 if head_dimension_at_first else 2
124
- q_len, kv_len, device = q.shape[seq_dim], k.shape[seq_dim], q.device
125
- q_heads, k_heads = q.shape[head_idx], k.shape[head_idx]
121
+ layout = 'b h n d' if head_dimension_at_first else 'b n h d'
122
+
123
+ q_shape = shape(q, layout)
124
+ heads, q_len, q_dim = q_shape.h, q_shape.n, q_shape.d
125
+ kv_len = size(k, f'{layout} -> n')
126
+ v_dim = size(v, f'{layout} -> d')
127
+ head_axis = q_shape.axis('h')
128
+ device = q.device
126
129
 
127
130
  fused = default(fused, TRITON_AVAILABLE and q.is_cuda)
128
131
 
129
- softmax_scale = default(softmax_scale, q.shape[-1] ** -0.5)
132
+ softmax_scale = default(softmax_scale, q_dim ** -0.5)
130
133
 
131
- groups = q_heads // k_heads
132
- k = repeat(k, 'b h ... -> b (g h) ...', g = groups) if groups > 1 else k
133
- v = repeat(v, 'b h ... -> b (g h) ...', g = groups) if groups > 1 else v
134
+ k = repeat_interleave_to_match(k, q, dim = head_axis)
135
+ v = repeat_interleave_to_match(v, q, dim = head_axis)
134
136
 
135
137
  attn_mask = mask
136
138
  if exists(attn_mask):
137
- attn_mask = rearrange(attn_mask, 'b j -> b 1 1 j')
139
+ if is_shape(attn_mask, 'i j', i = q_len, j = kv_len):
140
+ attn_mask = rearrange(attn_mask, 'i j -> 1 1 i j')
141
+ elif is_shape(attn_mask, 'b j'):
142
+ attn_mask = rearrange(attn_mask, 'b j -> b 1 1 j')
143
+ elif is_shape(attn_mask, 'b i j'):
144
+ attn_mask = rearrange(attn_mask, 'b i j -> b 1 i j')
138
145
 
139
146
  pos_mask = None
147
+ freqs, bias = None, None
140
148
 
141
149
  if exists(pos_emb):
142
150
  freqs, bias = pos_emb
143
-
151
+ bias = repeat_interleave_to_match(bias, heads, dim = 0)
152
+
144
153
  if exists(pope_pos_emb_indices):
145
154
  # handle mixed positions
146
- freqs = pad_freqs_for_mixed_positions(freqs, pope_pos_emb_indices, q_len, device)
155
+ freqs = pad_freqs_for_mixed_positions(freqs, pope_pos_emb_indices, q_len)
147
156
  pos_mask = q.new_zeros(q_len, dtype = torch.bool)
148
157
  pos_mask[pope_pos_emb_indices] = True
149
158
 
150
159
  pos_emb = (freqs, bias)
151
160
 
152
161
  if fused:
153
- freqs, bias = pos_emb
154
162
  if head_dimension_at_first:
155
163
  q = rearrange(q, 'b h n d -> b n h d')
156
164
  k = rearrange(k, 'b h n d -> b n h d')
@@ -174,16 +182,18 @@ def flash_attn_with_pope(
174
182
  k = rearrange(k, 'b n h d -> b h n d')
175
183
  v = rearrange(v, 'b n h d -> b h n d')
176
184
 
177
- q_pope, k_pope = apply_pope_to_qk(pos_emb, q, k, to_magnitude = F.softplus)
185
+ if exists(pos_emb):
186
+ q_pope, k_pope = apply_pope_to_qk(pos_emb, q, k, to_magnitude = F.softplus)
187
+ else:
188
+ q_pope, k_pope = q, k
178
189
 
179
190
  # manual attention path using SDPA
180
191
  # ensure dtypes match for SDPA (apply_pope_to_qk might have upcasted to float32)
181
192
 
182
193
  v_dtype = v.dtype
183
- v_dim = v.shape[-1]
184
194
 
185
- if q.dtype != v.dtype:
186
- v = v.to(q.dtype)
195
+ if q_pope.dtype != v.dtype:
196
+ v = v.to(q_pope.dtype)
187
197
 
188
198
  if exists(pos_mask):
189
199
  # handle mixed positions manually
@@ -204,6 +214,15 @@ def flash_attn_with_pope(
204
214
  attn = F.dropout(attn, p = dropout, training = v.requires_grad)
205
215
  out = einsum('b h i j, b h j d -> b h i d', attn, v)
206
216
  else:
217
+ # mps sdpa bug (torch 2.9.1) - when q/k dim != v dim in no_grad,
218
+ # output dim is wrong and values are corrupted. pad to match, then slice back
219
+
220
+ if q.device.type == 'mps':
221
+ max_dim = max(size(q_pope, '... [d]'), v_dim)
222
+ q_pope = pad_right_at_dim_to(q_pope, max_dim)
223
+ k_pope = pad_right_at_dim_to(k_pope, max_dim)
224
+ v = pad_right_at_dim_to(v, max_dim)
225
+
207
226
  out = F.scaled_dot_product_attention(
208
227
  q_pope, k_pope, v,
209
228
  attn_mask = attn_mask,
@@ -212,12 +231,7 @@ def flash_attn_with_pope(
212
231
  dropout_p = dropout
213
232
  )
214
233
 
215
- # mps sdpa bug (pytorch 2.9.1) - output takes q/k dim instead of v dim
216
- # first v_dim elements are correct, so slicing suffices
217
- # only triggers in no_grad (inference). todo - remove once fixed upstream
218
-
219
- if out.shape[-1] != v_dim:
220
- out = out[..., :v_dim]
234
+ out = slice_left_at_dim(out, v_dim)
221
235
 
222
236
  out = out.to(v_dtype)
223
237
 
@@ -3,7 +3,7 @@ from collections import namedtuple
3
3
  from math import pi
4
4
 
5
5
  import torch
6
- from torch import arange, cat, stack, is_tensor, Tensor
6
+ from torch import arange, cat, is_tensor, Tensor
7
7
  from torch.nn import Module, Parameter
8
8
  from torch.amp import autocast
9
9
 
@@ -12,6 +12,7 @@ import torch.nn.functional as F
12
12
  from einops import einsum, rearrange
13
13
 
14
14
  from torch_einops_utils import slice_right_at_dim
15
+ from torch_einops_utils.shape import shape, size, is_shape
15
16
 
16
17
  # constants
17
18
 
@@ -22,8 +23,11 @@ PolarEmbedReturn = namedtuple('PolarEmbedReturn', ('freqs', 'bias'))
22
23
  def exists(v):
23
24
  return v is not None
24
25
 
25
- def default(v, d):
26
- return v if exists(v) else d
26
+ def to_polar(t, freqs, return_complex = False):
27
+ if return_complex:
28
+ return torch.polar(t, freqs)
29
+
30
+ return rearrange([t * freqs.cos(), t * freqs.sin()], 'two ... d -> ... (d two)')
27
31
 
28
32
  # applying pope to qk
29
33
 
@@ -36,7 +40,9 @@ def apply_pope_to_qk(
36
40
  ):
37
41
  freqs, bias = pope
38
42
 
39
- q_len, k_len, qk_dim, rotate_dim = q.shape[-2], k.shape[-2], q.shape[-1], freqs.shape[-1]
43
+ q_len, qk_dim = shape(q, '... [n d]')
44
+ k_len = size(k, '... [n] d', d = qk_dim)
45
+ rotate_dim = size(freqs, '... [r]')
40
46
 
41
47
  assert q_len <= k_len and rotate_dim <= qk_dim
42
48
 
@@ -50,7 +56,7 @@ def apply_pope_to_qk(
50
56
  q_rest = torch.polar(q_rest, torch.zeros_like(q_rest))
51
57
  k_rest = torch.polar(k_rest, torch.zeros_like(k_rest))
52
58
 
53
- if freqs.ndim == 3:
59
+ if is_shape(freqs, 'b n d'):
54
60
  freqs = rearrange(freqs, 'b n d -> b 1 n d')
55
61
 
56
62
  freqs_with_bias = freqs + rearrange(bias, 'h d -> h 1 d')
@@ -59,23 +65,12 @@ def apply_pope_to_qk(
59
65
 
60
66
  q, k = to_magnitude(q), to_magnitude(k)
61
67
 
62
- # apply rotations
68
+ # apply rotations (slice right for q to handle kv-cached inference)
63
69
 
64
- freqs = slice_right_at_dim(freqs, q_len, dim = -2)
65
-
66
- if return_complex:
67
- q = torch.polar(q, freqs)
68
- else:
69
- qcos, qsin = freqs.cos(), freqs.sin()
70
- q = rearrange([q * qcos, q * qsin], 'two ... d -> ... (d two)')
70
+ q_freqs = slice_right_at_dim(freqs, q_len, dim = -2)
71
71
 
72
- # handle inference
73
-
74
- if return_complex:
75
- k = torch.polar(k, freqs_with_bias)
76
- else:
77
- kcos, ksin = freqs_with_bias.cos(), freqs_with_bias.sin()
78
- k = rearrange([k * kcos, k * ksin], 'two ... d -> ... (d two)')
72
+ q = to_polar(q, q_freqs, return_complex = return_complex)
73
+ k = to_polar(k, freqs_with_bias, return_complex = return_complex)
79
74
 
80
75
  # concat
81
76
 
@@ -105,15 +100,19 @@ class PoPE(Module):
105
100
 
106
101
  if not exists(inv_freqs):
107
102
  inv_freqs = theta ** -(arange(dim).float() / dim)
103
+ elif not is_tensor(inv_freqs):
104
+ inv_freqs = torch.tensor(inv_freqs, dtype = torch.float)
108
105
 
109
106
  self.register_buffer('inv_freqs', inv_freqs)
110
107
 
111
108
  # the learned bias on the keys
112
109
 
113
- self.bias = Parameter(torch.zeros(heads, dim))
110
+ bias = torch.zeros(heads, dim)
114
111
 
115
112
  if bias_uniform_init:
116
- self.bias.uniform_(-2. * pi, 0.)
113
+ bias.uniform_(-2. * pi, 0.)
114
+
115
+ self.bias = Parameter(bias)
117
116
 
118
117
  @property
119
118
  def device(self):
@@ -2,22 +2,20 @@ from __future__ import annotations
2
2
  from math import pi
3
3
 
4
4
  import torch
5
- from torch import arange, cat, stack, is_tensor, Tensor, meshgrid
5
+ from torch import arange, cat, stack, Tensor, meshgrid
6
6
  from torch.nn import Module, Parameter, ParameterList
7
7
  from torch.amp import autocast
8
8
 
9
- from einops import einsum, rearrange
9
+ from einops import einsum
10
10
 
11
11
  from PoPE_pytorch.pope import PolarEmbedReturn, apply_pope_to_qk
12
+ from torch_einops_utils.shape import assert_shape
12
13
 
13
14
  # helper functions
14
15
 
15
16
  def exists(v):
16
17
  return v is not None
17
18
 
18
- def default(v, d):
19
- return v if exists(v) else d
20
-
21
19
  # Axial PoPE class
22
20
 
23
21
  class AxialPoPE(Module):
@@ -53,10 +51,12 @@ class AxialPoPE(Module):
53
51
 
54
52
  # the learned bias on the keys
55
53
 
56
- self.bias = Parameter(torch.zeros(heads, dim))
54
+ bias = torch.zeros(heads, dim)
57
55
 
58
56
  if bias_uniform_init:
59
- self.bias.uniform_(-2. * pi, 0.)
57
+ bias.uniform_(-2. * pi, 0.)
58
+
59
+ self.bias = Parameter(bias)
60
60
 
61
61
  @property
62
62
  def device(self):
@@ -81,7 +81,7 @@ class AxialPoPE(Module):
81
81
 
82
82
  # pos shape is (..., N) where N is len(axial_dims)
83
83
 
84
- assert pos.shape[-1] == len(self.axial_dims)
84
+ assert_shape(pos, '... n', n = len(self.axial_dims))
85
85
 
86
86
  all_freqs = []
87
87
 
@@ -5,14 +5,14 @@ import triton.language as tl
5
5
 
6
6
  from einops import repeat
7
7
 
8
+ from torch_einops_utils import repeat_interleave_to_match
9
+ from torch_einops_utils.shape import shape, size, is_shape
10
+
8
11
  # helpers
9
12
 
10
13
  def exists(v):
11
14
  return v is not None
12
15
 
13
- def divisible_by(num, den):
14
- return (num % den) == 0
15
-
16
16
  # activation
17
17
 
18
18
  @triton.jit
@@ -359,18 +359,18 @@ def _bwd_kernel_dbias(
359
359
  class PoPESimilarityFunction(torch.autograd.Function):
360
360
  @staticmethod
361
361
  def forward(ctx, q, k, freqs, bias, rotate_dim, allow_tf32):
362
- b, h, seq_q, d = q.shape
363
- seq_k = k.shape[2]
362
+ b, h, seq_q, d = shape(q, 'b h n d')
363
+ seq_k = size(k, 'b h [n] d')
364
364
 
365
- ctx.orig_freqs_shape = freqs.shape
365
+ ctx.orig_freqs_ndim = freqs.ndim
366
366
  ctx.freqs_requires_grad = freqs.requires_grad
367
367
  ctx.bias_requires_grad = bias.requires_grad
368
368
 
369
369
  # expand freqs to (b, h, seq, rotate_dim) if needed
370
370
 
371
- if freqs.ndim == 2:
371
+ if is_shape(freqs, 'n d'):
372
372
  freqs = repeat(freqs, 'n d -> b h n d', b = b, h = h)
373
- elif freqs.ndim == 3:
373
+ elif is_shape(freqs, 'b n d'):
374
374
  freqs = repeat(freqs, 'b n d -> b h n d', h = h)
375
375
 
376
376
  freqs = freqs.contiguous()
@@ -416,8 +416,8 @@ class PoPESimilarityFunction(torch.autograd.Function):
416
416
  q, k, freqs, bias = ctx.saved_tensors
417
417
  rotate_dim = ctx.rotate_dim
418
418
  allow_tf32 = ctx.allow_tf32
419
- b, h, seq_q, d = q.shape
420
- seq_k = k.shape[2]
419
+ b, h, seq_q, d = shape(q, 'b h n d')
420
+ seq_k = size(k, 'b h [n] d')
421
421
 
422
422
  dq = torch.zeros_like(q, dtype = torch.float32)
423
423
  dk = torch.empty_like(k)
@@ -554,7 +554,7 @@ class PoPESimilarityFunction(torch.autograd.Function):
554
554
 
555
555
  if exists(dfreqs_q):
556
556
  dfreqs = dfreqs_q + dfreqs_k
557
- ndim = len(ctx.orig_freqs_shape)
557
+ ndim = ctx.orig_freqs_ndim
558
558
  if ndim == 2:
559
559
  dfreqs_out = dfreqs.sum(dim = (0, 1)).to(q.dtype)
560
560
  elif ndim == 3:
@@ -570,12 +570,9 @@ class PoPESimilarityFunction(torch.autograd.Function):
570
570
  # public api
571
571
 
572
572
  def triton_compute_qk_similarity(q, k, freqs, bias, rotate_dim, allow_tf32 = True):
573
- assert divisible_by(q.shape[1], k.shape[1])
574
-
575
573
  q, k = q.contiguous(), k.contiguous()
576
574
 
577
- groups = q.shape[1] // k.shape[1]
578
- k = repeat(k, 'b h ... -> b (g h) ...', g = groups)
579
- bias = repeat(bias, 'h ... -> (g h) ...', g = groups)
575
+ k = repeat_interleave_to_match(k, q, dim = 1)
576
+ bias = repeat_interleave_to_match(bias, q, dim = 0, target_dim = 1)
580
577
 
581
578
  return PoPESimilarityFunction.apply(q, k, freqs, bias, rotate_dim, allow_tf32)
@@ -5,6 +5,7 @@ from torch.autograd import Function
5
5
 
6
6
  import triton
7
7
  import triton.language as tl
8
+ from torch_einops_utils.shape import shape, size, is_shape
8
9
 
9
10
  # helpers
10
11
 
@@ -78,16 +79,23 @@ def _bwd_configs():
78
79
  def _freq_strides(freqs):
79
80
  if not exists(freqs):
80
81
  return (0, 0, 0)
81
- if freqs.ndim == 2:
82
+ if is_shape(freqs, 'n d'):
82
83
  return (0, 0, freqs.stride(0))
83
- if freqs.ndim == 3:
84
+ if is_shape(freqs, 'b n d'):
84
85
  return (freqs.stride(0), 0, freqs.stride(1))
85
86
  return (freqs.stride(0), freqs.stride(2), freqs.stride(1))
86
87
 
87
88
  def _mask_strides(mask):
88
89
  if not exists(mask):
89
- return (0, 0)
90
- return (mask.stride(0), mask.stride(1))
90
+ return (0, 0, 0, 0)
91
+
92
+ strides = [s if n > 1 else 0 for n, s in zip(mask.shape, mask.stride())]
93
+
94
+ if is_shape(mask, 'i j'):
95
+ return (0, 0, *strides)
96
+ if is_shape(mask, 'b i j'):
97
+ return (strides[0], 0, strides[1], strides[2])
98
+ return tuple(strides)
91
99
 
92
100
  # activation helpers
93
101
 
@@ -127,7 +135,7 @@ def _fwd_kernel(
127
135
  stride_fb, stride_fh, stride_fi,
128
136
  stride_pbh,
129
137
  stride_ob, stride_oh, stride_om,
130
- stride_kmb, stride_kmn,
138
+ stride_mb, stride_mh, stride_mm, stride_mn,
131
139
  n_heads, seqlen_q, seqlen_k, headdim, rotate_dim, dropout_p, drop_seed,
132
140
  HAS_POPE: tl.constexpr, IS_CAUSAL: tl.constexpr, HAS_MASK: tl.constexpr, IS_DROPOUT: tl.constexpr, HAS_POS_MASK: tl.constexpr,
133
141
  BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr,
@@ -159,7 +167,6 @@ def _fwd_kernel(
159
167
 
160
168
  q_off = seqlen_k - seqlen_q
161
169
 
162
-
163
170
  if HAS_POPE:
164
171
  q_act = _apply_softplus(q, mask_r)
165
172
  fq = tl.load(Freqs + b * stride_fb + h * stride_fh + (q_off + off_m[:, None]) * stride_fi + off_d[None, :], mask = mask_m[:, None] & mask_r[None, :], other = 0.0).to(tl.float32)
@@ -220,8 +227,8 @@ def _fwd_kernel(
220
227
  qk += tl.where(off_m[:, None] + q_off >= col_n[None, :], 0, float('-inf'))
221
228
 
222
229
  if HAS_MASK:
223
- mask = tl.load(Mask + b * stride_kmb + col_n * stride_kmn, mask = cmask, other = False)
224
- qk += tl.where(mask[None, :], 0, float('-inf'))
230
+ mask = tl.load(Mask + b * stride_mb + h * stride_mh + off_m[:, None] * stride_mm + col_n[None, :] * stride_mn, mask = mask_m[:, None] & cmask[None, :], other = False)
231
+ qk += tl.where(mask, 0, float('-inf'))
225
232
 
226
233
  if not EVEN_N:
227
234
  qk += tl.where(cmask[None, :], 0, float('-inf'))
@@ -309,7 +316,7 @@ def _bwd_kernel(
309
316
  stride_dkb, stride_dkh, stride_dkn,
310
317
  stride_dvb, stride_dvh, stride_dvn,
311
318
  stride_dfb, stride_dfh, stride_dfi,
312
- stride_kmb, stride_kmn,
319
+ stride_mb, stride_mh, stride_mm, stride_mn,
313
320
  n_heads, seqlen_q, seqlen_k, headdim, rotate_dim, dropout_p, drop_seed,
314
321
  HAS_POPE: tl.constexpr, IS_CAUSAL: tl.constexpr, HAS_MASK: tl.constexpr, IS_DROPOUT: tl.constexpr, HAS_POS_MASK: tl.constexpr,
315
322
  BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr,
@@ -388,8 +395,8 @@ def _bwd_kernel(
388
395
  qk += tl.where(cur_m[:, None] + q_off >= off_n[None, :], 0, float('-inf'))
389
396
 
390
397
  if HAS_MASK:
391
- mask = tl.load(Mask + b * stride_kmb + off_n * stride_kmn, mask = mask_n, other = False)
392
- qk += tl.where(mask[None, :], 0, float('-inf'))
398
+ mask = tl.load(Mask + b * stride_mb + h * stride_mh + cur_m[:, None] * stride_mm + off_n[None, :] * stride_mn, mask = mask_m[:, None] & mask_n[None, :], other = False)
399
+ qk += tl.where(mask, 0, float('-inf'))
393
400
 
394
401
  # recompute prob from lse
395
402
 
@@ -499,15 +506,15 @@ def _bwd_kernel(
499
506
  # wrapper functions
500
507
 
501
508
  def flash_attn_forward(q, k, v, freqs = None, pope_bias = None, mask = None, causal = False, softmax_scale = None, dropout = 0., drop_seed = 0, pos_mask = None):
502
- batch, seq_q, heads, d = q.shape
503
- seq_k = k.shape[1]
509
+ batch, seq_q, heads, d = shape(q, 'b n h d')
510
+ seq_k = size(k, 'b [n] h d')
504
511
 
505
512
  scale = default(softmax_scale, d ** -0.5)
506
513
  has_p = exists(freqs) and exists(pope_bias)
507
514
 
508
515
  f_str = _freq_strides(freqs) if has_p else (0, 0, 0)
509
516
  pb_str = pope_bias.stride(0) if has_p else 0
510
- rot = freqs.shape[-1] if has_p else 0
517
+ rot = size(freqs, '... [r]') if has_p else 0
511
518
  m_str = _mask_strides(mask)
512
519
 
513
520
  lse = torch.empty((batch, heads, seq_q), device = q.device, dtype = torch.float32)
@@ -550,8 +557,8 @@ def flash_attn_forward(q, k, v, freqs = None, pope_bias = None, mask = None, cau
550
557
  return o, lse
551
558
 
552
559
  def flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, dfreqs = None, dpope_bias = None, freqs = None, pope_bias = None, mask = None, causal = False, softmax_scale = None, dropout = 0., drop_seed = 0, pos_mask = None):
553
- batch, seq_q, heads, d = q.shape
554
- seq_k = k.shape[1]
560
+ batch, seq_q, heads, d = shape(q, 'b n h d')
561
+ seq_k = size(k, 'b [n] h d')
555
562
 
556
563
  scale = default(softmax_scale, d ** -0.5)
557
564
  blk_d = max(triton.next_power_of_2(d), 16)
@@ -573,7 +580,7 @@ def flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, dfreqs = None, dpope_bi
573
580
  f_str = _freq_strides(freqs) if has_p else (0, 0, 0)
574
581
  df_str = _freq_strides(dfreqs) if has_p and exists(dfreqs) else (0, 0, 0)
575
582
  pb_str = pope_bias.stride(0) if has_p else 0
576
- rot = freqs.shape[-1] if has_p else 0
583
+ rot = size(freqs, '... [r]') if has_p else 0
577
584
  m_str = _mask_strides(mask)
578
585
 
579
586
  elem_bytes = q.element_size()
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "PoPE-pytorch"
3
- version = "0.2.0"
3
+ version = "0.2.2"
4
4
  description = "PoPE"
5
5
  authors = [
6
6
  { name = "Phil Wang", email = "lucidrains@gmail.com" }
@@ -26,7 +26,7 @@ dependencies = [
26
26
  "einx[torch]>=0.3.0",
27
27
  "einops>=0.8.1",
28
28
  "torch>=2.5",
29
- "torch-einops-utils>=0.1.0"
29
+ "torch-einops-utils>=0.2.10"
30
30
  ]
31
31
 
32
32
  [project.urls]
File without changes
File without changes
File without changes