lhallee commited on
Commit
b9ac427
·
verified ·
1 Parent(s): e11d727

Upload vb_tri_attn_attention.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. vb_tri_attn_attention.py +189 -189
vb_tri_attn_attention.py CHANGED
@@ -1,189 +1,189 @@
1
- # Copyright 2021 AlQuraishi Laboratory
2
- # Copyright 2021 DeepMind Technologies Limited
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
-
16
- from functools import partial, partialmethod
17
- from typing import Optional
18
-
19
- import torch
20
- import torch.nn as nn
21
-
22
- from .vb_tri_attn_primitives import (
23
- Attention,
24
- LayerNorm,
25
- Linear,
26
- )
27
- from .vb_tri_attn_utils import (
28
- chunk_layer,
29
- permute_final_dims,
30
- )
31
-
32
-
33
- class TriangleAttention(nn.Module):
34
- """Implement Algorithm 12."""
35
-
36
- def __init__(
37
- self,
38
- c_in: int,
39
- c_hidden: int,
40
- no_heads: int,
41
- starting: bool = True,
42
- inf: float = 1e9,
43
- ) -> None:
44
- super().__init__()
45
-
46
- self.c_in = c_in
47
- self.c_hidden = c_hidden
48
- self.no_heads = no_heads
49
- self.starting = starting
50
- self.inf = inf
51
-
52
- self.layer_norm = LayerNorm(self.c_in)
53
-
54
- self.linear = Linear(c_in, self.no_heads, bias=False, init="normal")
55
-
56
- self.mha = Attention(
57
- self.c_in, self.c_in, self.c_in, self.c_hidden, self.no_heads
58
- )
59
-
60
- @torch.jit.ignore
61
- def _chunk(
62
- self,
63
- x: torch.Tensor,
64
- tri_bias: torch.Tensor,
65
- mask_bias: torch.Tensor,
66
- mask: torch.Tensor,
67
- chunk_size: int,
68
- use_kernels: bool = False,
69
- ) -> torch.Tensor:
70
- """Compute triangle attention.
71
-
72
- Parameters
73
- ----------
74
- x : torch.Tensor
75
- Input tensor of shape [*, I, J, C_in]
76
- biases : list[torch.Tensor]
77
- List of bias tensors of shape [*, H, I, J]
78
- chunk_size : int
79
- Size of chunks for memory efficient computation
80
- use_kernels : bool, default=False
81
- Whether to use optimized CUDA kernels
82
-
83
- Returns
84
- -------
85
- torch.Tensor
86
- Output tensor of shape [*, I, J, C_in]
87
-
88
- """
89
- mha_inputs = {
90
- "q_x": x,
91
- "kv_x": x,
92
- "tri_bias": tri_bias,
93
- "mask_bias": mask_bias,
94
- "mask": mask,
95
- }
96
-
97
- return chunk_layer(
98
- partial(
99
- self.mha,
100
- use_kernels=use_kernels,
101
- ),
102
- mha_inputs,
103
- chunk_size=chunk_size,
104
- no_batch_dims=len(x.shape[:-2]),
105
- _out=None,
106
- )
107
-
108
- def forward(
109
- self,
110
- x: torch.Tensor,
111
- mask: Optional[torch.Tensor] = None,
112
- chunk_size: Optional[int] = None,
113
- use_kernels: bool = False,
114
- ) -> torch.Tensor:
115
- """Compute triangle attention.
116
-
117
- Parameters
118
- ----------
119
- x : torch.Tensor
120
- Input tensor of shape [*, I, J, C_in]
121
- mask : torch.Tensor, optional
122
- Attention mask of shape [*, I, J]
123
- chunk_size : int, optional
124
- Size of chunks for memory efficient computation
125
- use_kernels : bool, default=False
126
- Whether to use optimized CUDA kernels
127
-
128
- Returns
129
- -------
130
- torch.Tensor
131
- Output tensor of shape [*, I, J, C_in]
132
-
133
- """
134
- if mask is None:
135
- # [*, I, J]
136
- mask = x.new_ones(
137
- x.shape[:-1],
138
- )
139
-
140
- if not self.starting:
141
- x = x.transpose(-2, -3)
142
- mask = mask.transpose(-1, -2)
143
-
144
- # [*, I, J, C_in]
145
- x = self.layer_norm(x)
146
-
147
- # [*, I, 1, 1, J]
148
- mask = mask[..., :, None, None, :]
149
- mask_bias = self.inf * (mask - 1)
150
-
151
- # [*, H, I, J]
152
- triangle_bias = permute_final_dims(self.linear(x), (2, 0, 1))
153
-
154
- # [*, 1, H, I, J]
155
- triangle_bias = triangle_bias.unsqueeze(-4)
156
-
157
- if chunk_size is not None and not use_kernels:
158
- x = self._chunk(
159
- x,
160
- triangle_bias,
161
- mask_bias,
162
- mask,
163
- chunk_size,
164
- use_kernels=use_kernels,
165
- )
166
- else:
167
- x = self.mha(
168
- x,
169
- x,
170
- triangle_bias,
171
- mask_bias,
172
- mask,
173
- use_kernels=use_kernels,
174
- )
175
-
176
- if not self.starting:
177
- x = x.transpose(-2, -3)
178
-
179
- return x
180
-
181
-
182
- # Implements Algorithm 13
183
- TriangleAttentionStartingNode = TriangleAttention
184
-
185
-
186
- class TriangleAttentionEndingNode(TriangleAttention):
187
- """Implement Algorithm 14."""
188
-
189
- __init__ = partialmethod(TriangleAttention.__init__, starting=False)
 
1
+ # Copyright 2021 AlQuraishi Laboratory
2
+ # Copyright 2021 DeepMind Technologies Limited
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from functools import partial, partialmethod
17
+ from typing import Optional
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from .vb_tri_attn_primitives import (
23
+ Attention,
24
+ LayerNorm,
25
+ Linear,
26
+ )
27
+ from .vb_tri_attn_utils import (
28
+ chunk_layer,
29
+ permute_final_dims,
30
+ )
31
+
32
+
33
+ class TriangleAttention(nn.Module):
34
+ """Implement Algorithm 12."""
35
+
36
+ def __init__(
37
+ self,
38
+ c_in: int,
39
+ c_hidden: int,
40
+ no_heads: int,
41
+ starting: bool = True,
42
+ inf: float = 1e9,
43
+ ) -> None:
44
+ super().__init__()
45
+
46
+ self.c_in = c_in
47
+ self.c_hidden = c_hidden
48
+ self.no_heads = no_heads
49
+ self.starting = starting
50
+ self.inf = inf
51
+
52
+ self.layer_norm = LayerNorm(self.c_in)
53
+
54
+ self.linear = Linear(c_in, self.no_heads, bias=False, init="normal")
55
+
56
+ self.mha = Attention(
57
+ self.c_in, self.c_in, self.c_in, self.c_hidden, self.no_heads
58
+ )
59
+
60
+ @torch.jit.ignore
61
+ def _chunk(
62
+ self,
63
+ x: torch.Tensor,
64
+ tri_bias: torch.Tensor,
65
+ mask_bias: torch.Tensor,
66
+ mask: torch.Tensor,
67
+ chunk_size: int,
68
+ use_kernels: bool = False,
69
+ ) -> torch.Tensor:
70
+ """Compute triangle attention.
71
+
72
+ Parameters
73
+ ----------
74
+ x : torch.Tensor
75
+ Input tensor of shape [*, I, J, C_in]
76
+ biases : list[torch.Tensor]
77
+ List of bias tensors of shape [*, H, I, J]
78
+ chunk_size : int
79
+ Size of chunks for memory efficient computation
80
+ use_kernels : bool, default=False
81
+ Whether to use optimized CUDA kernels
82
+
83
+ Returns
84
+ -------
85
+ torch.Tensor
86
+ Output tensor of shape [*, I, J, C_in]
87
+
88
+ """
89
+ mha_inputs = {
90
+ "q_x": x,
91
+ "kv_x": x,
92
+ "tri_bias": tri_bias,
93
+ "mask_bias": mask_bias,
94
+ "mask": mask,
95
+ }
96
+
97
+ return chunk_layer(
98
+ partial(
99
+ self.mha,
100
+ use_kernels=use_kernels,
101
+ ),
102
+ mha_inputs,
103
+ chunk_size=chunk_size,
104
+ no_batch_dims=len(x.shape[:-2]),
105
+ _out=None,
106
+ )
107
+
108
+ def forward(
109
+ self,
110
+ x: torch.Tensor,
111
+ mask: Optional[torch.Tensor] = None,
112
+ chunk_size: Optional[int] = None,
113
+ use_kernels: bool = False,
114
+ ) -> torch.Tensor:
115
+ """Compute triangle attention.
116
+
117
+ Parameters
118
+ ----------
119
+ x : torch.Tensor
120
+ Input tensor of shape [*, I, J, C_in]
121
+ mask : torch.Tensor, optional
122
+ Attention mask of shape [*, I, J]
123
+ chunk_size : int, optional
124
+ Size of chunks for memory efficient computation
125
+ use_kernels : bool, default=False
126
+ Whether to use optimized CUDA kernels
127
+
128
+ Returns
129
+ -------
130
+ torch.Tensor
131
+ Output tensor of shape [*, I, J, C_in]
132
+
133
+ """
134
+ if mask is None:
135
+ # [*, I, J]
136
+ mask = x.new_ones(
137
+ x.shape[:-1],
138
+ )
139
+
140
+ if not self.starting:
141
+ x = x.transpose(-2, -3)
142
+ mask = mask.transpose(-1, -2)
143
+
144
+ # [*, I, J, C_in]
145
+ x = self.layer_norm(x)
146
+
147
+ # [*, I, 1, 1, J]
148
+ mask = mask[..., :, None, None, :]
149
+ mask_bias = self.inf * (mask - 1)
150
+
151
+ # [*, H, I, J]
152
+ triangle_bias = permute_final_dims(self.linear(x), (2, 0, 1))
153
+
154
+ # [*, 1, H, I, J]
155
+ triangle_bias = triangle_bias.unsqueeze(-4)
156
+
157
+ if chunk_size is not None and not use_kernels:
158
+ x = self._chunk(
159
+ x,
160
+ triangle_bias,
161
+ mask_bias,
162
+ mask,
163
+ chunk_size,
164
+ use_kernels=use_kernels,
165
+ )
166
+ else:
167
+ x = self.mha(
168
+ x,
169
+ x,
170
+ triangle_bias,
171
+ mask_bias,
172
+ mask,
173
+ use_kernels=use_kernels,
174
+ )
175
+
176
+ if not self.starting:
177
+ x = x.transpose(-2, -3)
178
+
179
+ return x
180
+
181
+
182
+ # Implements Algorithm 13
183
+ TriangleAttentionStartingNode = TriangleAttention
184
+
185
+
186
+ class TriangleAttentionEndingNode(TriangleAttention):
187
+ """Implement Algorithm 14."""
188
+
189
+ __init__ = partialmethod(TriangleAttention.__init__, starting=False)