-
Notifications
You must be signed in to change notification settings - Fork 39
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
134 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
{ | ||
"cells": [ | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 1, | ||
"metadata": {}, | ||
"outputs": [ | ||
{ | ||
"name": "stderr", | ||
"output_type": "stream", | ||
"text": [ | ||
"/Users/sdan/miniforge3/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", | ||
" from .autonotebook import tqdm as notebook_tqdm\n" | ||
] | ||
}, | ||
{ | ||
"name": "stdout", | ||
"output_type": "stream", | ||
"text": [ | ||
"Similarities: [[0.7919583 0.6369279 0.16512007 0.36207786]]\n" | ||
] | ||
} | ||
], | ||
"source": [ | ||
"from typing import Dict\n", | ||
"import numpy as np\n", | ||
"from transformers import AutoModel, AutoTokenizer\n", | ||
"\n", | ||
"def transform_query(query: str) -> str:\n", | ||
" return f'Represent this sentence for searching relevant passages: {query}'\n", | ||
"\n", | ||
"def pooling_np(outputs, attention_mask, strategy='cls'):\n", | ||
" if strategy == 'cls':\n", | ||
" # Taking the first token (CLS token) for each sequence\n", | ||
" return outputs[:, 0]\n", | ||
" elif strategy == 'mean':\n", | ||
" # Applying attention mask and computing mean pooling\n", | ||
" outputs_masked = outputs * attention_mask[:, :, None]\n", | ||
" return np.sum(outputs_masked, axis=1) / np.sum(attention_mask, axis=1)[:, None]\n", | ||
" else:\n", | ||
" raise NotImplementedError\n", | ||
"\n", | ||
"def cos_sim_np(a, b):\n", | ||
" dot_product = np.dot(a, b.T)\n", | ||
" norm_a = np.linalg.norm(a, axis=1, keepdims=True)\n", | ||
" norm_b = np.linalg.norm(b, axis=1)\n", | ||
" return dot_product / (norm_a * norm_b)\n", | ||
"\n", | ||
"# Load the model and tokenizer\n", | ||
"model_id = 'mixedbread-ai/mxbai-embed-large-v1'\n", | ||
"tokenizer = AutoTokenizer.from_pretrained(model_id)\n", | ||
"model = AutoModel.from_pretrained(model_id) # Running on CPU\n", | ||
"\n", | ||
"# Example documents\n", | ||
"docs = [transform_query('A man is eating a piece of bread')] + [\n", | ||
" \"A man is eating food.\",\n", | ||
" \"A man is eating pasta.\",\n", | ||
" \"The girl is carrying a baby.\",\n", | ||
" \"A man is riding a horse.\",\n", | ||
"]\n", | ||
"\n", | ||
"# Tokenize and process with the model\n", | ||
"inputs = tokenizer(docs, padding=True, return_tensors='pt')\n", | ||
"outputs = model(**inputs).last_hidden_state.detach().numpy() # Convert to NumPy array\n", | ||
"attention_mask = inputs['attention_mask'].numpy() # Convert attention mask to NumPy array\n", | ||
"\n", | ||
"# Pool embeddings using NumPy\n", | ||
"embeddings = pooling_np(outputs, attention_mask, 'cls')\n", | ||
"\n", | ||
"# Calculate cosine similarities with NumPy\n", | ||
"similarities_np = cos_sim_np(embeddings[0:1], embeddings[1:])\n", | ||
"print('Similarities:', similarities_np)\n" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [] | ||
} | ||
], | ||
"metadata": { | ||
"kernelspec": { | ||
"display_name": "base", | ||
"language": "python", | ||
"name": "python3" | ||
}, | ||
"language_info": { | ||
"codemirror_mode": { | ||
"name": "ipython", | ||
"version": 3 | ||
}, | ||
"file_extension": ".py", | ||
"mimetype": "text/x-python", | ||
"name": "python", | ||
"nbconvert_exporter": "python", | ||
"pygments_lexer": "ipython3", | ||
"version": "3.10.6" | ||
} | ||
}, | ||
"nbformat": 4, | ||
"nbformat_minor": 2 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters