Skip to content

< CollectionsRetrieval-Augmented Generation · 1 of 7 ·06 · Level 02, Search

Generate Embeddings with Hugging Face

medium · implement · Embeddings & Retrieval

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.

  1. Tokenize the batch: tokenizer(sentences, padding=True, truncation=True, return_tensors="pt") returns input_ids and an attention_mask.
  2. Run the model with model(**batch) under torch.no_grad(). Its .last_hidden_state holds one 384-number vector per token.
  3. Masked mean pooling. Average the token vectors into one per sentence, over real tokens only.
  4. 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.