difflayers 0.1.0__py3-none-any.whl
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.
- difflayers/__init__.py +965 -0
- difflayers/activation.py +339 -0
- difflayers/attention_operator.py +157 -0
- difflayers/auxiliary/__init__.py +0 -0
- difflayers/auxiliary/data.py +252 -0
- difflayers/diffused_attention.py +427 -0
- difflayers/diffusion.py +395 -0
- difflayers/dynamics_engine.py +540 -0
- difflayers/functional.py +459 -0
- difflayers/graph/__init__.py +18 -0
- difflayers/graph/build_graph.py +77 -0
- difflayers/graph/builder.py +120 -0
- difflayers/graph/laplacian.py +76 -0
- difflayers/graph/laplacian_builder.py +64 -0
- difflayers/transformer.py +212 -0
- difflayers-0.1.0.dist-info/METADATA +210 -0
- difflayers-0.1.0.dist-info/RECORD +20 -0
- difflayers-0.1.0.dist-info/WHEEL +5 -0
- difflayers-0.1.0.dist-info/licenses/LICENSE +79 -0
- difflayers-0.1.0.dist-info/top_level.txt +1 -0
difflayers/functional.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
|
|
4
|
+
from torch import Tensor
|
|
5
|
+
from typing import Optional, Tuple, Union
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def hopfield_core_forward(query, # type: Tensor
|
|
9
|
+
key, # type: Tensor
|
|
10
|
+
value, # type: Tensor
|
|
11
|
+
embed_dim_to_check, # type: int
|
|
12
|
+
num_heads, # type: int
|
|
13
|
+
in_proj_weight, # type: Optional[Tensor]
|
|
14
|
+
in_proj_bias, # type: Optional[Tensor]
|
|
15
|
+
bias_k, # type: Optional[Tensor]
|
|
16
|
+
bias_v, # type: Optional[Tensor]
|
|
17
|
+
add_zero_attn, # type: bool
|
|
18
|
+
dropout_p, # type: float
|
|
19
|
+
out_proj_weight, # type: Tensor
|
|
20
|
+
out_proj_bias, # type: Tensor
|
|
21
|
+
training=True, # type: bool
|
|
22
|
+
key_padding_mask=None, # type: Optional[Tensor]
|
|
23
|
+
need_weights=True, # type: bool
|
|
24
|
+
attn_mask=None, # type: Optional[Tensor]
|
|
25
|
+
use_separate_proj_weight=False, # type: bool
|
|
26
|
+
q_proj_weight=None, # type: Optional[Tensor]
|
|
27
|
+
k_proj_weight=None, # type: Optional[Tensor]
|
|
28
|
+
v_proj_weight=None, # type: Optional[Tensor]
|
|
29
|
+
static_k=None, # type: Optional[Tensor]
|
|
30
|
+
static_v=None, # type: Optional[Tensor]
|
|
31
|
+
|
|
32
|
+
key_as_static=False, # type: bool
|
|
33
|
+
query_as_static=False, # type: bool
|
|
34
|
+
value_as_static=False, # type: bool
|
|
35
|
+
value_as_connected=False, # type: bool
|
|
36
|
+
normalize_pattern=False, # type: bool
|
|
37
|
+
normalize_pattern_eps=1e-5, # type: float
|
|
38
|
+
p_norm_weight=None, # type: Optional[Tensor]
|
|
39
|
+
p_norm_bias=None, # type: Optional[Tensor]
|
|
40
|
+
head_dim=None, # type: Optional[int]
|
|
41
|
+
pattern_dim=None, # type: Optional[int]
|
|
42
|
+
scaling=None, # type: Optional[Union[float, Tensor]]
|
|
43
|
+
update_steps_max=0, # type: Optional[Union[int, Tensor]]
|
|
44
|
+
update_steps_eps=1e-4, # type: Union[float, Tensor]
|
|
45
|
+
return_raw_associations=False, # type: bool
|
|
46
|
+
return_projected_patterns=False # type: bool
|
|
47
|
+
):
|
|
48
|
+
# type: (...) -> Tuple[Tensor, Optional[Tensor]]
|
|
49
|
+
r"""
|
|
50
|
+
Args:
|
|
51
|
+
query, key, value: map a query and a set of key-value pairs to an output.
|
|
52
|
+
See "Attention Is All You Need" for more details.
|
|
53
|
+
See "Hopfield Networks is All You Need" for more details in the setting of Hopfield networks.
|
|
54
|
+
embed_dim_to_check: total dimension of the model (in case of default head dimension).
|
|
55
|
+
num_heads: parallel attention heads.
|
|
56
|
+
in_proj_weight, in_proj_bias: input projection weight and bias.
|
|
57
|
+
bias_k, bias_v: bias of the key and value sequences to be added at dim=0.
|
|
58
|
+
add_zero_attn: add a new batch of zeros to the key and
|
|
59
|
+
value sequences at dim=1.
|
|
60
|
+
dropout_p: probability of an element to be zeroed.
|
|
61
|
+
out_proj_weight, out_proj_bias: the output projection weight and bias.
|
|
62
|
+
training: apply dropout if is ``True``.
|
|
63
|
+
key_padding_mask: if provided, specified padding elements in the key will
|
|
64
|
+
be ignored by the attention. This is an binary mask. When the value is True,
|
|
65
|
+
the corresponding value on the attention layer will be filled with -inf.
|
|
66
|
+
need_weights: output attn_output_weights.
|
|
67
|
+
attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
|
|
68
|
+
the batches while a 3D mask allows to specify a different mask for the entries of each batch.
|
|
69
|
+
use_separate_proj_weight: the function accept the proj. weights for query, key,
|
|
70
|
+
and value in different forms. If false, in_proj_weight will be used, which is
|
|
71
|
+
a combination of q_proj_weight, k_proj_weight, v_proj_weight.
|
|
72
|
+
q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias.
|
|
73
|
+
static_k, static_v: static key and value used for attention operators.
|
|
74
|
+
|
|
75
|
+
key_as_static: interpret specified key as being static.
|
|
76
|
+
query_as_static: interpret specified key as being static.
|
|
77
|
+
value_as_static: interpret specified key as being static.
|
|
78
|
+
value_as_connected: connect value projection with key projection.
|
|
79
|
+
normalize_pattern: enable normalization of patterns.
|
|
80
|
+
normalize_pattern_eps: offset of the denominator for numerical stability.
|
|
81
|
+
p_norm_weight, p_norm_bias: pattern normalization weight and bias.
|
|
82
|
+
head_dim: dimensionality of each head.
|
|
83
|
+
pattern_dim: dimensionality of each projected value input.
|
|
84
|
+
scaling: scaling of association heads, often represented as beta (one entry per head).
|
|
85
|
+
update_steps_max: maximum count of association update steps (None equals to infinity).
|
|
86
|
+
update_steps_eps: minimum difference threshold between two consecutive association update steps.
|
|
87
|
+
return_raw_associations: return raw association (softmax) values, unmodified.
|
|
88
|
+
return_projected_patterns: return pattern projection values, unmodified.
|
|
89
|
+
|
|
90
|
+
Shape:
|
|
91
|
+
Inputs:
|
|
92
|
+
- query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
|
|
93
|
+
the embedding dimension.
|
|
94
|
+
- key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
|
|
95
|
+
the embedding dimension.
|
|
96
|
+
- value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
|
|
97
|
+
the embedding dimension.
|
|
98
|
+
- key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
|
|
99
|
+
If a ByteTensor is provided, the non-zero positions will be ignored while the zero positions
|
|
100
|
+
will be unchanged. If a BoolTensor is provided, the positions with the
|
|
101
|
+
value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
|
|
102
|
+
- attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
|
|
103
|
+
3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
|
|
104
|
+
S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked
|
|
105
|
+
positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend
|
|
106
|
+
while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``
|
|
107
|
+
are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
|
|
108
|
+
is provided, it will be added to the attention weight.
|
|
109
|
+
- static_k: :math:`(N*num_heads, S, head_dim)`, where S is the source sequence length, N is the batch size.
|
|
110
|
+
- static_v: :math:`(N*num_heads, S, head_dim)`, where S is the source sequence length, N is the batch size.
|
|
111
|
+
|
|
112
|
+
- scaling: :math:`(num_heads,)`, where num_heads is the amount of heads.
|
|
113
|
+
|
|
114
|
+
Outputs:
|
|
115
|
+
- attn_output: :math:`(L, N, E)`, where L is the target sequence length, N is the batch size,
|
|
116
|
+
E is the embedding dimension.
|
|
117
|
+
- attn_output_weights: :math:`(N, L, S)`, where N is the batch size,
|
|
118
|
+
L is the target sequence length, S is the source sequence length.
|
|
119
|
+
- attn_raw: :math:``(N, num_heads, L, S)`, where N is the batch size,
|
|
120
|
+
L is the target sequence length, S is the source sequence length.
|
|
121
|
+
"""
|
|
122
|
+
if not torch.jit.is_scripting():
|
|
123
|
+
tens_ops = (query, key, value, in_proj_weight, in_proj_bias, bias_k, bias_v,
|
|
124
|
+
out_proj_weight, out_proj_bias)
|
|
125
|
+
if any([type(t) is not Tensor for t in tens_ops]) and nn.functional.has_torch_function(tens_ops):
|
|
126
|
+
return nn.functional.handle_torch_function(
|
|
127
|
+
hopfield_core_forward, tens_ops, query, key, value,
|
|
128
|
+
embed_dim_to_check, num_heads, in_proj_weight, in_proj_bias,
|
|
129
|
+
bias_k, bias_v, add_zero_attn, dropout_p, out_proj_weight,
|
|
130
|
+
out_proj_bias, training=training, key_padding_mask=key_padding_mask,
|
|
131
|
+
need_weights=need_weights, attn_mask=attn_mask,
|
|
132
|
+
use_separate_proj_weight=use_separate_proj_weight,
|
|
133
|
+
q_proj_weight=q_proj_weight, k_proj_weight=k_proj_weight,
|
|
134
|
+
v_proj_weight=v_proj_weight, static_k=static_k, static_v=static_v,
|
|
135
|
+
key_as_static=key_as_static, query_as_static=query_as_static,
|
|
136
|
+
value_as_static=value_as_static, value_as_connected=value_as_connected,
|
|
137
|
+
normalize_pattern=normalize_pattern, normalize_pattern_eps=normalize_pattern_eps,
|
|
138
|
+
p_norm_weight=p_norm_weight, p_norm_bias=p_norm_bias,
|
|
139
|
+
head_dim=head_dim, pattern_dim=pattern_dim, scaling=scaling, update_steps_max=update_steps_max,
|
|
140
|
+
update_steps_eps=update_steps_eps, return_raw_associations=return_raw_associations)
|
|
141
|
+
tgt_len, bsz, embed_dim = query.shape[0], value.shape[1], query.shape[2]
|
|
142
|
+
assert embed_dim == embed_dim_to_check
|
|
143
|
+
# allow MHA to have different sizes for the feature dimension
|
|
144
|
+
assert key.size(0) == value.size(0) and key.size(1) == value.size(1)
|
|
145
|
+
|
|
146
|
+
assert (scaling is None) or (type(scaling) in (float, torch.Tensor))
|
|
147
|
+
if type(scaling) == torch.Tensor:
|
|
148
|
+
assert scaling.ndimension() == 1 and scaling.shape[0] == num_heads, "only one entry per head."
|
|
149
|
+
|
|
150
|
+
assert (update_steps_max is None) or (type(update_steps_max) in (int, torch.Tensor))
|
|
151
|
+
if type(update_steps_max) == torch.Tensor:
|
|
152
|
+
assert update_steps_max.ndimension() == 1 and update_steps_max.shape[0] == num_heads, "only one entry per head."
|
|
153
|
+
elif type(update_steps_max) == int:
|
|
154
|
+
update_steps_max = torch.tensor([update_steps_max] * num_heads, dtype=torch.int32, device=query.device)
|
|
155
|
+
elif update_steps_max is None:
|
|
156
|
+
update_steps_max = -torch.ones(size=(num_heads,), dtype=torch.int32, device=query.device)
|
|
157
|
+
|
|
158
|
+
assert type(update_steps_eps) in (float, torch.Tensor)
|
|
159
|
+
if type(update_steps_eps) == torch.Tensor:
|
|
160
|
+
assert update_steps_eps.ndimension() == 1 and update_steps_eps.shape[0] == num_heads, "only one entry per head."
|
|
161
|
+
assert (update_steps_eps <= 0.0).sum() == 0, "only positive thresholds allowed."
|
|
162
|
+
update_steps_eps = update_steps_eps.to(device=query.device)
|
|
163
|
+
elif type(update_steps_eps) == float:
|
|
164
|
+
assert update_steps_eps > 0, "only positive thresholds allowed."
|
|
165
|
+
update_steps_eps = torch.tensor([update_steps_eps] * num_heads, dtype=query.dtype, device=query.device)
|
|
166
|
+
|
|
167
|
+
# Adapt dimensionality of each each.
|
|
168
|
+
if head_dim is None:
|
|
169
|
+
head_dim = embed_dim // num_heads
|
|
170
|
+
assert head_dim * num_heads == embed_dim, r'embed_dim must be divisible by num_heads.'
|
|
171
|
+
hopfield_dim = num_heads * head_dim
|
|
172
|
+
|
|
173
|
+
# Adapt dimensionality of each value projection.
|
|
174
|
+
if pattern_dim is None:
|
|
175
|
+
pattern_dim = head_dim
|
|
176
|
+
assert (not value_as_connected) or (pattern_dim == head_dim)
|
|
177
|
+
|
|
178
|
+
q, k, v, xi, src_len = None, None, None, None, 0
|
|
179
|
+
update_step, xi_old, xi_difference_norm = 0, None, float(r'+inf')
|
|
180
|
+
update_active_heads = torch.tensor([[[True]]] * num_heads * bsz, device=query.device)
|
|
181
|
+
assert update_active_heads.any(), "at least one head needs to be active."
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
####################################################################################################################
|
|
187
|
+
# BEGIN HOPFIELD UPDATE ITERATION #
|
|
188
|
+
####################################################################################################################
|
|
189
|
+
|
|
190
|
+
while update_active_heads.any():
|
|
191
|
+
|
|
192
|
+
# The query is already projected into the "Hopfield" space at "update_step" equals 0.
|
|
193
|
+
# No more projection necessary if "update_step" greater than 0.
|
|
194
|
+
if update_step == 0:
|
|
195
|
+
if not use_separate_proj_weight:
|
|
196
|
+
|
|
197
|
+
if torch.equal(query, key) and torch.equal(key, value) and not (
|
|
198
|
+
key_as_static or query_as_static or value_as_static):
|
|
199
|
+
# self-attention
|
|
200
|
+
q, k, v = nn.functional.linear(query, in_proj_weight, in_proj_bias).chunk(3, dim=-1)
|
|
201
|
+
|
|
202
|
+
elif torch.equal(key, value) and not (key_as_static or value_as_static):
|
|
203
|
+
# encoder-decoder attention
|
|
204
|
+
_start, _end = 0, hopfield_dim
|
|
205
|
+
if query_as_static:
|
|
206
|
+
q = query.repeat(1, num_heads, 1)
|
|
207
|
+
else:
|
|
208
|
+
# This is inline in_proj function with in_proj_weight and in_proj_bias
|
|
209
|
+
_b = in_proj_bias
|
|
210
|
+
_w = in_proj_weight[_start:_end, :]
|
|
211
|
+
if _b is not None:
|
|
212
|
+
_b = _b[_start:_end]
|
|
213
|
+
q = nn.functional.linear(query, _w, _b)
|
|
214
|
+
_start = hopfield_dim
|
|
215
|
+
_end = None
|
|
216
|
+
|
|
217
|
+
if key is None:
|
|
218
|
+
assert value is None
|
|
219
|
+
k = None
|
|
220
|
+
v = None
|
|
221
|
+
else:
|
|
222
|
+
|
|
223
|
+
# This is inline in_proj function with in_proj_weight and in_proj_bias
|
|
224
|
+
_b = in_proj_bias
|
|
225
|
+
_w = in_proj_weight[_start:_end, :]
|
|
226
|
+
if _b is not None:
|
|
227
|
+
_b = _b[_start:_end]
|
|
228
|
+
k, v = nn.functional.linear(key, _w, _b).chunk(2, dim=-1)
|
|
229
|
+
|
|
230
|
+
else:
|
|
231
|
+
_start, _end = 0, hopfield_dim
|
|
232
|
+
if query_as_static:
|
|
233
|
+
q = query.repeat(1, num_heads, 1)
|
|
234
|
+
else:
|
|
235
|
+
# This is inline in_proj function with in_proj_weight and in_proj_bias
|
|
236
|
+
_b = in_proj_bias
|
|
237
|
+
_w = in_proj_weight[_start:_end, :]
|
|
238
|
+
if _b is not None:
|
|
239
|
+
_b = _b[_start:_end]
|
|
240
|
+
q = nn.functional.linear(query, _w, _b)
|
|
241
|
+
_start += hopfield_dim
|
|
242
|
+
_end += hopfield_dim
|
|
243
|
+
|
|
244
|
+
if key_as_static:
|
|
245
|
+
k = key.repeat(1, num_heads, 1)
|
|
246
|
+
else:
|
|
247
|
+
# This is inline in_proj function with in_proj_weight and in_proj_bias
|
|
248
|
+
_b = in_proj_bias
|
|
249
|
+
_w = in_proj_weight[_start:_end, :]
|
|
250
|
+
if _b is not None:
|
|
251
|
+
_b = _b[_start:_end]
|
|
252
|
+
k = nn.functional.linear(key, _w, _b)
|
|
253
|
+
_start += hopfield_dim
|
|
254
|
+
_end += hopfield_dim
|
|
255
|
+
|
|
256
|
+
if value_as_static:
|
|
257
|
+
v = value.repeat(1, num_heads, 1)
|
|
258
|
+
else:
|
|
259
|
+
# This is inline in_proj function with in_proj_weight and in_proj_bias
|
|
260
|
+
_b = in_proj_bias
|
|
261
|
+
_w = in_proj_weight[_start:_end, :]
|
|
262
|
+
if _b is not None:
|
|
263
|
+
_b = _b[_start:_end]
|
|
264
|
+
v = nn.functional.linear(value, _w, _b)
|
|
265
|
+
else:
|
|
266
|
+
_start, _end = 0, hopfield_dim
|
|
267
|
+
if query_as_static:
|
|
268
|
+
q = query.repeat(1, num_heads, 1)
|
|
269
|
+
else:
|
|
270
|
+
q_proj_weight_non_opt = torch.jit._unwrap_optional(q_proj_weight)
|
|
271
|
+
len1, len2 = q_proj_weight_non_opt.size()
|
|
272
|
+
assert len1 == hopfield_dim and len2 == query.size(-1)
|
|
273
|
+
if in_proj_bias is not None:
|
|
274
|
+
q = nn.functional.linear(query, q_proj_weight_non_opt, in_proj_bias[_start:_end])
|
|
275
|
+
_start += hopfield_dim
|
|
276
|
+
_end += hopfield_dim
|
|
277
|
+
else:
|
|
278
|
+
q = nn.functional.linear(query, q_proj_weight_non_opt, in_proj_bias)
|
|
279
|
+
|
|
280
|
+
v = value
|
|
281
|
+
if key_as_static:
|
|
282
|
+
k = key.repeat(1, num_heads, 1)
|
|
283
|
+
else:
|
|
284
|
+
k_proj_weight_non_opt = torch.jit._unwrap_optional(k_proj_weight)
|
|
285
|
+
len1, len2 = k_proj_weight_non_opt.size()
|
|
286
|
+
assert len1 == hopfield_dim and len2 == key.size(-1)
|
|
287
|
+
|
|
288
|
+
_bias = None if in_proj_bias is None else in_proj_bias[_start:_end]
|
|
289
|
+
k = nn.functional.linear(key, k_proj_weight_non_opt, _bias)
|
|
290
|
+
if value_as_connected:
|
|
291
|
+
v = nn.functional.linear(v, k_proj_weight_non_opt, _bias)
|
|
292
|
+
_start += hopfield_dim
|
|
293
|
+
_end += num_heads * pattern_dim
|
|
294
|
+
|
|
295
|
+
if value_as_static:
|
|
296
|
+
if not (value_as_connected or key_as_static):
|
|
297
|
+
v = v.repeat(1, num_heads, 1)
|
|
298
|
+
else:
|
|
299
|
+
v_proj_weight_non_opt = torch.jit._unwrap_optional(v_proj_weight)
|
|
300
|
+
len1, len2 = v_proj_weight_non_opt.size()
|
|
301
|
+
assert len1 == (num_heads * pattern_dim) and len2 == v.size(-1)
|
|
302
|
+
if in_proj_bias is not None:
|
|
303
|
+
v = nn.functional.linear(v, v_proj_weight_non_opt, in_proj_bias[_start:])
|
|
304
|
+
else:
|
|
305
|
+
v = nn.functional.linear(v, v_proj_weight_non_opt, in_proj_bias)
|
|
306
|
+
|
|
307
|
+
if attn_mask is not None:
|
|
308
|
+
assert attn_mask.dtype == torch.float32 or attn_mask.dtype == torch.float64 or \
|
|
309
|
+
attn_mask.dtype == torch.float16 or attn_mask.dtype == torch.uint8 or \
|
|
310
|
+
attn_mask.dtype == torch.bool, \
|
|
311
|
+
'Only float, byte, and bool types are supported for attn_mask, not {}'.format(attn_mask.dtype)
|
|
312
|
+
if attn_mask.dtype == torch.uint8:
|
|
313
|
+
warnings.warn(
|
|
314
|
+
"Byte tensor for attn_mask in nn.HopfieldCore is deprecated. Use bool tensor instead.")
|
|
315
|
+
attn_mask = attn_mask.to(torch.bool)
|
|
316
|
+
|
|
317
|
+
if attn_mask.dim() == 2:
|
|
318
|
+
attn_mask = attn_mask.unsqueeze(0)
|
|
319
|
+
if list(attn_mask.size()) != [1, query.size(0), key.size(0)]:
|
|
320
|
+
raise RuntimeError('The size of the 2D attn_mask is not correct.')
|
|
321
|
+
elif attn_mask.dim() == 3:
|
|
322
|
+
if list(attn_mask.size()) != [bsz * num_heads, query.size(0), key.size(0)]:
|
|
323
|
+
raise RuntimeError('The size of the 3D attn_mask is not correct.')
|
|
324
|
+
else:
|
|
325
|
+
raise RuntimeError("attn_mask's dimension {} is not supported".format(attn_mask.dim()))
|
|
326
|
+
# attn_mask's dim is 3 now.
|
|
327
|
+
|
|
328
|
+
# Optionally normalize patterns.
|
|
329
|
+
if normalize_pattern:
|
|
330
|
+
q = torch.nn.functional.layer_norm(
|
|
331
|
+
input=q.reshape(shape=(-1, head_dim)), normalized_shape=(head_dim,),
|
|
332
|
+
weight=p_norm_weight, bias=p_norm_bias, eps=normalize_pattern_eps).reshape(shape=q.shape)
|
|
333
|
+
k = torch.nn.functional.layer_norm(
|
|
334
|
+
input=k.reshape(shape=(-1, head_dim)), normalized_shape=(head_dim,),
|
|
335
|
+
weight=p_norm_weight, bias=p_norm_bias, eps=normalize_pattern_eps).reshape(shape=k.shape)
|
|
336
|
+
|
|
337
|
+
else:
|
|
338
|
+
active_xi = xi.masked_select(mask=update_active_heads).view(size=(-1, *xi.shape[1:]))
|
|
339
|
+
active_k = k.masked_select(mask=update_active_heads).view(size=(-1, *k.shape[1:]))
|
|
340
|
+
q = torch.masked_scatter(input=q, mask=update_active_heads, source=torch.bmm(active_xi, active_k))
|
|
341
|
+
|
|
342
|
+
# Optionally scale association heads (each head separately).
|
|
343
|
+
if type(scaling) == float:
|
|
344
|
+
q = q * scaling
|
|
345
|
+
elif type(scaling) == torch.Tensor:
|
|
346
|
+
q = q * scaling.view(1, 1, -1).repeat(repeats=(1, 1, q.shape[2] // scaling.shape[0]))
|
|
347
|
+
|
|
348
|
+
if update_step == 0:
|
|
349
|
+
# convert ByteTensor key_padding_mask to bool
|
|
350
|
+
if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8:
|
|
351
|
+
warnings.warn(
|
|
352
|
+
"Byte tensor for key_padding_mask in nn.HopfieldCore is deprecated. Use bool tensor instead.")
|
|
353
|
+
key_padding_mask = key_padding_mask.to(torch.bool)
|
|
354
|
+
|
|
355
|
+
if bias_k is not None and bias_v is not None:
|
|
356
|
+
if static_k is None and static_v is None and key_as_static is None and value_as_static is None:
|
|
357
|
+
k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
|
|
358
|
+
v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
|
|
359
|
+
if attn_mask is not None:
|
|
360
|
+
attn_mask = nn.functional.pad(attn_mask, [0, 1])
|
|
361
|
+
if key_padding_mask is not None:
|
|
362
|
+
key_padding_mask = nn.functional.pad(key_padding_mask, [0, 1])
|
|
363
|
+
else:
|
|
364
|
+
assert static_k is None, "bias cannot be added to static key."
|
|
365
|
+
assert static_v is None, "bias cannot be added to static value."
|
|
366
|
+
assert not key_as_static, "bias cannot be added to static key."
|
|
367
|
+
assert not value_as_static, "bias cannot be added to static value."
|
|
368
|
+
else:
|
|
369
|
+
assert bias_k is None
|
|
370
|
+
assert bias_v is None
|
|
371
|
+
|
|
372
|
+
q = q.contiguous().view(tgt_len, -1, head_dim).transpose(0, 1)
|
|
373
|
+
if k is not None:
|
|
374
|
+
k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1)
|
|
375
|
+
if v is not None:
|
|
376
|
+
v = v.contiguous().view(v.shape[0], bsz * num_heads, -1).transpose(0, 1)
|
|
377
|
+
|
|
378
|
+
if static_k is not None:
|
|
379
|
+
assert static_k.size(0) == bsz * num_heads
|
|
380
|
+
assert static_k.size(2) == head_dim
|
|
381
|
+
k = static_k
|
|
382
|
+
|
|
383
|
+
if static_v is not None:
|
|
384
|
+
assert static_v.size(0) == bsz * num_heads
|
|
385
|
+
assert static_v.size(2) == pattern_dim
|
|
386
|
+
v = static_v
|
|
387
|
+
|
|
388
|
+
src_len = k.size(1)
|
|
389
|
+
|
|
390
|
+
if key_padding_mask is not None:
|
|
391
|
+
assert key_padding_mask.size(0) == bsz
|
|
392
|
+
assert key_padding_mask.size(1) == src_len
|
|
393
|
+
|
|
394
|
+
if add_zero_attn:
|
|
395
|
+
src_len += 1
|
|
396
|
+
k = torch.cat([k, torch.zeros((k.size(0), 1) + k.size()[2:], dtype=k.dtype, device=k.device)], dim=1)
|
|
397
|
+
v = torch.cat([v, torch.zeros((v.size(0), 1) + v.size()[2:], dtype=v.dtype, device=v.device)], dim=1)
|
|
398
|
+
if attn_mask is not None:
|
|
399
|
+
attn_mask = nn.functional.pad(attn_mask, [0, 1])
|
|
400
|
+
if key_padding_mask is not None:
|
|
401
|
+
key_padding_mask = nn.functional.pad(key_padding_mask, [0, 1])
|
|
402
|
+
|
|
403
|
+
attn_output_weights = torch.bmm(q, k.transpose(1, 2))
|
|
404
|
+
assert list(attn_output_weights.size()) == [bsz * num_heads, tgt_len, src_len]
|
|
405
|
+
|
|
406
|
+
if attn_mask is not None:
|
|
407
|
+
if attn_mask.dtype == torch.bool:
|
|
408
|
+
attn_output_weights.masked_fill_(attn_mask, float('-inf'))
|
|
409
|
+
else:
|
|
410
|
+
attn_output_weights += attn_mask
|
|
411
|
+
|
|
412
|
+
if key_padding_mask is not None:
|
|
413
|
+
attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
|
|
414
|
+
attn_output_weights = attn_output_weights.masked_fill(
|
|
415
|
+
key_padding_mask.unsqueeze(1).unsqueeze(2),
|
|
416
|
+
float('-inf'),
|
|
417
|
+
)
|
|
418
|
+
attn_output_weights = attn_output_weights.view(bsz * num_heads, tgt_len, src_len)
|
|
419
|
+
|
|
420
|
+
# Compute new xi for Hopfield retrieve iterations.
|
|
421
|
+
if xi is None:
|
|
422
|
+
xi = nn.functional.softmax(attn_output_weights, dim=-1)
|
|
423
|
+
else:
|
|
424
|
+
xi = torch.masked_scatter(input=xi, mask=update_active_heads, source=nn.functional.softmax(
|
|
425
|
+
attn_output_weights.masked_select(mask=update_active_heads).view(size=(-1, *xi.shape[1:])), dim=-1))
|
|
426
|
+
|
|
427
|
+
# Compute threshold-based stopping criterion for Hopfield retrieve iterations.
|
|
428
|
+
with torch.no_grad():
|
|
429
|
+
xi_active = xi.view(size=(bsz, num_heads, tgt_len, src_len))
|
|
430
|
+
update_active_heads = (update_step < update_steps_max) | (update_steps_max < 0)
|
|
431
|
+
if xi_old is not None:
|
|
432
|
+
update_active_heads &= ((xi_old - xi_active).norm(p=2, dim=(2, 3)).max(axis=0)[0]) > update_steps_eps
|
|
433
|
+
update_active_heads = update_active_heads.unsqueeze(dim=1).unsqueeze(dim=2).repeat(repeats=(bsz, 1, 1))
|
|
434
|
+
xi_old = xi_active
|
|
435
|
+
update_step += 1
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
####################################################################################################################
|
|
441
|
+
# END HOPFIELD UPDATE ITERATION #
|
|
442
|
+
####################################################################################################################
|
|
443
|
+
|
|
444
|
+
attn_output_weights = nn.functional.dropout(xi, p=dropout_p, training=training)
|
|
445
|
+
attn_output = torch.bmm(attn_output_weights, v)
|
|
446
|
+
assert list(attn_output.shape[:2]) == [bsz * num_heads, tgt_len]
|
|
447
|
+
attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, -1)
|
|
448
|
+
if out_proj_weight is not None:
|
|
449
|
+
assert attn_output.shape[2] == num_heads * pattern_dim
|
|
450
|
+
attn_output = nn.functional.linear(attn_output, out_proj_weight, out_proj_bias)
|
|
451
|
+
|
|
452
|
+
xi = xi.view(bsz, num_heads, tgt_len, src_len) if return_raw_associations else None
|
|
453
|
+
v = v.view(bsz, num_heads, src_len, -1) if return_projected_patterns else None
|
|
454
|
+
if need_weights:
|
|
455
|
+
# average attention weights over heads
|
|
456
|
+
attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
|
|
457
|
+
return attn_output, attn_output_weights.sum(dim=1) / num_heads, xi, v
|
|
458
|
+
else:
|
|
459
|
+
return attn_output, None, xi, v
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from .build_graph import build_similarity_matrix, build_knn_graph
|
|
2
|
+
from .builder import GraphBuilder
|
|
3
|
+
from .laplacian import compute_laplacian, compute_normalized_laplacian
|
|
4
|
+
from .laplacian_builder import LaplacianBuilder
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"build_similarity_matrix",
|
|
8
|
+
"build_knn_graph",
|
|
9
|
+
"GraphBuilder",
|
|
10
|
+
"compute_laplacian",
|
|
11
|
+
"compute_normalized_laplacian",
|
|
12
|
+
"LaplacianBuilder",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
# GraphBuilder.build(X) -> (W, deg, adj_indices)
|
|
16
|
+
# LaplacianBuilder.build(W) -> L (dense)
|
|
17
|
+
# build_knn_graph now accepts as_sparse=True to return a torch.sparse_coo_tensor.
|
|
18
|
+
# compute_laplacian / compute_normalized_laplacian accept sparse_coo input.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Graph construction utilities for Graph-Regularized Hopfield attention.
|
|
3
|
+
|
|
4
|
+
Responsibility: Build a kNN similarity graph from pattern embeddings.
|
|
5
|
+
|
|
6
|
+
Builds similarity graphs over pattern sets (stored patterns / queries) used
|
|
7
|
+
to construct the graph Laplacian for diffusion pre-processing.
|
|
8
|
+
|
|
9
|
+
Supports dense output (default) and torch.sparse_coo output for O(kN)
|
|
10
|
+
Laplacian-vector products at inference time.
|
|
11
|
+
|
|
12
|
+
Complexity:
|
|
13
|
+
build_similarity_matrix : O(N²d)
|
|
14
|
+
build_knn_graph (dense) : O(N²)
|
|
15
|
+
build_knn_graph (sparse) : O(kN) storage
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import torch
|
|
19
|
+
import torch.nn.functional as F
|
|
20
|
+
from torch import Tensor
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def build_similarity_matrix(X: Tensor) -> Tensor:
|
|
24
|
+
"""
|
|
25
|
+
Compute pairwise cosine similarity matrix, clamping negatives to zero
|
|
26
|
+
and zeroing out the diagonal (no self-loops).
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
X: (N, d) float32 embedding matrix.
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
S: (N, N) dense, non-negative cosine similarity matrix.
|
|
33
|
+
|
|
34
|
+
Complexity: O(N²d) time, O(N²) space.
|
|
35
|
+
"""
|
|
36
|
+
X_norm = F.normalize(X.float(), p=2, dim=-1) # (N, d)
|
|
37
|
+
S = X_norm @ X_norm.t() # (N, N)
|
|
38
|
+
S = S.clamp(min=0.0)
|
|
39
|
+
S.fill_diagonal_(0.0)
|
|
40
|
+
return S
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def build_knn_graph(S: Tensor, k: int, as_sparse: bool = False) -> Tensor:
|
|
44
|
+
"""
|
|
45
|
+
Sparsify a similarity matrix so that each node retains only its top-k
|
|
46
|
+
neighbors; adjacency is symmetrized (undirected graph).
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
S: (N, N) similarity matrix.
|
|
50
|
+
k: Number of neighbors to keep per node.
|
|
51
|
+
as_sparse: If True, return a torch.sparse_coo_tensor instead of
|
|
52
|
+
a dense tensor. Enables O(kN) sparse matmuls downstream.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
A: (N, N) symmetric adjacency matrix, dense or sparse_coo.
|
|
56
|
+
|
|
57
|
+
Complexity: O(N²) time for topk; O(kN) storage when as_sparse=True.
|
|
58
|
+
"""
|
|
59
|
+
N = S.shape[0]
|
|
60
|
+
k = min(k, N - 1)
|
|
61
|
+
|
|
62
|
+
# Select top-k similarities per row — O(N²) due to full topk scan.
|
|
63
|
+
topk_vals, topk_idx = torch.topk(S, k=k, dim=-1) # (N, k)
|
|
64
|
+
|
|
65
|
+
mask = torch.zeros_like(S)
|
|
66
|
+
mask.scatter_(dim=-1, index=topk_idx, src=topk_vals)
|
|
67
|
+
|
|
68
|
+
# Symmetrize: A_ij = max(A_ij, A_ji) — preserves all chosen edges.
|
|
69
|
+
A = torch.max(mask, mask.t())
|
|
70
|
+
|
|
71
|
+
if as_sparse:
|
|
72
|
+
# Convert to COO sparse for efficient downstream L @ X products.
|
|
73
|
+
indices = A.nonzero(as_tuple=False).t().contiguous() # (2, nnz)
|
|
74
|
+
values = A[indices[0], indices[1]]
|
|
75
|
+
return torch.sparse_coo_tensor(indices, values, A.shape,
|
|
76
|
+
dtype=A.dtype, device=A.device).coalesce()
|
|
77
|
+
return A
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Graph builder for Graph-Regularized Hopfield attention.
|
|
3
|
+
|
|
4
|
+
Responsibility: Build the kNN similarity graph (adjacency W and degree vector)
|
|
5
|
+
from raw pattern embeddings. This is the *only* class that calls
|
|
6
|
+
``build_similarity_matrix`` and ``build_knn_graph``.
|
|
7
|
+
|
|
8
|
+
Separating graph construction from Laplacian computation and diffusion
|
|
9
|
+
satisfies Single-Responsibility (SOLID) and avoids duplicated graph logic (DRY).
|
|
10
|
+
|
|
11
|
+
Usage::
|
|
12
|
+
|
|
13
|
+
builder = GraphBuilder(k=5, use_sparse=True)
|
|
14
|
+
W, deg, adj_idx = builder.build(X) # X: (N, d)
|
|
15
|
+
|
|
16
|
+
Complexity:
|
|
17
|
+
build_similarity_matrix : O(N²d)
|
|
18
|
+
build_knn_graph (dense) : O(N²) — topk + symmetrize
|
|
19
|
+
build_knn_graph (sparse): O(kN) storage
|
|
20
|
+
degree computation : O(N)
|
|
21
|
+
adj_indices extraction : O(kN)
|
|
22
|
+
|
|
23
|
+
Memory:
|
|
24
|
+
dense : O(N²)
|
|
25
|
+
sparse : O(kN) for W; O(N) for deg; O(kN) for adj_indices
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
from typing import Optional, Tuple
|
|
31
|
+
|
|
32
|
+
import torch
|
|
33
|
+
from torch import Tensor
|
|
34
|
+
|
|
35
|
+
from .build_graph import build_knn_graph, build_similarity_matrix
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class GraphBuilder:
|
|
39
|
+
"""
|
|
40
|
+
Builds kNN adjacency matrix W, degree vector, and neighbor-index table
|
|
41
|
+
from pattern embeddings.
|
|
42
|
+
|
|
43
|
+
The neighbor-index table (adj_indices) is the (N, k) integer tensor
|
|
44
|
+
required by graph-constrained attention (``AttentionOperator`` in graph
|
|
45
|
+
mode) to avoid forming the full N×N weight matrix.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
k: Number of nearest neighbors per node.
|
|
49
|
+
use_sparse: Return W as ``torch.sparse_coo_tensor`` (O(kN) storage).
|
|
50
|
+
Enables O(kN) sparse matmuls in ``FactoredDiffusion``.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, k: int = 5, use_sparse: bool = False) -> None:
|
|
54
|
+
self.k = k
|
|
55
|
+
self.use_sparse = use_sparse
|
|
56
|
+
|
|
57
|
+
def build(self, X: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
|
|
58
|
+
"""
|
|
59
|
+
Build adjacency W, degree deg, and neighbor index table from X.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
X: (N, d) float32 pattern embeddings.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
W: (N, N) adjacency matrix — dense float or sparse_coo.
|
|
66
|
+
deg: (N,) degree vector, float32 (row sums of dense W).
|
|
67
|
+
adj_indices:(N, k) LongTensor of kNN neighbor indices (dense W).
|
|
68
|
+
Required by ``AttentionOperator(mode='graph')``.
|
|
69
|
+
|
|
70
|
+
Complexity: O(N²d) + O(N²) + O(kN).
|
|
71
|
+
"""
|
|
72
|
+
S = build_similarity_matrix(X) # O(N²d)
|
|
73
|
+
N = S.shape[0]
|
|
74
|
+
k_actual = min(self.k, N - 1)
|
|
75
|
+
|
|
76
|
+
if self.use_sparse:
|
|
77
|
+
# BUG-7 fix: build sparse W directly from topk of S, avoiding
|
|
78
|
+
# the O(N²) full N×N W_dense intermediate that the dense path
|
|
79
|
+
# would otherwise materialise before conversion to sparse.
|
|
80
|
+
topk_vals, topk_idx = torch.topk(S, k=k_actual, dim=-1) # (N, k)
|
|
81
|
+
|
|
82
|
+
# adj_indices: kNN neighbor table from pre-symmetrisation topk.
|
|
83
|
+
adj_indices = topk_idx # (N, k)
|
|
84
|
+
|
|
85
|
+
# Symmetrize: include both directed halves of each edge.
|
|
86
|
+
row_idx = (
|
|
87
|
+
torch.arange(N, device=X.device)
|
|
88
|
+
.unsqueeze(1)
|
|
89
|
+
.expand(-1, k_actual)
|
|
90
|
+
.reshape(-1)
|
|
91
|
+
) # (N*k,)
|
|
92
|
+
col_idx = topk_idx.reshape(-1) # (N*k,)
|
|
93
|
+
vals = topk_vals.reshape(-1) # (N*k,)
|
|
94
|
+
|
|
95
|
+
all_rows = torch.cat([row_idx, col_idx]) # (2*N*k,)
|
|
96
|
+
all_cols = torch.cat([col_idx, row_idx]) # (2*N*k,)
|
|
97
|
+
all_vals = torch.cat([vals, vals]) # (2*N*k,)
|
|
98
|
+
|
|
99
|
+
# Coalesce sums duplicate (i,j) entries; the resulting W is
|
|
100
|
+
# symmetric and non-negative — sufficient for diffusion/Laplacian.
|
|
101
|
+
W: Tensor = torch.sparse_coo_tensor(
|
|
102
|
+
torch.stack([all_rows, all_cols]),
|
|
103
|
+
all_vals,
|
|
104
|
+
(N, N),
|
|
105
|
+
dtype=S.dtype,
|
|
106
|
+
device=S.device,
|
|
107
|
+
).coalesce()
|
|
108
|
+
|
|
109
|
+
# Degree from sparse row sums — O(kN), no N×N buffer.
|
|
110
|
+
deg = torch.zeros(N, dtype=S.dtype, device=S.device)
|
|
111
|
+
deg.scatter_add_(0, all_rows, all_vals) # (N,)
|
|
112
|
+
else:
|
|
113
|
+
W_dense = build_knn_graph(S, k=k_actual, as_sparse=False)
|
|
114
|
+
deg = W_dense.sum(dim=1) # (N,)
|
|
115
|
+
adj_indices = torch.topk(
|
|
116
|
+
W_dense, k=k_actual, dim=1
|
|
117
|
+
).indices # (N, k)
|
|
118
|
+
W = W_dense
|
|
119
|
+
|
|
120
|
+
return W, deg, adj_indices
|