Fix bug with empty slice if amount of dimensions matches amount of frequencies, but is not equal to 512

#1
Files changed (1) hide show
  1. modeling_reve.py +25 -3
modeling_reve.py CHANGED
@@ -229,6 +229,19 @@ class FourierEmb4D(nn.Module):
229
  self.freqs = freqs
230
  self.increment_time = increment_time
231
  self.margin = margin
 
 
 
 
 
 
 
 
 
 
 
 
 
232
 
233
  def forward(self, positions_):
234
  positions = positions_.clone()
@@ -247,9 +260,18 @@ class FourierEmb4D(nn.Module):
247
  p_w = 2 * math.pi * freqs_w / width
248
  positions = positions[..., None, None, None, None, :]
249
  loc = (positions[..., 0] * p_x + positions[..., 1] * p_y + positions[..., 2] * p_z + positions[..., 3] * p_w).view(*U, -1)
250
- if self.dimension != 512: # noqa
251
- _, _, hd = loc.shape
252
- diff = hd - self.dimension // 2
 
 
 
 
 
 
 
 
 
253
  loc = loc[:, :, :-diff]
254
  emb = torch.cat([torch.cos(loc), torch.sin(loc)], dim=-1)
255
  return emb
 
229
  self.freqs = freqs
230
  self.increment_time = increment_time
231
  self.margin = margin
232
+ harmonics_size = 2 * self.freqs ** 4
233
+ if self.dimension % 2 != 0:
234
+ raise ValueError(
235
+ "Requested embedding size must be even. " \
236
+ f"Requested: {self.dimension}, Must be even as amount of frequency components in positional encodings " \
237
+ "is always even due to amount of harmonics being doubled (one for sine and one for cosine component)."
238
+ )
239
+ if self.dimension > harmonics_size:
240
+ raise ValueError(
241
+ f"Requested embedding size is larger than the maximum possible size for the given frequency range. " \
242
+ f"Requested: {self.dimension}, Maximum: {harmonics_size}. " \
243
+ "Please increase the number of frequencies or decrease the embedding size."
244
+ )
245
 
246
  def forward(self, positions_):
247
  positions = positions_.clone()
 
260
  p_w = 2 * math.pi * freqs_w / width
261
  positions = positions[..., None, None, None, None, :]
262
  loc = (positions[..., 0] * p_x + positions[..., 1] * p_y + positions[..., 2] * p_z + positions[..., 3] * p_w).view(*U, -1)
263
+ # Positional encoding returns dimension of size self.freqs ** 4 per sine/cosine pair
264
+ # That makes output dimention 2 * self.freqs ** 4
265
+ # If requested embedding size of a model is larger final harmonics are cut off
266
+ _, _, hd = loc.shape
267
+ diff = hd - self.dimension // 2
268
+ if diff < 0:
269
+ raise ValueError(
270
+ "Requested embedding size is larger than the maximum possible size for the given frequency range. " \
271
+ f"Requested: {self.dimension}, Maximum: {2 * self.freqs ** 4}. " \
272
+ "Please increase the number of frequencies or decrease the embedding size."
273
+ )
274
+ elif diff > 0:
275
  loc = loc[:, :, :-diff]
276
  emb = torch.cat([torch.cos(loc), torch.sin(loc)], dim=-1)
277
  return emb