-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Encode minicoil vectors to Qdrant #1
Open
mrscoopers
wants to merge
5
commits into
master
Choose a base branch
from
benchmarking
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 |
---|---|---|
@@ -1,32 +1,114 @@ | ||
|
||
from typing import List | ||
import mmh3 | ||
from minicoil_demo.model.mini_coil import MiniCOIL | ||
from minicoil_demo.model.stopwords import english_stopwords | ||
from fastembed.common.utils import get_all_punctuation | ||
|
||
from qdrant_client import models | ||
|
||
GAP = 32000 | ||
INT32_MAX = 2**31 - 1 | ||
english_stopwords = set(english_stopwords) | ||
punctuation = set(get_all_punctuation()) | ||
special_tokens = set(['[CLS]', '[SEP]', '[PAD]', '[UNK]', '[MASK]']) #TBD do better | ||
|
||
def normalize_vector(vector: List[float]) -> List[float]: | ||
norm = sum([x ** 2 for x in vector]) ** 0.5 | ||
return [x / norm for x in vector] | ||
|
||
def unkn_word_token_id(word: str, shift: int) -> int: #2-3 words can collied in 1 index with this mapping, not considering mm3 collisions | ||
hash = mmh3.hash(word) | ||
|
||
if hash < 0: | ||
unsigned_hash = hash + 2**32 | ||
else: | ||
unsigned_hash = hash | ||
|
||
range_size = INT32_MAX - shift | ||
remapped_hash = shift + (unsigned_hash % range_size) | ||
|
||
return remapped_hash | ||
|
||
def embedding_to_vector(model: MiniCOIL, sentence_embedding: List[dict]) -> models.SparseVector: | ||
indicies = [] | ||
def bm25_tf(num_occurrences: int, sentence_len: int, k: float = 1.2, b: float = 0.75, avg_len: float = 6.0) -> float: #avg_len 25 for quora | ||
#omitted checking token_max_lenth | ||
res = num_occurrences * (k + 1) | ||
res /= num_occurrences + k * (1 - b + b * sentence_len / avg_len) | ||
return res | ||
|
||
def embedding_to_vector(model: MiniCOIL, sentence_embedding: dict) -> models.SparseVector: | ||
indices = [] | ||
values = [] | ||
|
||
embedding_size = model.output_dim | ||
vocab_size = model.vocab_resolver.vocab_size() #mini_coil.vocab_resolver.vocab_size() returns "vocab_size + 1" ("-1" to any word) | ||
|
||
#still dependent on vocab_size :( | ||
unknown_words_shift = ((vocab_size * embedding_size) // GAP + 2) * GAP #miniCOIL vocab + at least (32000 // embedding_size) + 1 new words gap | ||
|
||
#we can't use fastembed's def remove_non_alphanumeric(text: str) unless propagating it right to vocab_resolver | ||
sentence_len = 0 | ||
for embedding in sentence_embedding.values(): | ||
if embedding["word"] not in punctuation | english_stopwords | special_tokens: | ||
sentence_len += embedding["count"] | ||
|
||
#print(f"Sentence len is {sentence_len}") | ||
|
||
#BM25 will always return a positive value, miniCOIL - nope | ||
#So, if a word is familiar to miniCOIL, and in one text it's with a +sign (in some dims of the 4 dims), | ||
#while in another it has a -sign in the same dim, then we penalize the match between these documents compared to the documents where this word is not present | ||
#maybe it's not so good(?) | ||
|
||
for embedding in sentence_embedding.values(): | ||
word_id = embedding["word_id"] | ||
|
||
if word_id >= 0: | ||
num_occurences = embedding["count"] | ||
|
||
if word_id >= 0: #miniCOIL starts with ID 1 | ||
#print(f"""We counted {num_occurences} occurences of \"{embedding["word"]}\"""") | ||
embedding = embedding["embedding"] | ||
normalized_embedding = normalize_vector(embedding) | ||
for val_id, value in enumerate(normalized_embedding): | ||
indicies.append(word_id * embedding_size + val_id) | ||
values.append(value) | ||
indices.append((word_id - 1) * embedding_size + val_id) #since miniCOIL IDs start with 1 | ||
#TBD perhaps only if it's positive <THNK> | ||
values.append(value * bm25_tf(num_occurences, sentence_len)) | ||
if word_id == -1: #unk | ||
if embedding["word"] not in punctuation | english_stopwords | special_tokens: | ||
#print(f"""We counted {num_occurences} occurences of \"{embedding["word"]}\"""") | ||
indices.append(unkn_word_token_id(embedding["word"], unknown_words_shift)) | ||
values.append(bm25_tf(num_occurences, sentence_len)) | ||
|
||
return models.SparseVector( | ||
indices=indicies, | ||
indices=indices, | ||
values=values, | ||
) | ||
|
||
def query_embedding_to_vector(model: MiniCOIL, sentence_embedding: dict) -> models.SparseVector: | ||
indices = [] | ||
values = [] | ||
|
||
embedding_size = model.output_dim | ||
vocab_size = model.vocab_resolver.vocab_size() #mini_coil.vocab_resolver.vocab_size() returns "vocab_size + 1" ("-1" to any word) | ||
|
||
#still dependent on vocab_size :( | ||
unknown_words_shift = ((vocab_size * embedding_size) // GAP + 2) * GAP #miniCOIL vocab + at least (32000 // embedding_size) + 1 new words gap | ||
|
||
for embedding in sentence_embedding.values(): | ||
word_id = embedding["word_id"] | ||
|
||
if word_id >= 0: #miniCOIL starts with ID 1 | ||
#print(f"""We counted {num_occurences} occurences of \"{embedding["word"]}\"""") | ||
embedding = embedding["embedding"] | ||
normalized_embedding = normalize_vector(embedding) | ||
for val_id, value in enumerate(normalized_embedding): | ||
indices.append((word_id - 1) * embedding_size + val_id) #since miniCOIL IDs start with 1 | ||
#TBD perhaps only if it's positive <THNK> | ||
values.append(value) | ||
if word_id == -1: #unk | ||
if embedding["word"] not in punctuation | english_stopwords | special_tokens: | ||
#print(f"""We counted {num_occurences} occurences of \"{embedding["word"]}\"""") | ||
indices.append(unkn_word_token_id(embedding["word"], unknown_words_shift)) | ||
values.append(1) | ||
|
||
return models.SparseVector( | ||
indices=indices, | ||
values=values, | ||
) |
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
perhaps only for positive values, or to remap miniCOIL output to range [0, 1] with norm 1, or smth against this penalizing of matching if some word "meaning" (dimension) is opposite in 2 docs;