-
Notifications
You must be signed in to change notification settings - Fork 417
Adding support for reranker and other utilities #258
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
base: main
Are you sure you want to change the base?
Changes from 2 commits
1e3bc19
b50b560
8ea24c0
9d6d238
c909dd2
bef7bbf
2e19ad6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
from .bge_reranker import BGERerankerScorer | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. do we need this here? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do you mean the init file or bge models and hf scorers? No in both. We can remove init file and we can remove hf scorers as whole too given they don't play any role as of now. |
||
from .bge_large import BGELargeV15Scorer |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
from colbert.infra import Run | ||
from colbert.parameters import DEVICE | ||
from colbert.utils.utils import flatten | ||
from colbert.infra.launcher import Launcher | ||
|
||
class BaseHFScorer: | ||
def __init__(self, queries, collection, model, bsize=32, maxlen=180): | ||
self.queries = queries | ||
self.collection = collection | ||
self.model = model | ||
|
||
self.device = DEVICE | ||
self.bsize = bsize | ||
self.maxlen = maxlen | ||
|
||
def launch(self, qids, pids): | ||
launcher = Launcher(self._score_pairs_process, return_all=True) | ||
outputs = launcher.launch(Run().config, qids, pids) | ||
|
||
return flatten(outputs) | ||
|
||
def _score_pairs_process(self, config, qids, pids): | ||
assert len(qids) == len(pids), (len(qids), len(pids)) | ||
share = 1 + len(qids) // config.nranks | ||
offset = config.rank * share | ||
endpos = (1 + config.rank) * share | ||
|
||
return self.score(qids[offset:endpos], pids[offset:endpos], show_progress=(config.rank < 1)) | ||
|
||
def score(self, qids, pids): | ||
raise NotImplementedError |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import torch | ||
import tqdm | ||
from transformers import AutoTokenizer, AutoModel | ||
|
||
from colbert.infra import Run | ||
from colbert.distillation.hf_scorers.base import BaseHFScorer | ||
|
||
class BGELargeV15Scorer(BaseHFScorer): | ||
def __init__(self, queries, collection, model, bsize=32, maxlen=180, query_instruction=None): | ||
super().__init__(queries, collection, model, bsize=bsize, maxlen=maxlen) | ||
|
||
self.query_instruction = query_instruction or "Represent this sentence for searching relevant passages:" | ||
|
||
def score(self, qids, pids, show_progress=False): | ||
tokenizer = AutoTokenizer.from_pretrained(self.model) | ||
model = AutoModel.from_pretrained(self.model).to(self.device) | ||
|
||
assert len(qids) == len(pids), (len(qids), len(pids)) | ||
|
||
scores = [] | ||
|
||
model.eval() | ||
with torch.inference_mode(): | ||
with torch.cuda.amp.autocast(): | ||
for offset in tqdm.tqdm(range(0, len(qids), self.bsize), disable=(not show_progress)): | ||
endpos = offset + self.bsize | ||
|
||
if self.query_instruction is None: | ||
queries_ = [self.queries[qid] for qid in qids[offset:endpos]] | ||
else: | ||
queries_ = [self.query_instruction + self.queries[qid] for qid in qids[offset:endpos]] | ||
|
||
try: | ||
passages_ = [self.collection[pid] for pid in pids[offset:endpos]] | ||
except: | ||
print(pids[offset:endpos]) | ||
raise Exception | ||
|
||
query_features = tokenizer(queries_, padding='longest', truncation=True, | ||
return_tensors='pt', max_length=self.maxlen).to(self.device) | ||
|
||
passage_features = tokenizer(passages_, padding='longest', truncation=True, | ||
return_tensors='pt', max_length=self.maxlen).to(self.device) | ||
|
||
query_embeddings = model(**query_features) | ||
query_embeddings = query_embeddings[0][:, 0] | ||
query_embeddings = torch.nn.functional.normalize(query_embeddings, p=2, dim=1) | ||
|
||
passage_embeddings = model(**passage_features) | ||
passage_embeddings = passage_embeddings[0][:, 0] | ||
passage_embeddings = torch.nn.functional.normalize(passage_embeddings, p=2, dim=1) | ||
|
||
batch_scores = torch.einsum('nd,nd->n', query_embeddings, passage_embeddings) | ||
|
||
scores.append(batch_scores) | ||
|
||
|
||
scores = torch.cat(scores) | ||
scores = scores.tolist() | ||
|
||
Run().print(f'Returning with {len(scores)} scores') | ||
|
||
return scores |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import torch | ||
import tqdm | ||
from transformers import AutoTokenizer, AutoModelForSequenceClassification | ||
|
||
from colbert.infra import Run | ||
from colbert.distillation.hf_scorers.base import BaseHFScorer | ||
|
||
class BGERerankerScorer(BaseHFScorer): | ||
def __init__(self, queries, collection, model, bsize=32, maxlen=180, query_instruction=None): | ||
super().__init__(queries, collection, model, bsize=bsize, maxlen=maxlen) | ||
|
||
self.query_instruction = query_instruction | ||
|
||
def score(self, qids, pids, show_progress=False): | ||
tokenizer = AutoTokenizer.from_pretrained(self.model) | ||
model = AutoModelForSequenceClassification.from_pretrained(self.model).cuda() | ||
|
||
assert len(qids) == len(pids), (len(qids), len(pids)) | ||
|
||
scores = [] | ||
|
||
model.eval() | ||
with torch.inference_mode(): | ||
with torch.cuda.amp.autocast(): | ||
for offset in tqdm.tqdm(range(0, len(qids), self.bsize), disable=(not show_progress)): | ||
endpos = offset + self.bsize | ||
|
||
if self.query_instruction is None: | ||
queries_ = [self.queries[qid] for qid in qids[offset:endpos]] | ||
else: | ||
queries_ = [self.query_instruction + self.queries[qid] for qid in qids[offset:endpos]] | ||
|
||
try: | ||
passages_ = [self.collection[pid] for pid in pids[offset:endpos]] | ||
except: | ||
print(pids[offset:endpos]) | ||
raise Exception | ||
|
||
pairs = [[q,p] for q, p in zip(queries_, passages_)] | ||
|
||
features = tokenizer(pairs, padding='longest', truncation=True, | ||
return_tensors='pt', max_length=self.maxlen).to(self.device) | ||
|
||
batch_scores = model(**features, return_dict=True).logits.view(-1, ).float() | ||
|
||
scores.append(batch_scores) | ||
|
||
|
||
scores = torch.cat(scores) | ||
scores = scores.tolist() | ||
|
||
Run().print(f'Returning with {len(scores)} scores') | ||
|
||
return scores |
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.
This is really cool, Herumb!