Skip to content

Feat: Support Ranking Method #1820

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion llama_cpp/llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -997,12 +997,32 @@ def create_embedding(
},
}

def rank(
self,
query: str,
documents: List[str]
) -> List[float]:
"""Rank a query against a list of docs

Args:
query: The utf-8 encoded query string.
documents: The utf-8 encoded list of documents.

Returns:
A list of rank scores.
"""
input = [f"{query}</s><s>{doc}" for doc in documents]
embeds = self.embed(input, special_tokenize=True)
rank_scores = [embed[0] for embed in embeds]
return rank_scores

def embed(
self,
input: Union[str, List[str]],
normalize: bool = False,
truncate: bool = True,
return_count: bool = False,
special_tokenize: bool = False,
Copy link

@KanishkNavale KanishkNavale Jun 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @yutyan0119 ,

This is an awesome PR. Nice work! I use this almost everyday.

I have a suggestion. Would it be better to rename the arg. 'special_tokenize' -> 'add_special_tokens'? As the tokenizer endpoint has a arg. named 'add_special', this renaming would bring better fluency.

Moreover, I would like you to add an error handling mechanism as follows:

  1. If the "documents" is an empty list then, return None.

I have faced this issue a few times and this will be a nice "user-comfort" edit.

):
"""Embed a string.

Expand Down Expand Up @@ -1074,7 +1094,7 @@ def decode_batch(seq_sizes: List[int]):

# accumulate batches and encode
for text in inputs:
tokens = self.tokenize(text.encode("utf-8"))
tokens = self.tokenize(text.encode("utf-8"), special=special_tokenize)
if truncate:
tokens = tokens[:n_batch]

Expand Down