yaojin17 commited on
Commit
9aedabe
·
verified ·
1 Parent(s): ad212ba

Speed up the correspondence adapters (fused attention, no host syncs, one weight cast per call)

Browse files
click3r/correspondence_adapter.py CHANGED
@@ -1,30 +1,42 @@
1
- import math
2
  from typing import Optional, Tuple
3
  import torch
4
  import torch.nn as nn
 
5
  from torch import Tensor
6
 
7
  from segment_anything.modeling.transformer import TwoWayTransformer
8
  from click3r.correspondence_encoder import CorrespondenceEncoder
9
 
10
 
11
- def _attention_without_padded_keys(attention, q, k, v, padded_keys):
12
- """SAM's Attention.forward with padded keys left out of the softmax."""
13
- q = attention._separate_heads(attention.q_proj(q), attention.num_heads)
14
- k = attention._separate_heads(attention.k_proj(k), attention.num_heads)
15
- v = attention._separate_heads(attention.v_proj(v), attention.num_heads)
16
- attn = q @ k.permute(0, 1, 3, 2) / math.sqrt(q.shape[-1])
17
- attn = attn.masked_fill(padded_keys, float("-inf"))
18
- out = torch.softmax(attn, dim=-1) @ v
19
- return attention.out_proj(attention._recombine_heads(out))
 
 
 
 
 
 
 
 
 
 
20
 
21
 
22
  class CorrespondenceAdapter(nn.Module):
23
  """
24
- Sparse prompting adapter. Training runs the prompted samples of a batch through
25
- the two-way transformer at once; evaluation runs them one by one. Both compute
26
- the same function up to rounding, and rounding depends on the batch shape, so
27
- evaluation stays per-sample to keep its results independent of batching.
 
 
28
  Inputs:
29
  image_tokens: (B,N,C) tokens AFTER DUSt3R decoder_embed, BEFORE dec_blocks
30
  coords_xy: (B,P,2) pixel (x,y)
@@ -63,6 +75,12 @@ class CorrespondenceAdapter(nn.Module):
63
  num_heads=transformer_heads,
64
  mlp_dim=transformer_mlp_dim,
65
  )
 
 
 
 
 
 
66
 
67
  def _image_position_encoding(self, token_positions: Optional[Tensor]) -> Tensor:
68
  """
@@ -94,42 +112,34 @@ class CorrespondenceAdapter(nn.Module):
94
  token_positions
95
  ) # (B,C,H,W)
96
 
97
- def _update_image_tokens(
98
- self,
99
- image_tokens: Tensor,
100
- image_position_encoding: Tensor,
101
- prompt_tokens: Tensor,
102
- ) -> Tensor:
103
- """
104
- Single-sample Two-Way call.
105
- image_tokens: (1,N,C)
106
- image_position_encoding: (1,C,H,W)
107
- prompt_tokens: (1,P,C)
108
- Returns updated (1,N,C)
109
- """
110
- Ht, Wt = self.image_embedding_size
111
- # reshape tokens to SAM's (B,C,H,W)
112
- image_features = (
113
- image_tokens.view(1, Ht, Wt, self.embed_dim)
114
- .permute(0, 3, 1, 2)
115
- .contiguous()
116
- )
117
-
118
- # TwoWayTransformer forward signature in SAM:
119
- # returns (updated_points, updated_image) = (queries, keys)
120
- _, updated_tokens = self.transformer(
121
- image_features, image_position_encoding, prompt_tokens
122
- )
123
 
124
- # updated_tokens is already (1,N,C) from TwoWayTransformer
125
- return updated_tokens
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
  def _update_image_tokens_batched(
128
  self,
129
  image_tokens: Tensor, # (B,N,C)
130
  image_position_encoding: Tensor, # (B,C,H,W)
131
  prompt_tokens: Tensor, # (B,P,C)
132
- padded: Tensor, # (B,P) bool; True rows are padding
133
  ) -> Tensor:
134
  """TwoWayTransformer.forward, keeping padded prompts out of attention as keys.
135
 
@@ -140,30 +150,47 @@ class CorrespondenceAdapter(nn.Module):
140
  key_pe = image_position_encoding.flatten(2).permute(0, 2, 1)
141
  queries = prompt_tokens
142
  query_pe = prompt_tokens
143
- padded_keys = padded[:, None, None, :]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  for layer in self.transformer.layers:
145
  if layer.skip_first_layer_pe:
146
- queries = _attention_without_padded_keys(
147
- layer.self_attn, queries, queries, queries, padded_keys
148
  )
149
  else:
150
  q = queries + query_pe
151
- queries = queries + _attention_without_padded_keys(
152
- layer.self_attn, q, q, queries, padded_keys
153
  )
154
  queries = layer.norm1(queries)
155
  q = queries + query_pe
156
  k = keys + key_pe
157
  queries = layer.norm2(
158
- queries + layer.cross_attn_token_to_image(q=q, k=k, v=keys)
 
159
  )
160
- queries = layer.norm3(queries + layer.mlp(queries))
 
 
161
  q = queries + query_pe
162
- k = keys + key_pe
163
  keys = layer.norm4(
164
  keys
165
- + _attention_without_padded_keys(
166
- layer.cross_attn_image_to_token, k, q, queries, padded_keys
167
  )
168
  )
169
  return keys
@@ -188,15 +215,16 @@ class CorrespondenceAdapter(nn.Module):
188
  token_positions
189
  ) # (B,C,H,W)
190
 
191
- if self.training:
192
- valid = (
193
- torch.ones(
194
- B, coords_xy.shape[1], dtype=torch.bool, device=image_tokens.device
195
- )
196
- if valid_mask is None
197
- else valid_mask
198
  )
199
- prompted = valid.any(dim=1)
 
 
 
 
 
200
  if not prompted.any():
201
  return image_tokens
202
  prompt_tokens = self.correspondence_encoder.encode_points(
@@ -209,49 +237,23 @@ class CorrespondenceAdapter(nn.Module):
209
  image_tokens[prompted],
210
  image_position_encoding[prompted],
211
  prompt_tokens,
212
- ~valid[prompted],
213
  )
214
  # Under autocast the updated tokens are wider than the input ones.
215
  out = image_tokens.to(updated.dtype, copy=True)
216
  out[prompted] = updated
217
  return out
218
 
219
- out = []
220
- for b in range(B):
221
- # choose valid rows for this sample
222
- if valid_mask is None:
223
- use = torch.ones(
224
- coords_xy.shape[1], dtype=torch.bool, device=image_tokens.device
225
- )
226
- else:
227
- use = valid_mask[b]
228
- num_valid_prompts = int(use.sum().item())
229
-
230
- if num_valid_prompts == 0:
231
- # identity for this sample (no prompt tokens)
232
- out.append(image_tokens[b])
233
- continue
234
-
235
- sample_coords = coords_xy[b : b + 1, use, :] # (1,Pv,2)
236
- sample_image_ids = image_ids[b : b + 1, use] # (1,Pv)
237
- sample_pair_ids = pair_ids[b : b + 1, use] # (1,Pv)
238
- sample_sizes = image_sizes[b : b + 1] # (1,2)
239
-
240
- prompt_tokens = self.correspondence_encoder.encode_points(
241
- sample_coords,
242
- sample_image_ids,
243
- sample_pair_ids,
244
- image_sizes=sample_sizes,
245
- ) # (1,Pv,C)
246
-
247
- sample_position_encoding = image_position_encoding[b : b + 1] # (1,C,H,W)
248
- sample_tokens = image_tokens[b : b + 1] # (1,N,C)
249
-
250
- # Directly use prompt-conditioned features
251
- updated_tokens = self._update_image_tokens(
252
- sample_tokens, sample_position_encoding, prompt_tokens
253
- )
254
-
255
- out.append(updated_tokens[0])
256
-
257
- return torch.stack(out, dim=0) # (B,N,C)
 
 
1
  from typing import Optional, Tuple
2
  import torch
3
  import torch.nn as nn
4
+ import torch.nn.functional as F
5
  from torch import Tensor
6
 
7
  from segment_anything.modeling.transformer import TwoWayTransformer
8
  from click3r.correspondence_encoder import CorrespondenceEncoder
9
 
10
 
11
+ def _linear(module, x, weights):
12
+ """module(x) for an nn.Linear, or F.linear with weights[module] = (weight, bias)."""
13
+ if weights is None:
14
+ return module(x)
15
+ return F.linear(x, *weights[module])
16
+
17
+
18
+ def _attention(attention, q, k, v, key_bias=None, weights=None):
19
+ """SAM's Attention.forward as one fused attention call.
20
+
21
+ key_bias: optional (B,1,1,Nk) additive mask, -inf for keys left out of the softmax.
22
+ weights: optional (weight, bias) per projection, as for _linear.
23
+ """
24
+ heads = attention.num_heads
25
+ q = attention._separate_heads(_linear(attention.q_proj, q, weights), heads)
26
+ k = attention._separate_heads(_linear(attention.k_proj, k, weights), heads)
27
+ v = attention._separate_heads(_linear(attention.v_proj, v, weights), heads)
28
+ out = F.scaled_dot_product_attention(q, k, v, attn_mask=key_bias)
29
+ return _linear(attention.out_proj, attention._recombine_heads(out), weights)
30
 
31
 
32
  class CorrespondenceAdapter(nn.Module):
33
  """
34
+ Sparse prompting adapter. The prompts of a sample update its image tokens through
35
+ a SAM two-way transformer; padded prompts stay out of attention as keys. Training
36
+ runs only the prompted samples of a batch. Evaluation runs every sample without
37
+ host synchronization and gives samples without valid prompts their input tokens
38
+ back. Rounding depends on the batch shape, so results can differ between batch
39
+ sizes in the last bits.
40
  Inputs:
41
  image_tokens: (B,N,C) tokens AFTER DUSt3R decoder_embed, BEFORE dec_blocks
42
  coords_xy: (B,P,2) pixel (x,y)
 
75
  num_heads=transformer_heads,
76
  mlp_dim=transformer_mlp_dim,
77
  )
78
+ # The Linear layers that run (the final token-to-image attention is skipped)
79
+ # and their weights cast to an autocast dtype, by (dtype, device).
80
+ self._linears = [
81
+ m for m in self.transformer.layers.modules() if isinstance(m, nn.Linear)
82
+ ]
83
+ self._linear_casts = {}
84
 
85
  def _image_position_encoding(self, token_positions: Optional[Tensor]) -> Tensor:
86
  """
 
112
  token_positions
113
  ) # (B,C,H,W)
114
 
115
+ def _cast_linear_weights(self, device_type):
116
+ """(weight, bias) of each Linear layer in the autocast dtype.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
+ Autocast would cast every weight and bias at its own call; one multi-tensor
119
+ copy per adapter call casts them all with the same rounding. Returns None,
120
+ so the layers cast for themselves, with autograd or without autocast.
121
+ """
122
+ if torch.is_grad_enabled() or not torch.is_autocast_enabled(device_type):
123
+ return None
124
+ tensors = [t for m in self._linears for t in (m.weight, m.bias)]
125
+ key = (torch.get_autocast_dtype(device_type), tensors[0].device)
126
+ if key not in self._linear_casts:
127
+ # Normal tensors, not inference tensors, so that calls under no_grad and
128
+ # under inference_mode can both write them.
129
+ with torch.inference_mode(False):
130
+ self._linear_casts[key] = [
131
+ torch.empty_like(t, dtype=key[0]) for t in tensors
132
+ ]
133
+ casts = self._linear_casts[key]
134
+ torch._foreach_copy_(casts, tensors)
135
+ return {m: casts[2 * i : 2 * i + 2] for i, m in enumerate(self._linears)}
136
 
137
  def _update_image_tokens_batched(
138
  self,
139
  image_tokens: Tensor, # (B,N,C)
140
  image_position_encoding: Tensor, # (B,C,H,W)
141
  prompt_tokens: Tensor, # (B,P,C)
142
+ attend: Tensor, # (B,P) bool; False rows are padding
143
  ) -> Tensor:
144
  """TwoWayTransformer.forward, keeping padded prompts out of attention as keys.
145
 
 
150
  key_pe = image_position_encoding.flatten(2).permute(0, 2, 1)
151
  queries = prompt_tokens
152
  query_pe = prompt_tokens
153
+ # The additive mask SDPA would build from a bool mask at every call, in the
154
+ # attention dtype, with rows padded to 16 for memory-efficient attention.
155
+ device = attend.device.type
156
+ dtype = (
157
+ torch.get_autocast_dtype(device)
158
+ if torch.is_autocast_enabled(device)
159
+ else prompt_tokens.dtype
160
+ )
161
+ B, P = attend.shape
162
+ key_bias = torch.zeros(
163
+ B, 1, 1, -(-P // 16) * 16, dtype=dtype, device=attend.device
164
+ )
165
+ key_bias = key_bias[..., :P].masked_fill_(
166
+ ~attend[:, None, None, :], float("-inf")
167
+ )
168
+ weights = self._cast_linear_weights(device)
169
  for layer in self.transformer.layers:
170
  if layer.skip_first_layer_pe:
171
+ queries = _attention(
172
+ layer.self_attn, queries, queries, queries, key_bias, weights
173
  )
174
  else:
175
  q = queries + query_pe
176
+ queries = queries + _attention(
177
+ layer.self_attn, q, q, queries, key_bias, weights
178
  )
179
  queries = layer.norm1(queries)
180
  q = queries + query_pe
181
  k = keys + key_pe
182
  queries = layer.norm2(
183
+ queries
184
+ + _attention(layer.cross_attn_token_to_image, q, k, keys, None, weights)
185
  )
186
+ mlp = layer.mlp
187
+ hidden = mlp.act(_linear(mlp.lin1, queries, weights))
188
+ queries = layer.norm3(queries + _linear(mlp.lin2, hidden, weights))
189
  q = queries + query_pe
 
190
  keys = layer.norm4(
191
  keys
192
+ + _attention(
193
+ layer.cross_attn_image_to_token, k, q, queries, key_bias, weights
194
  )
195
  )
196
  return keys
 
215
  token_positions
216
  ) # (B,C,H,W)
217
 
218
+ valid = (
219
+ torch.ones(
220
+ B, coords_xy.shape[1], dtype=torch.bool, device=image_tokens.device
 
 
 
 
221
  )
222
+ if valid_mask is None
223
+ else valid_mask
224
+ )
225
+ prompted = valid.any(dim=1)
226
+
227
+ if self.training:
228
  if not prompted.any():
229
  return image_tokens
230
  prompt_tokens = self.correspondence_encoder.encode_points(
 
237
  image_tokens[prompted],
238
  image_position_encoding[prompted],
239
  prompt_tokens,
240
+ valid[prompted],
241
  )
242
  # Under autocast the updated tokens are wider than the input ones.
243
  out = image_tokens.to(updated.dtype, copy=True)
244
  out[prompted] = updated
245
  return out
246
 
247
+ # Evaluation runs every sample, so it needs no host synchronization. A sample
248
+ # without valid prompts attends to all its rows, which keeps its softmax rows
249
+ # non-empty, and then gets its input tokens back.
250
+ prompt_tokens = self.correspondence_encoder.encode_points(
251
+ coords_xy, image_ids, pair_ids, image_sizes=image_sizes
252
+ ) # (B,P,C)
253
+ updated = self._update_image_tokens_batched(
254
+ image_tokens,
255
+ image_position_encoding,
256
+ prompt_tokens,
257
+ valid | ~prompted[:, None],
258
+ )
259
+ return torch.where(prompted[:, None, None], updated, image_tokens)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
click3r/correspondence_encoder.py CHANGED
@@ -92,14 +92,11 @@ class CorrespondenceEncoder(nn.Module):
92
  self,
93
  coords_xy_pixels: Tensor, # (B,Pvalid,2)
94
  image_ids: Tensor, # (B,Pvalid)
95
- pair_ids: Tensor, # (B,Pvalid) in [0..max_pairs-1]
96
  image_sizes: Optional[Tensor] = None, # (B,2) (H,W)
97
  ) -> Tensor:
98
  B, P, two = coords_xy_pixels.shape
99
  assert two == 2, "coords must be (x,y)"
100
- assert (pair_ids >= 0).all(), (
101
- "Pair IDs must be nonnegative; remove padded rows before encoding."
102
- )
103
 
104
  if image_sizes is None:
105
  img_sizes_b2 = (
 
92
  self,
93
  coords_xy_pixels: Tensor, # (B,Pvalid,2)
94
  image_ids: Tensor, # (B,Pvalid)
95
+ pair_ids: Tensor, # (B,Pvalid) in [0..max_pairs-1], padded rows too
96
  image_sizes: Optional[Tensor] = None, # (B,2) (H,W)
97
  ) -> Tensor:
98
  B, P, two = coords_xy_pixels.shape
99
  assert two == 2, "coords must be (x,y)"
 
 
 
100
 
101
  if image_sizes is None:
102
  img_sizes_b2 = (