Views
No views yet
| Model | T2Reranking | MMarcoReranking | CMedQAv1 | CMedQAv2 | Avg |
|---|---|---|---|---|---|
| 360Zhinao-1.8B-Reranking | 68.55 | 37.29 | 86.75 | 87.92 | 70.13 |
| piccolo-large-zh-v2 | 67.15 | 33.39 | 90.14 | 89.31 | 70 |
| Baichuan-text-embedding | 67.85 | 34.3 | 88.46 | 88.06 | 69.67 |
| stella-mrl-large-zh-v3.5-1792d | 66.43 | 28.85 | 89.18 | 89.33 | 68.45 |
| PEG | 69.43 | 33.55 | 86.56 | 84.09 | 68.41 |
| bge-reranker-base | 67.28 | 35.46 | 81.27 | 84.1 | 67.03 |
| bge-reranker-large | 67.6 | 37.17 | 82.14 | 84.19 | 67.78 |
pip install -r requirements.txt1git clone https://github.com/Dao-AILab/flash-attention
2cd flash-attention && pip install .
3# The installation below is optional and might be slow.
4# pip install csrc/layer_norm
5# No need to install the following if the flash-attn version is above 2.1.1.
6# pip install csrc/rotaryFLASH_ATTENTION_FORCE_BUILD=TRUE ./miniconda3/bin/python -m pip install flash-attn==2.3.61from typing import cast, List, Union, Tuple, Dict, Optional
2
3import numpy as np
4import torch
5from tqdm import tqdm
6from transformers import AutoModel, AutoTokenizer, AutoModelForSequenceClassification
7import transformers
8from transformers.trainer_pt_utils import LabelSmoother
9IGNORE_TOKEN_ID = LabelSmoother.ignore_index
10
11def preprocess(
12 sources,
13 tokenizer: transformers.PreTrainedTokenizer,
14 max_len: int = 1024,
15 system_message: str = "",
16 device = None,
17) -> Dict:
18 roles = {"user": "<|im_start|>user", "assistant": "<|im_start|>assistant"}
19 answer_len = 64
20
21 im_start = tokenizer.im_start_id
22 im_end = tokenizer.im_end_id
23 nl_tokens = tokenizer('\n').input_ids
24 _system = tokenizer('system').input_ids + nl_tokens
25 _user = tokenizer('user').input_ids + nl_tokens
26 _assistant = tokenizer('assistant').input_ids + nl_tokens
27
28 # Apply prompt templates
29 input_ids, targets = [], []
30 for i, source in enumerate(sources):
31 ## system_message
32 input_id, target = [], []
33 system = [im_start] + _system + tokenizer(system_message, max_length=max_len-answer_len, truncation=True).input_ids + [im_end] + nl_tokens
34 input_id += system
35 target += [im_start] + [IGNORE_TOKEN_ID] * (len(system)-3) + [im_end] + nl_tokens
36 assert len(input_id) == len(target)
37
38 ## query ans
39 source = "\n\n".join(source)
40 role = "<|im_start|>user"
41 _input_id = tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids + nl_tokens + \
42 tokenizer(source, max_length=max_len-answer_len, truncation=True).input_ids + [im_end] + nl_tokens
43 input_id += _input_id
44 if role == '<|im_start|>user':
45 _target = [im_start] + [IGNORE_TOKEN_ID] * (len(_input_id)-3) + [im_end] + nl_tokens
46 elif role == '<|im_start|>assistant':
47 _target = [im_start] + [IGNORE_TOKEN_ID] * len(tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids) + \
48 _input_id[len(tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids)+1:-2] + [im_end] + nl_tokens
49 else:
50 raise NotImplementedError
51 target += _target
52
53 ## label use placeholder 0; It will be masked later in the modeling_zhinao.py
54 role = "<|im_start|>assistant"
55 _input_id = tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids + nl_tokens + \
56 tokenizer("0", max_length=max_len-answer_len, truncation=True).input_ids + [im_end] + nl_tokens
57 input_id += _input_id
58 if role == '<|im_start|>user':
59 _target = [im_start] + [IGNORE_TOKEN_ID] * (len(_input_id)-3) + [im_end] + nl_tokens
60 elif role == '<|im_start|>assistant':
61 _target = [im_start] + [IGNORE_TOKEN_ID] * len(tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids) + \
62 _input_id[len(tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids)+1:-2] + [im_end] + nl_tokens
63 else:
64 raise NotImplementedError
65 target += _target
66
67 assert len(input_id) == len(target)
68 input_id += [tokenizer.pad_token_id] * (max_len - len(input_id))
69 target += [IGNORE_TOKEN_ID] * (max_len - len(target))
70 if len(input_id) > max_len:
71 print("max_len_error")
72 print(tokenizer.decode(input_id))
73
74 input_ids.append(input_id[:max_len])
75 targets.append(target[:max_len])
76 input_ids = torch.tensor(input_ids, dtype=torch.int)
77 targets = torch.tensor(targets, dtype=torch.int)
78 #print(f"input_ids {input_ids.shape}")
79 #print(f"targets {targets.shape}")
80
81 return dict(
82 input_ids=input_ids.to(device),
83 labels=targets.to(device),
84 attention_mask=input_ids.ne(tokenizer.pad_token_id).to(device),
85 )
86
87class FlagRerankerCustom:
88 def __init__(
89 self,
90 model_name_or_path: str = None,
91 use_fp16: bool = False
92 ) -> None:
93 self.tokenizer = transformers.AutoTokenizer.from_pretrained(
94 model_name_or_path,
95 model_max_length=1024,
96 padding_side="right",
97 use_fast=False,
98 trust_remote_code=True
99 )
100 self.tokenizer.pad_token_id = self.tokenizer.eod_id
101 config = transformers.AutoConfig.from_pretrained(
102 model_name_or_path,
103 trust_remote_code=True,
104 bf16=True,
105 )
106 config.use_cache = False
107 self.model = transformers.AutoModelForCausalLM.from_pretrained(
108 model_name_or_path,
109 config=config,
110 trust_remote_code=True,
111 )
112 self.model.linear.bfloat16()
113
114 if torch.cuda.is_available():
115 self.device = torch.device('cuda')
116 elif torch.backends.mps.is_available():
117 self.device = torch.device('mps')
118 else:
119 self.device = torch.device('cpu')
120 use_fp16 = False
121 if use_fp16:
122 self.model.half()
123
124 self.model = self.model.to(self.device)
125
126 self.model.eval()
127
128 self.num_gpus = torch.cuda.device_count()
129 if self.num_gpus > 1:
130 print(f"----------using {self.num_gpus}*GPUs----------")
131 self.model = torch.nn.DataParallel(self.model)
132
133 @torch.no_grad()
134 def compute_score(self, sentence_pairs: Union[List[Tuple[str, str]], Tuple[str, str]], batch_size: int =128,
135 max_length: int = 1024) -> List[float]:
136 if self.num_gpus > 0:
137 batch_size = batch_size * self.num_gpus
138
139 assert isinstance(sentence_pairs, list)
140 if isinstance(sentence_pairs[0], str):
141 sentence_pairs = [sentence_pairs]
142
143 all_scores = []
144 for start_index in tqdm(range(0, len(sentence_pairs), batch_size), desc="Compute Scores",
145 disable=False):
146 sentences_batch = sentence_pairs[start_index:start_index + batch_size] # [[q,ans],[q, ans]...]
147 inputs = preprocess(sources=sentences_batch, tokenizer=self.tokenizer,max_len=1024,device=self.device)
148 scores = self.model(**inputs, return_dict=True).logits.view(-1, ).float()
149 all_scores.extend(scores.cpu().numpy().tolist())
150
151 if len(all_scores) == 1:
152 return all_scores[0]
153 return all_scores
154
155
156if __name__ == "__main__":
157 model_name_or_path = "360Zhinao-1.8B-Reranking"
158 model = FlagRerankerCustom(model_name_or_path, use_fp16=False)
159 inputs=[["What Color Is the Sky","Blue"], ["What Color Is the Sky","Pink"],]
160 ret = model.compute_score(inputs)
161 print(ret)
162