Generate Embeddings with Hugging Face
Implement embed(sentences, tokenizer, model), returning a (n, d) NumPy array (not a tensor) of normalized sentence embeddings.
tokenizer and model are a Hugging Face transformers tokenizer and model for sentence-transformers/all-MiniLM-L6-v2. The setup loads both with from_pretrained and passes them in, so your code only calls them.
- Tokenize the batch:
tokenizer(sentences, padding=True, truncation=True, return_tensors="pt")returnsinput_idsand anattention_mask. - Run the model with
model(**batch)undertorch.no_grad(). Its.last_hidden_stateholds one 384-number vector per token. - Masked mean pooling. Average the token vectors into one per sentence, over real tokens only.
- L2-normalize each row.
The catch: padding positions carry attention mask value 0. Average them in and every short sentence drifts toward the same meaningless point.