lhallee commited on
Commit
192d7ce
·
verified ·
1 Parent(s): 3611a85

Upload modeling_fastesm.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_fastesm.py +0 -538
modeling_fastesm.py CHANGED
@@ -586,544 +586,6 @@ class EsmEncoder(nn.Module):
586
  )
587
 
588
 
589
- ### Support for embedding datasets with low code
590
- class _LegacyPooler:
591
- def __init__(self, pooling_types: List[str]):
592
- self.pooling_types = pooling_types
593
- self.pooling_options = {
594
- 'mean': self.mean_pooling,
595
- 'max': self.max_pooling,
596
- 'norm': self.norm_pooling,
597
- 'median': self.median_pooling,
598
- 'std': self.std_pooling,
599
- 'var': self.var_pooling,
600
- 'cls': self.cls_pooling,
601
- 'parti': self._pool_parti,
602
- }
603
-
604
- def _create_pooled_matrices_across_layers(self, attentions: torch.Tensor) -> torch.Tensor:
605
- maxed_attentions = torch.max(attentions, dim=1)[0]
606
- return maxed_attentions
607
-
608
- def _page_rank(self, attention_matrix, personalization=None, nstart=None, prune_type="top_k_outdegree"):
609
- # Run PageRank on the attention matrix converted to a graph.
610
- # Raises exceptions if the graph doesn't match the token sequence or has no edges.
611
- # Returns the PageRank scores for each token node.
612
- G = self._convert_to_graph(attention_matrix)
613
- if G.number_of_nodes() != attention_matrix.shape[0]:
614
- raise Exception(
615
- f"The number of nodes in the graph should be equal to the number of tokens in sequence! You have {G.number_of_nodes()} nodes for {attention_matrix.shape[0]} tokens.")
616
- if G.number_of_edges() == 0:
617
- raise Exception(f"You don't seem to have any attention edges left in the graph.")
618
-
619
- return nx.pagerank(G, alpha=0.85, tol=1e-06, weight='weight', personalization=personalization, nstart=nstart, max_iter=100)
620
-
621
- def _convert_to_graph(self, matrix):
622
- # Convert a matrix (e.g., attention scores) to a directed graph using networkx.
623
- # Each element in the matrix represents a directed edge with a weight.
624
- G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
625
- return G
626
-
627
- def _calculate_importance_weights(self, dict_importance, attention_mask: Optional[torch.Tensor] = None):
628
- # Remove keys where attention_mask is 0
629
- if attention_mask is not None:
630
- for k in list(dict_importance.keys()):
631
- if attention_mask[k] == 0:
632
- del dict_importance[k]
633
-
634
- #dict_importance[0] # remove cls
635
- #dict_importance[-1] # remove eos
636
- total = sum(dict_importance.values())
637
- return np.array([v / total for _, v in dict_importance.items()])
638
-
639
- def _pool_parti(self, emb: torch.Tensor, attentions: torch.Tensor, attention_mask: Optional[torch.Tensor] = None): # (b, L, d) -> (b, d)
640
- maxed_attentions = self._create_pooled_matrices_across_layers(attentions).numpy()
641
- # emb is (b, L, d), maxed_attentions is (b, L, L)
642
- emb_pooled = []
643
- for e, a, mask in zip(emb, maxed_attentions, attention_mask):
644
- dict_importance = self._page_rank(a)
645
- importance_weights = self._calculate_importance_weights(dict_importance, mask)
646
- num_tokens = int(mask.sum().item())
647
- emb_pooled.append(np.average(e[:num_tokens], weights=importance_weights, axis=0))
648
- pooled = torch.tensor(np.array(emb_pooled))
649
- return pooled
650
-
651
- def mean_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
652
- if attention_mask is None:
653
- return emb.mean(dim=1)
654
- else:
655
- attention_mask = attention_mask.unsqueeze(-1)
656
- return (emb * attention_mask).sum(dim=1) / attention_mask.sum(dim=1)
657
-
658
- def max_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
659
- if attention_mask is None:
660
- return emb.max(dim=1).values
661
- else:
662
- attention_mask = attention_mask.unsqueeze(-1)
663
- return (emb * attention_mask).max(dim=1).values
664
-
665
- def norm_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
666
- if attention_mask is None:
667
- return emb.norm(dim=1, p=2)
668
- else:
669
- attention_mask = attention_mask.unsqueeze(-1)
670
- return (emb * attention_mask).norm(dim=1, p=2)
671
-
672
- def median_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
673
- if attention_mask is None:
674
- return emb.median(dim=1).values
675
- else:
676
- attention_mask = attention_mask.unsqueeze(-1)
677
- return (emb * attention_mask).median(dim=1).values
678
-
679
- def std_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
680
- if attention_mask is None:
681
- return emb.std(dim=1)
682
- else:
683
- # Compute variance correctly over non-masked positions, then take sqrt
684
- var = self.var_pooling(emb, attention_mask, **kwargs)
685
- return torch.sqrt(var)
686
-
687
- def var_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
688
- if attention_mask is None:
689
- return emb.var(dim=1)
690
- else:
691
- # Correctly compute variance over only non-masked positions
692
- attention_mask = attention_mask.unsqueeze(-1) # (b, L, 1)
693
- # Compute mean over non-masked positions
694
- mean = (emb * attention_mask).sum(dim=1) / attention_mask.sum(dim=1) # (b, d)
695
- mean = mean.unsqueeze(1) # (b, 1, d)
696
- # Compute squared differences from mean, only over non-masked positions
697
- squared_diff = (emb - mean) ** 2 # (b, L, d)
698
- # Sum squared differences over non-masked positions and divide by count
699
- var = (squared_diff * attention_mask).sum(dim=1) / attention_mask.sum(dim=1) # (b, d)
700
- return var
701
-
702
- def cls_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
703
- return emb[:, 0, :]
704
-
705
- def __call__(
706
- self,
707
- emb: torch.Tensor,
708
- attention_mask: Optional[torch.Tensor] = None,
709
- attentions: Optional[torch.Tensor] = None
710
- ): # [mean, max]
711
- final_emb = []
712
- for pooling_type in self.pooling_types:
713
- final_emb.append(self.pooling_options[pooling_type](emb=emb, attention_mask=attention_mask, attentions=attentions)) # (b, d)
714
- return torch.cat(final_emb, dim=-1) # (b, n_pooling_types * d)
715
-
716
-
717
- class ProteinDataset(TorchDataset):
718
- """Simple dataset for protein sequences."""
719
- def __init__(self, sequences: list[str]):
720
- self.sequences = sequences
721
-
722
- def __len__(self) -> int:
723
- return len(self.sequences)
724
-
725
- def __getitem__(self, idx: int) -> str:
726
- return self.sequences[idx]
727
-
728
-
729
- def build_collator(tokenizer) -> Callable[[list[str]], tuple[torch.Tensor, torch.Tensor]]:
730
- def _collate_fn(sequences: list[str]) -> tuple[torch.Tensor, torch.Tensor]:
731
- """Collate function for batching sequences."""
732
- return tokenizer(sequences, return_tensors="pt", padding='longest')
733
- return _collate_fn
734
-
735
-
736
- class _LegacyEmbeddingMixin:
737
- def _embed(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
738
- raise NotImplementedError
739
-
740
- @property
741
- def device(self) -> torch.device:
742
- """Get the device of the model."""
743
- return next(self.parameters()).device
744
-
745
- def _read_sequences_from_db(self, db_path: str) -> set[str]:
746
- """Read sequences from SQLite database."""
747
- import sqlite3
748
- sequences = []
749
- with sqlite3.connect(db_path) as conn:
750
- c = conn.cursor()
751
- c.execute("SELECT sequence FROM embeddings")
752
- while True:
753
- row = c.fetchone()
754
- if row is None:
755
- break
756
- sequences.append(row[0])
757
- return set(sequences)
758
-
759
- def embed_dataset(
760
- self,
761
- sequences: List[str],
762
- tokenizer: PreTrainedTokenizerBase,
763
- batch_size: int = 2,
764
- max_len: int = 512,
765
- truncate: bool = True,
766
- full_embeddings: bool = False,
767
- embed_dtype: torch.dtype = torch.float32,
768
- pooling_types: List[str] = ['mean'],
769
- num_workers: int = 0,
770
- sql: bool = False,
771
- save: bool = True,
772
- sql_db_path: str = 'embeddings.db',
773
- save_path: str = 'embeddings.pth',
774
- **kwargs,
775
- ) -> Optional[dict[str, torch.Tensor]]:
776
- """Embed a dataset of protein sequences.
777
-
778
- Args:
779
- sequences: List of protein sequences
780
- batch_size: Batch size for processing
781
- max_len: Maximum sequence length
782
- full_embeddings: Whether to return full residue-wise (True) embeddings or pooled (False)
783
- pooling_type: Type of pooling ('mean' or 'cls')
784
- num_workers: Number of workers for data loading, 0 for the main process
785
- sql: Whether to store embeddings in SQLite database - will be stored in float32
786
- sql_db_path: Path to SQLite database
787
-
788
- Returns:
789
- Dictionary mapping sequences to embeddings, or None if sql=True
790
-
791
- Note:
792
- - If sql=True, embeddings can only be stored in float32
793
- - sql is ideal if you need to stream a very large dataset for training in real-time
794
- - save=True is ideal if you can store the entire embedding dictionary in RAM
795
- - sql will be used if it is True and save is True or False
796
- - If your sql database or .pth file is already present, they will be scanned first for already embedded sequences
797
- - Sequences will be truncated to max_len and sorted by length in descending order for faster processing
798
-
799
- Example:
800
- >>> embedder = EmbeddingMixin()
801
- >>> embedding_dict = embedder.embed_dataset(
802
- sequences=[
803
- 'MALWMRLLPLLALLALWGPDPAAA', ... # list of protein sequences
804
- ],
805
- batch_size=2, # adjust for your GPU memory
806
- max_len=512, # adjust for your needs
807
- full_embeddings=False, # if True, no pooling is performed
808
- embed_dtype=torch.float32, # cast to what dtype you want
809
- pooling_type=['mean', 'cls'], # more than one pooling type will be concatenated together
810
- num_workers=0, # if you have many cpu cores, we find that num_workers = 4 is fast for large datasets
811
- sql=False, # if True, embeddings will be stored in SQLite database
812
- sql_db_path='embeddings.db',
813
- save=True, # if True, embeddings will be saved as a .pth file
814
- save_path='embeddings.pth',
815
- )
816
- >>> # embedding_dict is a dictionary mapping sequences to their embeddings as tensors for .pth or numpy arrays for sql
817
- """
818
- sequences = list(set([seq[:max_len] if truncate else seq for seq in sequences]))
819
- sequences = sorted(sequences, key=len, reverse=True)
820
- hidden_size = self.config.hidden_size
821
- collate_fn = build_collator(tokenizer)
822
- device = self.device
823
- pooler = Pooler(pooling_types) if not full_embeddings else None
824
-
825
- def get_embeddings(residue_embeddings: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
826
- if full_embeddings or residue_embeddings.ndim == 2: # if already pooled or want residue-wise embeddings
827
- return residue_embeddings
828
- else:
829
- return pooler(residue_embeddings, attention_mask)
830
-
831
- if sql:
832
- import sqlite3
833
- conn = sqlite3.connect(sql_db_path)
834
- c = conn.cursor()
835
- c.execute('CREATE TABLE IF NOT EXISTS embeddings (sequence text PRIMARY KEY, embedding blob)')
836
- already_embedded = self._read_sequences_from_db(sql_db_path)
837
- to_embed = [seq for seq in sequences if seq not in already_embedded]
838
- print(f"Found {len(already_embedded)} already embedded sequences in {sql_db_path}")
839
- print(f"Embedding {len(to_embed)} new sequences")
840
- if len(to_embed) > 0:
841
- dataset = ProteinDataset(to_embed)
842
- dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, collate_fn=collate_fn, shuffle=False)
843
- with torch.no_grad():
844
- for i, batch in tqdm(enumerate(dataloader), total=len(dataloader), desc='Embedding batches'):
845
- seqs = to_embed[i * batch_size:(i + 1) * batch_size]
846
- input_ids, attention_mask = batch['input_ids'].to(device), batch['attention_mask'].to(device)
847
- residue_embeddings = self._embed(input_ids, attention_mask).float() # sql requires float32
848
- embeddings = get_embeddings(residue_embeddings, attention_mask)
849
- for seq, emb, mask in zip(seqs, embeddings, attention_mask):
850
- if full_embeddings:
851
- emb = emb[mask.bool()].reshape(-1, hidden_size)
852
- c.execute("INSERT OR REPLACE INTO embeddings VALUES (?, ?)", (seq, emb.cpu().numpy().tobytes()))
853
-
854
- if (i + 1) % 100 == 0:
855
- conn.commit()
856
-
857
- conn.commit()
858
- conn.close()
859
- return None
860
-
861
- embeddings_dict = {}
862
- if os.path.exists(save_path):
863
- embeddings_dict = torch.load(save_path, map_location='cpu', weights_only=True)
864
- to_embed = [seq for seq in sequences if seq not in embeddings_dict]
865
- print(f"Found {len(embeddings_dict)} already embedded sequences in {save_path}")
866
- print(f"Embedding {len(to_embed)} new sequences")
867
- else:
868
- to_embed = sequences
869
- print(f"Embedding {len(to_embed)} new sequences")
870
-
871
- if len(to_embed) > 0:
872
- dataset = ProteinDataset(to_embed)
873
- dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, collate_fn=collate_fn, shuffle=False)
874
- with torch.no_grad():
875
- for i, batch in tqdm(enumerate(dataloader), total=len(dataloader), desc='Embedding batches'):
876
- seqs = to_embed[i * batch_size:(i + 1) * batch_size]
877
- input_ids, attention_mask = batch['input_ids'].to(device), batch['attention_mask'].to(device)
878
- residue_embeddings = self._embed(input_ids, attention_mask)
879
- embeddings = get_embeddings(residue_embeddings, attention_mask).to(embed_dtype)
880
- for seq, emb, mask in zip(seqs, embeddings, attention_mask):
881
- if full_embeddings:
882
- emb = emb[mask.bool()].reshape(-1, hidden_size)
883
- embeddings_dict[seq] = emb.cpu()
884
-
885
- if save:
886
- torch.save(embeddings_dict, save_path)
887
-
888
- return embeddings_dict
889
-
890
-
891
- class FastEsmPreTrainedModel(PreTrainedModel):
892
- """
893
- An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
894
- models.
895
- """
896
- config_class = FastEsmConfig
897
- base_model_prefix = "fastesm"
898
- supports_gradient_checkpointing = True
899
- all_tied_weights_keys = {}
900
- tokenizer = EsmTokenizer.from_pretrained("facebook/esm2_t6_8M_UR50D")
901
- def _init_weights(self, module):
902
- """Initialize the weights"""
903
- if isinstance(module, nn.Linear):
904
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
905
- if module.bias is not None:
906
- module.bias.data.zero_()
907
- elif isinstance(module, nn.Embedding):
908
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
909
- if module.padding_idx is not None:
910
- module.weight.data[module.padding_idx].zero_()
911
- elif isinstance(module, nn.LayerNorm):
912
- if module.bias is not None:
913
- module.bias.data.zero_()
914
- module.weight.data.fill_(1.0)
915
-
916
- def get_input_embeddings(self) -> nn.Module:
917
- try:
918
- return self.embeddings.word_embeddings
919
- except AttributeError:
920
- return self.esm.embeddings.word_embeddings
921
-
922
-
923
- class FAST_ESM_ENCODER(FastEsmPreTrainedModel, EmbeddingMixin):
924
- def __init__(self, config, add_pooling_layer: Optional[bool] = True, **kwargs):
925
- FastEsmPreTrainedModel.__init__(self, config, **kwargs)
926
- self.config = config
927
- self.embeddings = EsmEmbeddings(config)
928
- self.encoder = EsmEncoder(config)
929
- self.contact_head = EsmContactPredictionHead(
930
- in_features=config.num_hidden_layers * config.num_attention_heads, bias=True
931
- )
932
- # Initialize weights and apply final processing
933
- self.post_init()
934
-
935
- def get_input_embeddings(self):
936
- return self.embeddings.word_embeddings
937
-
938
- def set_input_embeddings(self, value):
939
- self.embeddings.word_embeddings = value
940
-
941
- def _embed(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
942
- token_embedding_output = self.embeddings(input_ids, attention_mask=attention_mask)
943
- batch_size, seq_length = input_ids.shape
944
- if attention_mask is not None:
945
- extended_attention_mask = attention_mask[:, None, None, :].expand(
946
- batch_size, 1, seq_length, seq_length
947
- ).bool()
948
- else:
949
- extended_attention_mask = None
950
- if (
951
- attention_mask is not None
952
- and self.config.attn_backend == "flex"
953
- and create_block_mask is not None
954
- ):
955
- flex_block_mask = _create_pad_block_mask(attention_mask, self.config.flex_block_size)
956
- else:
957
- flex_block_mask = None
958
- encoder_outputs = self.encoder(
959
- token_embedding_output,
960
- attention_mask=extended_attention_mask,
961
- flex_block_mask=flex_block_mask,
962
- output_hidden_states=False,
963
- output_attentions=False,
964
- )
965
- return encoder_outputs.last_hidden_state
966
-
967
- def predict_contacts(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
968
- attns = self(input_ids, attention_mask=attention_mask, output_attentions=True).attentions
969
- attns = torch.stack(attns, dim=1)
970
- attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(3)
971
- attns *= attention_mask.unsqueeze(1).unsqueeze(2).unsqueeze(4)
972
- return self.contact_head(input_ids, attns)
973
-
974
- def forward(
975
- self,
976
- input_ids: Optional[torch.Tensor] = None,
977
- attention_mask: Optional[torch.Tensor] = None,
978
- position_ids: Optional[torch.Tensor] = None,
979
- inputs_embeds: Optional[torch.Tensor] = None,
980
- output_attentions: Optional[bool] = None,
981
- output_hidden_states: Optional[bool] = None,
982
- return_dict: Optional[bool] = None, # to play nice with HF adjacent packages
983
- ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
984
- """Forward pass for base model.
985
-
986
- Args:
987
- input_ids: Input token IDs
988
- attention_mask: Optional attention mask
989
- position_ids: Optional position IDs
990
- inputs_embeds: Optional input embeddings
991
- output_hidden_states: Whether to return all hidden states
992
- output_attentions: Whether to return attention weights
993
-
994
- Returns:
995
- Model outputs including hidden states and optionally attention weights
996
- """
997
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
998
- output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
999
-
1000
- if input_ids is not None and inputs_embeds is not None:
1001
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1002
- elif input_ids is not None:
1003
- self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1004
- input_shape = input_ids.size()
1005
- elif inputs_embeds is not None:
1006
- input_shape = inputs_embeds.size()[:-1]
1007
- else:
1008
- raise ValueError("You have to specify either input_ids or inputs_embeds")
1009
-
1010
- batch_size, seq_length = input_shape
1011
- token_embedding_output = self.embeddings(
1012
- input_ids=input_ids,
1013
- position_ids=position_ids,
1014
- attention_mask=attention_mask,
1015
- inputs_embeds=inputs_embeds,
1016
- )
1017
-
1018
- if attention_mask is not None:
1019
- extended_attention_mask = attention_mask[:, None, None, :].expand(
1020
- batch_size, 1, seq_length, seq_length
1021
- ).bool()
1022
- else:
1023
- extended_attention_mask = None
1024
- if (
1025
- attention_mask is not None
1026
- and self.config.attn_backend == "flex"
1027
- and create_block_mask is not None
1028
- and not output_attentions
1029
- ):
1030
- flex_block_mask = _create_pad_block_mask(attention_mask, self.config.flex_block_size)
1031
- else:
1032
- flex_block_mask = None
1033
-
1034
- encoder_outputs = self.encoder(
1035
- token_embedding_output,
1036
- attention_mask=extended_attention_mask,
1037
- flex_block_mask=flex_block_mask,
1038
- output_hidden_states=output_hidden_states,
1039
- output_attentions=output_attentions,
1040
- )
1041
- sequence_output = encoder_outputs.last_hidden_state
1042
-
1043
- return BaseModelOutputWithPoolingAndCrossAttentions(
1044
- last_hidden_state=sequence_output,
1045
- hidden_states=encoder_outputs.hidden_states,
1046
- attentions=encoder_outputs.attentions,
1047
- )
1048
-
1049
-
1050
- class FastEsmModel(FastEsmPreTrainedModel, EmbeddingMixin):
1051
- def __init__(self, config, add_pooling_layer: Optional[bool] = True, **kwargs):
1052
- FastEsmPreTrainedModel.__init__(self, config, **kwargs)
1053
- self.config = config
1054
- self.esm = FAST_ESM_ENCODER(config)
1055
- self.pooler = EsmPooler(config) if add_pooling_layer else None
1056
- # Initialize weights and apply final processing
1057
- self.post_init()
1058
-
1059
- def get_input_embeddings(self):
1060
- return self.embeddings.word_embeddings
1061
-
1062
- def set_input_embeddings(self, value):
1063
- self.embeddings.word_embeddings = value
1064
-
1065
- def _embed(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
1066
- return self.esm._embed(input_ids, attention_mask)
1067
-
1068
- def predict_contacts(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
1069
- return self.esm.predict_contacts(input_ids, attention_mask=attention_mask)
1070
-
1071
- def forward(
1072
- self,
1073
- input_ids: Optional[torch.Tensor] = None,
1074
- attention_mask: Optional[torch.Tensor] = None,
1075
- position_ids: Optional[torch.Tensor] = None,
1076
- inputs_embeds: Optional[torch.Tensor] = None,
1077
- output_attentions: Optional[bool] = None,
1078
- output_hidden_states: Optional[bool] = None,
1079
- return_dict: Optional[bool] = None, # to play nice with HF adjacent packages
1080
- **kwargs,
1081
- ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
1082
- """Forward pass for base model.
1083
-
1084
- Args:
1085
- input_ids: Input token IDs
1086
- attention_mask: Optional attention mask
1087
- position_ids: Optional position IDs
1088
- inputs_embeds: Optional input embeddings
1089
- output_hidden_states: Whether to return all hidden states
1090
- output_attentions: Whether to return attention weights
1091
-
1092
- Returns:
1093
- Model outputs including hidden states and optionally attention weights
1094
- """
1095
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1096
- output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1097
-
1098
- if input_ids is not None and inputs_embeds is not None:
1099
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1100
- elif input_ids is not None:
1101
- self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1102
- input_shape = input_ids.size()
1103
- elif inputs_embeds is not None:
1104
- input_shape = inputs_embeds.size()[:-1]
1105
- else:
1106
- raise ValueError("You have to specify either input_ids or inputs_embeds")
1107
-
1108
- outputs = self.esm(
1109
- input_ids,
1110
- attention_mask=attention_mask,
1111
- position_ids=position_ids,
1112
- inputs_embeds=inputs_embeds,
1113
- output_hidden_states=output_hidden_states,
1114
- output_attentions=output_attentions,
1115
- )
1116
- sequence_output = outputs.last_hidden_state
1117
- pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1118
-
1119
- return BaseModelOutputWithPoolingAndCrossAttentions(
1120
- last_hidden_state=sequence_output,
1121
- pooler_output=pooled_output,
1122
- hidden_states=outputs.hidden_states,
1123
- attentions=outputs.attentions,
1124
- )
1125
-
1126
-
1127
  class FastEsmForMaskedLM(FastEsmPreTrainedModel, EmbeddingMixin):
1128
  def __init__(self, config, **kwargs):
1129
  FastEsmPreTrainedModel.__init__(self, config, **kwargs)
 
586
  )
587
 
588
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589
  class FastEsmForMaskedLM(FastEsmPreTrainedModel, EmbeddingMixin):
590
  def __init__(self, config, **kwargs):
591
  FastEsmPreTrainedModel.__init__(self, config, **kwargs)