AndreaTacchella commited on
Commit
d101cc2
·
verified ·
1 Parent(s): 1718329

Recommend loading with BertModel instead of BertForMaskedLM for embedding extraction

Browse files
Files changed (1) hide show
  1. README.md +18 -9
README.md CHANGED
@@ -73,19 +73,24 @@ For details see the full paper.
73
 
74
  ## Usage
75
 
 
 
76
  > **Minimal example:** build a batch where only the abstract is truncated (on the right), while the title, tech tokens, and all special tokens are preserved. Then run the model and extract the `[CLS]` embedding for each example.
77
 
78
  ```python
79
  import torch
80
- from transformers import BertTokenizer, BertForMaskedLM
81
 
82
  # ---------------------------------------------------------------------------
83
  # 1. Load model + tokenizer
84
  # ---------------------------------------------------------------------------
85
  MODEL_NAME = "AndreaTacchella/TechTokenBert"
86
  tokenizer = BertTokenizer.from_pretrained(MODEL_NAME)
87
- model = BertForMaskedLM.from_pretrained(MODEL_NAME)
88
  model.eval()
 
 
 
89
 
90
  # ---------------------------------------------------------------------------
91
  # 2. Toy data (3 rows)
@@ -156,10 +161,10 @@ enc = build_batch(titles, abstracts, tech_tokens_list, tokenizer, max_length=512
156
  # 4. Forward pass + extract the [CLS] embedding
157
  # ---------------------------------------------------------------------------
158
  with torch.no_grad():
159
- outputs = model(**enc, output_hidden_states=True)
160
 
161
  # last hidden state: (batch, seq_len, hidden_dim); position 0 is [CLS]
162
- cls_embeddings = outputs.hidden_states[-1][:, 0, :]
163
  print(cls_embeddings.shape) # (3, 1024)
164
  ```
165
 
@@ -169,9 +174,9 @@ To obtain the context-dependent embedding of a specific IPC code within a patent
169
 
170
  ```python
171
  with torch.no_grad():
172
- outputs = model(**enc, output_hidden_states=True)
173
 
174
- last_hidden = outputs.hidden_states[-1] # (batch, seq_len, 1024)
175
 
176
  # By construction the TechTokens are always enclosed between the last two [SEP] tokens
177
  # Find the positions of the last two [SEP] tokens and extract the embeddings for the tokens in between
@@ -197,6 +202,12 @@ for i, ids in enumerate(input_ids):
197
  # a tensor of shape (num_tech_tokens, hidden_size)
198
  ```
199
 
 
 
 
 
 
 
200
  ---
201
 
202
  ## Input Format
@@ -211,8 +222,6 @@ for i, ids in enumerate(input_ids):
211
 
212
  ---
213
 
214
- ---
215
-
216
  ## Citation
217
 
218
  ```bibtex
@@ -223,4 +232,4 @@ for i, ids in enumerate(input_ids):
223
  journal = {arXiv preprint arXiv:2605.04875},
224
  year = {2026}
225
  }
226
- ```
 
73
 
74
  ## Usage
75
 
76
+ > **Note on loading the model:** the checkpoint is saved in `BertForMaskedLM` format (used during fine-tuning), but for embedding extraction you should load it with `BertModel` instead, as shown below. `BertModel` loads only the encoder and skips the masked-language-modeling head, which projects every token's hidden state to a logit over the full ~48k vocabulary -- an expensive computation that fine-tuning needs but embedding extraction never uses. This has no effect on the resulting embeddings (the MLM head sits downstream of the hidden states and doesn't feed back into them) but is substantially faster. Only load `BertForMaskedLM` if you actually need masked-token prediction.
77
+
78
  > **Minimal example:** build a batch where only the abstract is truncated (on the right), while the title, tech tokens, and all special tokens are preserved. Then run the model and extract the `[CLS]` embedding for each example.
79
 
80
  ```python
81
  import torch
82
+ from transformers import BertTokenizer, BertModel
83
 
84
  # ---------------------------------------------------------------------------
85
  # 1. Load model + tokenizer
86
  # ---------------------------------------------------------------------------
87
  MODEL_NAME = "AndreaTacchella/TechTokenBert"
88
  tokenizer = BertTokenizer.from_pretrained(MODEL_NAME)
89
+ model = BertModel.from_pretrained(MODEL_NAME) # encoder only, no MLM head -- see note above
90
  model.eval()
91
+ # You will see a warning about "pooler.dense.weight/bias" being newly initialized: this is
92
+ # expected and harmless. The checkpoint has no pooler (BertForMaskedLM doesn't use one), so
93
+ # BertModel creates a random one; we only ever read `last_hidden_state`, never `pooler_output`.
94
 
95
  # ---------------------------------------------------------------------------
96
  # 2. Toy data (3 rows)
 
161
  # 4. Forward pass + extract the [CLS] embedding
162
  # ---------------------------------------------------------------------------
163
  with torch.no_grad():
164
+ outputs = model(**enc)
165
 
166
  # last hidden state: (batch, seq_len, hidden_dim); position 0 is [CLS]
167
+ cls_embeddings = outputs.last_hidden_state[:, 0, :]
168
  print(cls_embeddings.shape) # (3, 1024)
169
  ```
170
 
 
174
 
175
  ```python
176
  with torch.no_grad():
177
+ outputs = model(**enc)
178
 
179
+ last_hidden = outputs.last_hidden_state # (batch, seq_len, 1024)
180
 
181
  # By construction the TechTokens are always enclosed between the last two [SEP] tokens
182
  # Find the positions of the last two [SEP] tokens and extract the embeddings for the tokens in between
 
202
  # a tensor of shape (num_tech_tokens, hidden_size)
203
  ```
204
 
205
+ ### Performance tips for embedding large collections
206
+
207
+ - **Sort by length before batching.** Grouping patents of similar title+abstract length into the same batch minimizes padding, which can nearly double throughput compared to processing patents in arbitrary order. Since embeddings are typically stored keyed by patent ID, results don't need to be restored to the original order afterwards.
208
+ - **Use fp16 autocast on GPU** (`torch.autocast(device_type="cuda", dtype=torch.float16)` around the forward pass) for a further speedup with no measurable loss in embedding quality.
209
+ - Combined with loading via `BertModel` (see note above), these changes gave roughly a 3x throughput increase in practice (RTX 4090, batch size ~24).
210
+
211
  ---
212
 
213
  ## Input Format
 
222
 
223
  ---
224
 
 
 
225
  ## Citation
226
 
227
  ```bibtex
 
232
  journal = {arXiv preprint arXiv:2605.04875},
233
  year = {2026}
234
  }
235
+ ```