lhallee commited on
Commit
5ec5a80
Β·
verified Β·
1 Parent(s): c8a6d41

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +187 -187
README.md CHANGED
@@ -1,188 +1,188 @@
1
- ---
2
- library_name: transformers
3
- tags: []
4
- ---
5
-
6
- # NOTE
7
- The GitHub with the implementation and requirements.txt can be found [here](https://github.com/Synthyra/FastPLMs.git)
8
-
9
- # ESM++
10
- [ESM++](https://github.com/Synthyra/ESMplusplus) is a faithful implementation of [ESMC](https://www.evolutionaryscale.ai/blog/esm-cambrian) ([license](https://www.evolutionaryscale.ai/policies/cambrian-non-commercial-license-agreement)) that allows for batching and standard Huggingface compatibility without requiring the ESM Python package.
11
- The large version corresponds to the 600 million parameter version of ESMC.
12
-
13
- ## Attention backends
14
-
15
- `sdpa` (PyTorch Scaled Dot Product Attention) is the default. The backend is set via `config.attn_backend` before loading.
16
-
17
- | Backend | Key | Notes |
18
- | :--- | :--- | :--- |
19
- | PyTorch SDPA | `"sdpa"` | Default. Exact numerics, stable on all hardware. |
20
- | Flash Attention | `"kernels_flash"` | Fastest on Ampere/Hopper GPUs. Requires `pip install kernels` (pre-built β€” no hours-long compilation). Outputs are not bitwise identical to SDPA due to online softmax reordering; differences are often small but not guaranteed to be inconsequential β€” use `"sdpa"` if exact numerics matter. |
21
- | Flex Attention | `"flex"` | Skips padding tokens via block mask β€” faster on variable-length batches. Near-exact numerics. First use compiles a Triton kernel (30–120 s). Best combined with `torch.compile`. |
22
- | Auto | `"auto"` | Picks the best available: `kernels_flash` β†’ `flex` β†’ `sdpa`. |
23
-
24
- ```python
25
- from transformers import AutoConfig, AutoModelForMaskedLM
26
-
27
- config = AutoConfig.from_pretrained('Synthyra/ESMplusplus_large', trust_remote_code=True)
28
- config.attn_backend = "flex" # or "kernels_flash", "sdpa", "auto"
29
- model = AutoModelForMaskedLM.from_pretrained('Synthyra/ESMplusplus_large', config=config, trust_remote_code=True)
30
- ```
31
-
32
- `torch.compile(model)` is heavily recommended for sustained throughput, especially with Flex Attention.
33
-
34
-
35
- ## Use with πŸ€— transformers
36
- ```python
37
- from transformers import AutoModelForMaskedLM
38
- model = AutoModelForMaskedLM.from_pretrained('Synthyra/ESMplusplus_large', trust_remote_code=True)
39
- tokenizer = model.tokenizer
40
-
41
- sequences = ['MPRTEIN', 'MSEQWENCE']
42
- tokenized = tokenizer(sequences, padding=True, return_tensors='pt')
43
-
44
- # tokenized['labels'] = tokenized['input_ids'].clone() # correctly mask input_ids and set unmasked instances of labels to -100 for MLM training
45
-
46
- output = model(**tokenized) # get all hidden states with output_hidden_states=True
47
- print(output.logits.shape) # language modeling logits, (batch_size, seq_len, vocab_size), (2, 11, 64)
48
- print(output.last_hidden_state.shape) # last hidden state of the model, (batch_size, seq_len, hidden_size), (2, 11, 1152)
49
- print(output.loss) # language modeling loss if you passed labels
50
- #print(output.hidden_states) # all hidden states if you passed output_hidden_states=True (in tuple)
51
- ```
52
-
53
- ESM++ also supports sequence and token level classification tasks like ESM2. Simply pass the number of labels during initialization.
54
-
55
- ```python
56
- from transformers import AutoModelForSequenceClassification, AutoModelForTokenClassification
57
-
58
- model = AutoModelForSequenceClassification.from_pretrained('Synthyra/ESMplusplus_large', num_labels=2, trust_remote_code=True)
59
- logits = model(**tokenized).logits
60
- print(logits.shape) # (batch_size, num_labels), (2, 2)
61
- ```
62
-
63
- ESM++ weights are fp32 by default. You can load them in fp16 or bf16 like this:
64
- ```python
65
- import torch
66
- model = AutoModelForMaskedLM.from_pretrained('Synthyra/ESMplusplus_large', trust_remote_code=True, dtype=torch.float16) # or torch.bfloat16
67
- ```
68
-
69
- ## Embed entire datasets with no new code
70
- To embed a list of protein sequences **fast**, just call embed_dataset. Sequences are sorted to reduce padding tokens, so the initial progress bar estimation is usually much longer than the actual time it will take.
71
-
72
- Example:
73
- ```python
74
- embedding_dict = model.embed_dataset(
75
- sequences=[
76
- 'MALWMRLLPLLALLALWGPDPAAA', ... # list of protein sequences
77
- ],
78
- tokenizer=model.tokenizer,
79
- batch_size=2, # adjust for your GPU memory
80
- max_len=512, # adjust for your needs
81
- full_embeddings=False, # if True, no pooling is performed
82
- embed_dtype=torch.float32, # cast to what dtype you want
83
- pooling_types=['mean', 'cls'], # more than one pooling type will be concatenated together
84
- num_workers=0, # if you have many cpu cores, we find that num_workers = 4 is fast for large datasets
85
- sql=False, # if True, embeddings will be stored in SQLite database
86
- sql_db_path='embeddings.db',
87
- save=True, # if True, embeddings will be saved as a .pth file
88
- save_path='embeddings.pth',
89
- )
90
- # embedding_dict is a dictionary mapping sequences to their embeddings as tensors for .pth or numpy arrays for sql
91
- ```
92
-
93
- ```
94
- model.embed_dataset()
95
- Args:
96
- sequences: List of protein sequences
97
- batch_size: Batch size for processing
98
- max_len: Maximum sequence length
99
- full_embeddings: Whether to return full residue-wise (True) embeddings or pooled (False)
100
- pooling_type: Type of pooling ('mean' or 'cls')
101
- num_workers: Number of workers for data loading, 0 for the main process
102
- sql: Whether to store embeddings in SQLite database - will be stored in float32
103
- sql_db_path: Path to SQLite database
104
-
105
- Returns:
106
- Dictionary mapping sequences to embeddings, or None if sql=True
107
-
108
- Note:
109
- - If sql=True, embeddings can only be stored in float32
110
- - sql is ideal if you need to stream a very large dataset for training in real-time
111
- - save=True is ideal if you can store the entire embedding dictionary in RAM
112
- - sql will be used if it is True and save is True or False
113
- - If your sql database or .pth file is already present, they will be scanned first for already embedded sequences
114
- - Sequences will be truncated to max_len and sorted by length in descending order for faster processing
115
- ```
116
-
117
- ## Fine-tuning with πŸ€— peft
118
- ```python
119
- model = AutoModelForSequenceClassification.from_pretrained('Synthyra/ESMplusplus_large', num_labels=2, trust_remote_code=True)
120
- # these modules handle ESM++ and ESM2 attention layers
121
- target_modules = ["layernorm_qkv.1", "out_proj", "query", "key", "value", "dense"]
122
-
123
- lora_config = LoraConfig(
124
- r=8, # choose lora parameters to your liking
125
- lora_alpha=16,
126
- lora_dropout=0.01,
127
- bias="none",
128
- target_modules=target_modules,
129
- )
130
-
131
- # Apply LoRA to the model
132
- model = get_peft_model(model, lora_config)
133
-
134
- # Unfreeze the classifier head
135
- for param in model.classifier.parameters():
136
- param.requires_grad = True
137
- ```
138
-
139
- For a more thourough example of fine-tuning, check out our example script [here](https://github.com/Synthyra/FastPLMs/blob/main/fine_tuning_example.py).
140
-
141
-
142
- ## Returning attention maps
143
- When `attn_backend="flex"`, Flex Attention with a pad-token block mask is used for attention calculations. Optimized attention paths do not return attention maps directly.
144
- ESM++ has the option to ```output_attentions```, which will calculate attention manually. This is much slower, so do not use unless you need the attention maps.
145
-
146
- ```python
147
- output = model(**tokenized, output_attentions=True)
148
- att = output.attentions
149
- len(att) # 33, one for each layer, size (batch_size, num_heads, seq_len, seq_len) each
150
- ```
151
-
152
- ## Comparison across floating-point precision and implementations
153
- We measured the difference of the last hidden states of the fp32 weights vs. fp16 or bf16. We find that the fp16 is closer to the fp32 outputs, so we recommend loading in fp16.
154
- Please note that the ESM package also loads ESMC in fp32 but casts to bf16 by default, which has its share of advantages and disadvantages in inference / training - so load whichever you like for half precision.
155
-
156
- Average MSE for FP16: 0.00000003
157
-
158
- Average MSE for BF16: 0.00000122
159
-
160
- We also measured the difference between the outputs of ESM++ vs. ESMC (both in bfloat16) on 1000 random sequences to ensure compliance with the ESM package.
161
-
162
- Average MSE of last hidden state: 2.46e-09
163
-
164
- You can load the weights from the ESM package instead of transformers by replacing .from_pretrained(...) to .from_pretrained_esm('esmc_600m')
165
-
166
- ## Model probes
167
- We employ linear probing techniques on various PLMs and standard datasets, similar our previous [paper](https://www.biorxiv.org/content/10.1101/2024.07.30.605924v1), to assess the intrinsic correlation between pooled hidden states and valuable properties. ESMC (and thus ESM++) perform very well.
168
-
169
- The plot below showcases performance normalized between the negative control (random vector embeddings) and the best performer. Classification task scores are averaged between MCC and F1 (or F1max for multilabel) and regression tasks are averaged between Spearman rho and R2.
170
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/62f2bd3bdb7cbd214b658c48/uRAHYQcwkbgajylTIFbUb.png)
171
-
172
- ## Inference speeds
173
- We look at various ESM models and their throughput on an H100. Adding efficient batching between ESMC and ESM++ significantly improves the throughput, although ESM++ is also faster than ESMC for batch size one. ESM++ small is even faster than ESM2-35M with long sequences! The most gains will be seen with PyTorch > 2.5 on linux machines.
174
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/62f2bd3bdb7cbd214b658c48/Lu6nWB9Fc-7YTql3Z1hVB.png)
175
-
176
- ### Citation
177
- If you use any of this implementation or work please cite it (as well as the ESMC preprint).
178
-
179
- ```
180
- @misc {FastPLMs,
181
- author = { Hallee, Logan and Bichara, David and Gleghorn, Jason P.},
182
- title = { FastPLMs: Fast, efficient, protien language model inference from Huggingface AutoModel.},
183
- year = {2024},
184
- url = { https://huggingface.co/Synthyra/ESMplusplus_small },
185
- DOI = { 10.57967/hf/3726 },
186
- publisher = { Hugging Face }
187
- }
188
  ```
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # NOTE
7
+ The GitHub with the implementation and requirements.txt can be found [here](https://github.com/Synthyra/FastPLMs.git)
8
+
9
+ # ESM++
10
+ [ESM++](https://github.com/Synthyra/ESMplusplus) is a faithful implementation of [ESMC](https://www.evolutionaryscale.ai/blog/esm-cambrian) ([license](https://www.evolutionaryscale.ai/policies/cambrian-non-commercial-license-agreement)) that allows for batching and standard Huggingface compatibility without requiring the ESM Python package.
11
+ The large version corresponds to the 600 million parameter version of ESMC.
12
+
13
+ ## Attention backends
14
+
15
+ `sdpa` (PyTorch Scaled Dot Product Attention) is the default. The backend is set via `config.attn_backend` before loading.
16
+
17
+ | Backend | Key | Notes |
18
+ | :--- | :--- | :--- |
19
+ | PyTorch SDPA | `"sdpa"` | Default. Exact numerics, stable on all hardware. |
20
+ | Flash Attention | `"kernels_flash"` | Fastest on Ampere/Hopper GPUs. Requires `pip install kernels` (pre-built β€” no hours-long compilation). Outputs are not bitwise identical to SDPA due to online softmax reordering; differences are often small but not guaranteed to be inconsequential β€” use `"sdpa"` if exact numerics matter. |
21
+ | Flex Attention | `"flex"` | Skips padding tokens via block mask β€” faster on variable-length batches. Near-exact numerics. First use compiles a Triton kernel (30–120 s). Best combined with `torch.compile`. |
22
+ | Auto | `"auto"` | Picks the best available: `kernels_flash` β†’ `flex` β†’ `sdpa`. |
23
+
24
+ ```python
25
+ from transformers import AutoConfig, AutoModelForMaskedLM
26
+
27
+ config = AutoConfig.from_pretrained('Synthyra/ESMplusplus_large', trust_remote_code=True)
28
+ config.attn_backend = "flex" # or "kernels_flash", "sdpa", "auto"
29
+ model = AutoModelForMaskedLM.from_pretrained('Synthyra/ESMplusplus_large', config=config, trust_remote_code=True)
30
+ ```
31
+
32
+ `torch.compile(model)` is heavily recommended for sustained throughput, especially with Flex Attention.
33
+
34
+
35
+ ## Use with πŸ€— transformers
36
+ ```python
37
+ from transformers import AutoModelForMaskedLM
38
+ model = AutoModelForMaskedLM.from_pretrained('Synthyra/ESMplusplus_large', trust_remote_code=True)
39
+ tokenizer = model.tokenizer
40
+
41
+ sequences = ['MPRTEIN', 'MSEQWENCE']
42
+ tokenized = tokenizer(sequences, padding=True, return_tensors='pt')
43
+
44
+ # tokenized['labels'] = tokenized['input_ids'].clone() # correctly mask input_ids and set unmasked instances of labels to -100 for MLM training
45
+
46
+ output = model(**tokenized) # get all hidden states with output_hidden_states=True
47
+ print(output.logits.shape) # language modeling logits, (batch_size, seq_len, vocab_size), (2, 11, 64)
48
+ print(output.last_hidden_state.shape) # last hidden state of the model, (batch_size, seq_len, hidden_size), (2, 11, 1152)
49
+ print(output.loss) # language modeling loss if you passed labels
50
+ #print(output.hidden_states) # all hidden states if you passed output_hidden_states=True (in tuple)
51
+ ```
52
+
53
+ ESM++ also supports sequence and token level classification tasks like ESM2. Simply pass the number of labels during initialization.
54
+
55
+ ```python
56
+ from transformers import AutoModelForSequenceClassification, AutoModelForTokenClassification
57
+
58
+ model = AutoModelForSequenceClassification.from_pretrained('Synthyra/ESMplusplus_large', num_labels=2, trust_remote_code=True)
59
+ logits = model(**tokenized).logits
60
+ print(logits.shape) # (batch_size, num_labels), (2, 2)
61
+ ```
62
+
63
+ ESM++ weights are fp32 by default. You can load them in fp16 or bf16 like this:
64
+ ```python
65
+ import torch
66
+ model = AutoModelForMaskedLM.from_pretrained('Synthyra/ESMplusplus_large', trust_remote_code=True, dtype=torch.float16) # or torch.bfloat16
67
+ ```
68
+
69
+ ## Embed entire datasets with no new code
70
+ To embed a list of protein sequences **fast**, just call embed_dataset. Sequences are sorted to reduce padding tokens, so the initial progress bar estimation is usually much longer than the actual time it will take.
71
+
72
+ Example:
73
+ ```python
74
+ embedding_dict = model.embed_dataset(
75
+ sequences=[
76
+ 'MALWMRLLPLLALLALWGPDPAAA', ... # list of protein sequences
77
+ ],
78
+ tokenizer=model.tokenizer,
79
+ batch_size=2, # adjust for your GPU memory
80
+ max_len=512, # adjust for your needs
81
+ full_embeddings=False, # if True, no pooling is performed
82
+ embed_dtype=torch.float32, # cast to what dtype you want
83
+ pooling_types=['mean', 'cls'], # more than one pooling type will be concatenated together
84
+ num_workers=0, # if you have many cpu cores, we find that num_workers = 4 is fast for large datasets
85
+ sql=False, # if True, embeddings will be stored in SQLite database
86
+ sql_db_path='embeddings.db',
87
+ save=True, # if True, embeddings will be saved as a .pth file
88
+ save_path='embeddings.pth',
89
+ )
90
+ # embedding_dict is a dictionary mapping sequences to their embeddings as tensors for .pth or numpy arrays for sql
91
+ ```
92
+
93
+ ```
94
+ model.embed_dataset()
95
+ Args:
96
+ sequences: List of protein sequences
97
+ batch_size: Batch size for processing
98
+ max_len: Maximum sequence length
99
+ full_embeddings: Whether to return full residue-wise (True) embeddings or pooled (False)
100
+ pooling_type: Type of pooling ('mean' or 'cls')
101
+ num_workers: Number of workers for data loading, 0 for the main process
102
+ sql: Whether to store embeddings in SQLite database - will be stored in float32
103
+ sql_db_path: Path to SQLite database
104
+
105
+ Returns:
106
+ Dictionary mapping sequences to embeddings, or None if sql=True
107
+
108
+ Note:
109
+ - If sql=True, embeddings can only be stored in float32
110
+ - sql is ideal if you need to stream a very large dataset for training in real-time
111
+ - save=True is ideal if you can store the entire embedding dictionary in RAM
112
+ - sql will be used if it is True and save is True or False
113
+ - If your sql database or .pth file is already present, they will be scanned first for already embedded sequences
114
+ - Sequences will be truncated to max_len and sorted by length in descending order for faster processing
115
+ ```
116
+
117
+ ## Fine-tuning with πŸ€— peft
118
+ ```python
119
+ model = AutoModelForSequenceClassification.from_pretrained('Synthyra/ESMplusplus_large', num_labels=2, trust_remote_code=True)
120
+ # these modules handle ESM++ and ESM2 attention layers
121
+ target_modules = ["layernorm_qkv.1", "out_proj", "query", "key", "value", "dense"]
122
+
123
+ lora_config = LoraConfig(
124
+ r=8, # choose lora parameters to your liking
125
+ lora_alpha=16,
126
+ lora_dropout=0.01,
127
+ bias="none",
128
+ target_modules=target_modules,
129
+ )
130
+
131
+ # Apply LoRA to the model
132
+ model = get_peft_model(model, lora_config)
133
+
134
+ # Unfreeze the classifier head
135
+ for param in model.classifier.parameters():
136
+ param.requires_grad = True
137
+ ```
138
+
139
+ For a more thourough example of fine-tuning, check out our example script [here](https://github.com/Synthyra/FastPLMs/blob/main/fine_tuning_example.py).
140
+
141
+
142
+ ## Returning attention maps
143
+ When `attn_backend="flex"`, Flex Attention with a pad-token block mask is used for attention calculations. Optimized attention paths do not return attention maps directly.
144
+ ESM++ has the option to ```output_attentions```, which will calculate attention manually. This is much slower, so do not use unless you need the attention maps.
145
+
146
+ ```python
147
+ output = model(**tokenized, output_attentions=True)
148
+ att = output.attentions
149
+ len(att) # 33, one for each layer, size (batch_size, num_heads, seq_len, seq_len) each
150
+ ```
151
+
152
+ ## Comparison across floating-point precision and implementations
153
+ We measured the difference of the last hidden states of the fp32 weights vs. fp16 or bf16. We find that the fp16 is closer to the fp32 outputs, so we recommend loading in fp16.
154
+ Please note that the ESM package also loads ESMC in fp32 but casts to bf16 by default, which has its share of advantages and disadvantages in inference / training - so load whichever you like for half precision.
155
+
156
+ Average MSE for FP16: 0.00000003
157
+
158
+ Average MSE for BF16: 0.00000122
159
+
160
+ We also measured the difference between the outputs of ESM++ vs. ESMC (both in bfloat16) on 1000 random sequences to ensure compliance with the ESM package.
161
+
162
+ Average MSE of last hidden state: 2.46e-09
163
+
164
+ You can load the weights from the ESM package instead of transformers by replacing .from_pretrained(...) to .from_pretrained_esm('esmc_600m')
165
+
166
+ ## Model probes
167
+ We employ linear probing techniques on various PLMs and standard datasets, similar our previous [paper](https://www.biorxiv.org/content/10.1101/2024.07.30.605924v1), to assess the intrinsic correlation between pooled hidden states and valuable properties. ESMC (and thus ESM++) perform very well.
168
+
169
+ The plot below showcases performance normalized between the negative control (random vector embeddings) and the best performer. Classification task scores are averaged between MCC and F1 (or F1max for multilabel) and regression tasks are averaged between Spearman rho and R2.
170
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/62f2bd3bdb7cbd214b658c48/uRAHYQcwkbgajylTIFbUb.png)
171
+
172
+ ## Inference speeds
173
+ We look at various ESM models and their throughput on an H100. Adding efficient batching between ESMC and ESM++ significantly improves the throughput, although ESM++ is also faster than ESMC for batch size one. ESM++ small is even faster than ESM2-35M with long sequences! The most gains will be seen with PyTorch > 2.5 on linux machines.
174
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/62f2bd3bdb7cbd214b658c48/Lu6nWB9Fc-7YTql3Z1hVB.png)
175
+
176
+ ### Citation
177
+ If you use any of this implementation or work please cite it (as well as the ESMC preprint).
178
+
179
+ ```
180
+ @misc {FastPLMs,
181
+ author = { Hallee, Logan and Bichara, David and Gleghorn, Jason P.},
182
+ title = { FastPLMs: Fast, efficient, protien language model inference from Huggingface AutoModel.},
183
+ year = {2024},
184
+ url = { https://huggingface.co/Synthyra/ESMplusplus_small },
185
+ DOI = { 10.57967/hf/3726 },
186
+ publisher = { Hugging Face }
187
+ }
188
  ```