Xsmos commited on
Commit
a5f1e91
·
verified ·
1 Parent(s): 86ec786

Update foundation_bert retrieval embedding APIs

Browse files
Files changed (1) hide show
  1. foundation_bert.py +130 -55
foundation_bert.py CHANGED
@@ -291,35 +291,37 @@ class FoundationBert(ModernBertModel):
291
  outputs (dict): A dictionary containing the logits and error logits for each modality.
292
  """
293
 
294
- # Initialize the dictionary for the dynamic input-label mapping
295
- input_label_mapping = {}
296
- combined = []
297
- for src_modality in self.modalscalars:
298
- # Add the modality's input and label data to the input_label_mapping
299
- input_label_mapping[src_modality] = {
300
- 'input': inputs[f"input_{src_modality}"], # Input data
301
- 'labels': inputs[f"labels_{src_modality}"] # Corresponding labels
302
- }
303
-
304
- input_data = input_label_mapping[src_modality]['input'] # get input data
305
- label = input_label_mapping[src_modality]['labels'] # get label data (for masking)
306
- input_data = torch.where(label, self.mask_token, input_data) # apply masking
307
-
308
- x = self.embedding[src_modality](input_data.unsqueeze(-1)) # shape: (B, L, H)
309
- x = torch.nn.functional.silu(x)
310
- combined.append(x) # combine all modalities
311
-
312
- combined = torch.cat(combined, dim=1) # Concatenate along the sequence length dimension
313
 
314
- position_ids = torch.arange(combined.size(1)).unsqueeze(0).to(combined.device) # shape: (1, L)
315
- # combined += self.position_embeddings(position_ids) # add position embedding
316
- combined = self.embed_dropout(combined)
317
 
318
- # x = self.encoder(combined, output_hidden_states=True).last_hidden_state # encode the combined input
319
- hidden_states = combined
320
- for encoder_layer in self.layers:
321
- hidden_states = encoder_layer(hidden_states, position_ids = position_ids)[0]
322
- x = self.final_norm(hidden_states)
 
 
323
 
324
  start = 0
325
  outputs = {}
@@ -337,6 +339,50 @@ class FoundationBert(ModernBertModel):
337
 
338
  return (outputs, input_label_mapping) if return_input_label_mapping else outputs
339
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
  def save_pooled_embedding(self, features):
341
  """
342
  Save the last hidden state to a file.
@@ -359,48 +405,77 @@ class FoundationBert(ModernBertModel):
359
  with h5py.File(fname, 'w') as f:
360
  f.create_dataset('features', data=features, maxshape=(None, features.shape[-1]), chunks=True)
361
 
362
- def get_retrieval_embedding(
363
  self,
364
  inputs,
365
  pooling: str = "mean",
366
  normalize: bool = True,
367
  ) -> torch.Tensor:
368
  """
369
- Build a single embedding per sample for kNN-style retrieval.
370
 
371
- Parameters
372
- ----------
373
- inputs : dict
374
- Batch dict with `input_<modality>` and `labels_<modality>` entries.
375
- pooling : str
376
- `mean` (default) or `last`.
377
- normalize : bool
378
- L2-normalize output embeddings for cosine/inner-product search.
379
  """
380
- combined = []
381
- for src_modality in self.modalscalars:
382
- input_data = inputs[f"input_{src_modality}"]
383
- label = inputs[f"labels_{src_modality}"]
384
- input_data = torch.where(label, self.mask_token, input_data)
385
- x = self.embedding[src_modality](input_data.unsqueeze(-1))
386
- x = torch.nn.functional.silu(x)
387
- combined.append(x)
388
-
389
- combined = torch.cat(combined, dim=1)
390
- position_ids = torch.arange(combined.size(1)).unsqueeze(0).to(combined.device)
391
- combined = self.embed_dropout(combined)
392
-
393
- hidden_states = combined
394
- for encoder_layer in self.layers:
395
- hidden_states = encoder_layer(hidden_states, position_ids=position_ids)[0]
396
- hidden_states = self.final_norm(hidden_states)
397
 
398
  if pooling == "last":
399
  embedding = hidden_states[:, -1, :]
400
- else:
401
  embedding = hidden_states.mean(dim=1)
 
 
402
 
403
  if normalize:
404
  embedding = torch.nn.functional.normalize(embedding, p=2, dim=-1)
405
 
406
  return embedding
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  outputs (dict): A dictionary containing the logits and error logits for each modality.
292
  """
293
 
294
+ # # Initialize the dictionary for the dynamic input-label mapping
295
+ # input_label_mapping = {}
296
+ # combined = []
297
+ # for src_modality in self.modalscalars:
298
+ # # Add the modality's input and label data to the input_label_mapping
299
+ # input_label_mapping[src_modality] = {
300
+ # 'input': inputs[f"input_{src_modality}"], # Input data
301
+ # 'labels': inputs[f"labels_{src_modality}"] # Corresponding labels
302
+ # }
303
+
304
+ # input_data = input_label_mapping[src_modality]['input'] # get input data
305
+ # label = input_label_mapping[src_modality]['labels'] # get label data (for masking)
306
+ # input_data = torch.where(label, self.mask_token, input_data) # apply masking
307
+
308
+ # x = self.embedding[src_modality](input_data.unsqueeze(-1)) # shape: (B, L, H)
309
+ # x = torch.nn.functional.silu(x)
310
+ # combined.append(x) # combine all modalities
311
+
312
+ # combined = torch.cat(combined, dim=1) # Concatenate along the sequence length dimension
313
 
314
+ # position_ids = torch.arange(combined.size(1)).unsqueeze(0).to(combined.device) # shape: (1, L)
315
+ # # combined += self.position_embeddings(position_ids) # add position embedding
316
+ # combined = self.embed_dropout(combined)
317
 
318
+ # # x = self.encoder(combined, output_hidden_states=True).last_hidden_state # encode the combined input
319
+ # hidden_states = combined
320
+ # for encoder_layer in self.layers:
321
+ # hidden_states = encoder_layer(hidden_states, position_ids = position_ids)[0]
322
+ # x = self.final_norm(hidden_states)
323
+
324
+ x, input_label_mapping = self.encode_hidden_states(inputs)
325
 
326
  start = 0
327
  outputs = {}
 
339
 
340
  return (outputs, input_label_mapping) if return_input_label_mapping else outputs
341
 
342
+ def encode_hidden_states(self, inputs):
343
+ """
344
+ Encode all available modality/scalar inputs into shared hidden states.
345
+
346
+ Returns
347
+ -------
348
+ hidden_states : torch.Tensor
349
+ Shape: (B, total_seq_len, H)
350
+ input_label_mapping : dict
351
+ Mapping used to recover each modality segment.
352
+ """
353
+ input_label_mapping = {}
354
+ combined = []
355
+
356
+ for src_modality in self.modalscalars:
357
+ input_label_mapping[src_modality] = {
358
+ "input": inputs[f"input_{src_modality}"],
359
+ "labels": inputs[f"labels_{src_modality}"],
360
+ }
361
+
362
+ input_data = input_label_mapping[src_modality]["input"]
363
+ label = input_label_mapping[src_modality]["labels"]
364
+
365
+ input_data = torch.where(
366
+ label,
367
+ torch.full_like(input_data, float(self.mask_token)),
368
+ input_data,
369
+ )
370
+
371
+ x = self.embedding[src_modality](input_data.unsqueeze(-1))
372
+ x = torch.nn.functional.silu(x)
373
+ combined.append(x)
374
+
375
+ combined = torch.cat(combined, dim=1)
376
+ position_ids = torch.arange(combined.size(1), device=combined.device).unsqueeze(0)
377
+ combined = self.embed_dropout(combined)
378
+
379
+ hidden_states = combined
380
+ for encoder_layer in self.layers:
381
+ hidden_states = encoder_layer(hidden_states, position_ids=position_ids)[0]
382
+
383
+ hidden_states = self.final_norm(hidden_states)
384
+ return hidden_states, input_label_mapping
385
+
386
  def save_pooled_embedding(self, features):
387
  """
388
  Save the last hidden state to a file.
 
405
  with h5py.File(fname, 'w') as f:
406
  f.create_dataset('features', data=features, maxshape=(None, features.shape[-1]), chunks=True)
407
 
408
+ def get_unified_embedding(
409
  self,
410
  inputs,
411
  pooling: str = "mean",
412
  normalize: bool = True,
413
  ) -> torch.Tensor:
414
  """
415
+ Build a single unified embedding per sample for kNN-style retrieval.
416
 
417
+ Output shape:
418
+ (B, H)
 
 
 
 
 
 
419
  """
420
+ hidden_states, _ = self.encode_hidden_states(inputs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
 
422
  if pooling == "last":
423
  embedding = hidden_states[:, -1, :]
424
+ elif pooling == "mean":
425
  embedding = hidden_states.mean(dim=1)
426
+ else:
427
+ raise ValueError(f"Unsupported pooling={pooling}. Use 'mean' or 'last'.")
428
 
429
  if normalize:
430
  embedding = torch.nn.functional.normalize(embedding, p=2, dim=-1)
431
 
432
  return embedding
433
+
434
+
435
+ def get_modality_embeddings(
436
+ self,
437
+ inputs,
438
+ pooling: str = "mean",
439
+ normalize: bool = True,
440
+ return_token_embeddings: bool = False,
441
+ ):
442
+ """
443
+ Build one embedding per modality/scalar group.
444
+
445
+ Returns
446
+ -------
447
+ pooled : dict
448
+ pooled[modality] has shape (B, H)
449
+
450
+ token_embeddings : dict, optional
451
+ token_embeddings[modality] has shape (B, L_modality, H)
452
+ """
453
+ hidden_states, input_label_mapping = self.encode_hidden_states(inputs)
454
+
455
+ start = 0
456
+ pooled = {}
457
+ token_embeddings = {}
458
+
459
+ for modality in self.modalscalars:
460
+ length = input_label_mapping[modality]["input"].shape[1]
461
+ x_t = hidden_states[:, start:start + length, :]
462
+
463
+ token_embeddings[modality] = x_t
464
+
465
+ if pooling == "last":
466
+ z = x_t[:, -1, :]
467
+ elif pooling == "mean":
468
+ z = x_t.mean(dim=1)
469
+ else:
470
+ raise ValueError(f"Unsupported pooling={pooling}. Use 'mean' or 'last'.")
471
+
472
+ if normalize:
473
+ z = torch.nn.functional.normalize(z, p=2, dim=-1)
474
+
475
+ pooled[modality] = z
476
+ start += length
477
+
478
+ if return_token_embeddings:
479
+ return pooled, token_embeddings
480
+
481
+ return pooled