Skip to content

Instantly share code, notes, and snippets.

@hypnopump
Last active December 1, 2022 14:24
Show Gist options
  • Save hypnopump/73bd8b3968b00cc6342401bb2dffdc19 to your computer and use it in GitHub Desktop.
Save hypnopump/73bd8b3968b00cc6342401bb2dffdc19 to your computer and use it in GitHub Desktop.
Attention comparison between PyTorch and KeOps
"""
Copyright 2021 Eric Alcaide
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
"""
import time
import torch
from torch import nn, einsum, broadcast_tensors
import torch.nn.functional as F
from einops import rearrange, repeat
from pykeops import torch as keops_torch
class Attention(nn.Module):
""" Simple PyTorch Attention. """
def __init__(self, dim, heads = 8, dim_head = 64, bias=False):
super().__init__()
inner_dim = heads * dim_head
self.heads = heads
self.scale = dim_head ** -0.5
self.to_q = nn.Linear(dim, inner_dim, bias = bias)
self.to_kv = nn.Linear(dim, inner_dim * 2, bias = bias)
self.to_out = nn.Linear(inner_dim, dim)
def forward(self, x, context, mask = None):
h = self.heads
q = self.to_q(x)
kv = self.to_kv(context).chunk(2, dim = -1)
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = h), (q, *kv))
dots = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale
if mask is not None:
mask_value = -torch.finfo(dots.dtype).max
mask = rearrange(mask, 'b n -> b () () n')
dots.masked_fill_(~mask, mask_value)
attn = dots.softmax(dim = -1)
out = einsum('b h i j, b h j d -> b h i d', attn, v)
out = rearrange(out, 'b h n d -> b n (h d)', h = h)
return self.to_out(out)
class Attention_keops(nn.Module):
def __init__(self, dim, heads=1, dim_head = 64, bias=False):
super().__init__()
inner_dim = heads * dim_head
self.heads = heads
self.scale = dim_head ** -0.5
self.to_q = nn.Linear(dim, inner_dim, bias = bias)
self.to_k = nn.Linear(dim, inner_dim, bias = bias)
self.to_v = nn.Linear(dim, inner_dim, bias = bias)
self.to_out = nn.Linear(inner_dim, dim)
def forward(self, x, context, mask = None):
h = self.heads
q = rearrange( self.to_q(x), 'b n (h d) -> b h n () d', h=h ) * self.scale
k = rearrange( self.to_k(context), 'b n (h d) -> b h () n d', h=h )
v = rearrange( self.to_v(context), 'b n (h d) -> b h () n d', h=h )
q,k,v = map( lambda t: keops_torch.LazyTensor(t), (q,k,v) )
attn = (q*k).sum(dim=-1) # q | k
if mask is not None:
mask = LazyTensor( mask.unsqueeze(-1) )
attn += mask
out = attn.sumsoftmaxweight(v, dim=len(x.shape))
out = rearrange(out, 'b h n d -> b n (h d)', h = h)
return self.to_out( out )
if __name__ == "__main__":
# perform a sample test
b, l, d = 64, 32, 64
torch.random.manual_seed(42)
x = torch.randn(b, l, d)
y = torch.randn(b, l, d)
torch.random.manual_seed(42)
attn = Attention(dim=d, heads=1)
torch.random.manual_seed(42)
attn_keops = Attention_keops(d)
assert torch.allclose(attn_keops(x,y), attn(x,y), atol=1e-5), "Attns are not the same"
tic = time.time()
res = attn_keops(x,y)
print("Attn keops took:", time.time()-tic)
tic = time.time()
res = attn(x,y)
print("Attn pytorch took:", time.time()-tic)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment