DongfuJiang commited on
Commit
2107a44
1 Parent(s): 51fcf35
Files changed (5) hide show
  1. README.md +1 -1
  2. app.py +2 -4
  3. bak_requirements.txt +0 -8
  4. requirements.txt +6 -5
  5. tigerscore.py +388 -0
README.md CHANGED
@@ -5,7 +5,7 @@ colorFrom: indigo
5
  colorTo: pink
6
  sdk: gradio
7
  app_file: app.py
8
- python_version: 3.9
9
  pinned: false
10
  license: mit
11
  ---
 
5
  colorTo: pink
6
  sdk: gradio
7
  app_file: app.py
8
+ python_version: 3.10
9
  pinned: false
10
  license: mit
11
  ---
app.py CHANGED
@@ -1,13 +1,9 @@
1
  import os
2
- # os.environ["HF_HOME"] = "/data/.huggingface"
3
  import gradio as gr
4
  import sys
5
  import copy
6
  import spaces
7
  from datasets import load_dataset
8
- from typing import List
9
- from llama_cpp import Llama
10
- from huggingface_hub import hf_hub_download
11
  from string import Template
12
  from tigerscore import TIGERScorer
13
 
@@ -50,6 +46,8 @@ For each error you give in the response, please also elaborate the following inf
50
  Your evaluation output:
51
  """
52
 
 
 
53
  # llm = Llama(
54
  # model_path=hf_hub_download(
55
  # repo_id=os.environ.get("REPO_ID", "TIGER-Lab/TIGERScore-13B-GGUF"),
 
1
  import os
 
2
  import gradio as gr
3
  import sys
4
  import copy
5
  import spaces
6
  from datasets import load_dataset
 
 
 
7
  from string import Template
8
  from tigerscore import TIGERScorer
9
 
 
46
  Your evaluation output:
47
  """
48
 
49
+ # from huggingface_hub import hf_hub_download
50
+ # from llama_cpp import Llama
51
  # llm = Llama(
52
  # model_path=hf_hub_download(
53
  # repo_id=os.environ.get("REPO_ID", "TIGER-Lab/TIGERScore-13B-GGUF"),
bak_requirements.txt DELETED
@@ -1,8 +0,0 @@
1
- git+https://github.com/TIGER-AI-Lab/TIGERScore.git
2
- datasets
3
- torch
4
- gradio==4.24.0
5
- spaces
6
- # multiprocess==0.70.15
7
- sentencepiece
8
- eval_type_backport
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,8 +1,9 @@
1
- git+https://github.com/TIGER-AI-Lab/TIGERScore.git
2
  datasets
3
  torch
4
- gradio==4.24.0
5
- spaces
6
- # multiprocess==0.70.15
7
  sentencepiece
8
- eval_type_backport
 
 
 
 
1
+ transformers
2
  datasets
3
  torch
4
+ gradio
 
 
5
  sentencepiece
6
+ tiktoken
7
+ spaces
8
+ accelerate
9
+ protobuf
tigerscore.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import regex as re
3
+ import importlib
4
+ from string import Template
5
+ from typing import List
6
+ from tqdm import tqdm
7
+
8
+ TEMPLATE = """You are evaluating errors in a model-generated output for a given instruction.
9
+ Instruction:
10
+ ${generation_instruction}
11
+ ${input_context}
12
+
13
+ Model-generated Output:
14
+ ${hypothesis_output}
15
+
16
+ For each error you give in the response, please also elaborate the following information:
17
+ - error location (the words that are wrong in the output)
18
+ - error aspect it belongs to.
19
+ - explanation why it's an error, and the correction suggestions.
20
+ - severity of the error ("Major" or "Minor").
21
+ - reduction of score (between 0.5 and 5 given the severity of the error)
22
+
23
+ Your evaluation output:
24
+ """
25
+
26
+ class TIGERScorer(object):
27
+ def __init__(self, model_name, quantized=False, use_vllm=False, use_llamacpp=False):
28
+ """Initialize the TIGERScore model.
29
+
30
+ Args:
31
+ model_name:
32
+ basic model names:
33
+ - "TIGER-Lab/TIGERScore-7B",
34
+ - "TIGER-Lab/TIGERScore-13B",
35
+ for llamacpp models:
36
+ - "TIGER-Lab/TIGERScore-7B-GGUF",
37
+ - "TIGER-Lab/TIGERScore-13B-GGUF",
38
+ quantized (Run on GPU):
39
+ If true, load the 4-bit quantized version of the model.
40
+ quantized version occupies 2-3 times less memory but will running slower.
41
+ use_vllm (Run on GPU):
42
+ If true, use the VLLM version of the model. The inference speed can be 0.2s per input.
43
+ if false, use the Hugging face inference API. The inference speed can be slower.
44
+ vllm currently does not work with quantized models, so quantized will be ignored if use_vllm is true.
45
+ use_llamacpp (Run on CPU):
46
+ True indicates that the model_name is a path to a llamacpp model to run on the CPU.
47
+ Will ignore use_vllm if True.
48
+ """
49
+ self.model_name = model_name
50
+ self.use_vllm = use_vllm
51
+ self.quantized = quantized
52
+ self.use_llamacpp = use_llamacpp
53
+ self.tokenizer = None
54
+ if use_llamacpp:
55
+ if use_vllm:
56
+ print("Warning: use_vllm is ignored when use_llamacpp is True.")
57
+ # assert model_name.endswith(".gguf"), "llamacpp model name should end with .gguf, please check if this model is a valid llamacpp model."
58
+ if not os.path.exists(model_name):
59
+ from huggingface_hub import hf_hub_download
60
+ import llama_cpp
61
+ model_path = hf_hub_download(repo_id=model_name, filename="ggml-model-q4_0.gguf")
62
+ self.model = llama_cpp.Llama(model_path, n_ctx=1024)
63
+ else:
64
+ self.model = llama_cpp.Llama(model_name, n_ctx=1024)
65
+ elif use_vllm:
66
+ import torch
67
+ import vllm
68
+ num_gpus = torch.cuda.device_count()
69
+ self.model = vllm.LLM(model_name, dtype=torch.bfloat16, tensor_parallel_size=num_gpus)
70
+ else:
71
+ import torch
72
+ from transformers import AutoTokenizer, AutoModelForCausalLM
73
+ if quantized:
74
+ self.model = AutoModelForCausalLM.from_pretrained(
75
+ model_name,
76
+ torch_dtype=torch.bfloat16,
77
+ device_map="auto",
78
+ load_in_4bit=True,
79
+ )
80
+ else:
81
+ self.model = AutoModelForCausalLM.from_pretrained(
82
+ model_name,
83
+ torch_dtype=torch.bfloat16,
84
+ device_map="auto"
85
+ )
86
+ self.tokenizer = AutoTokenizer.from_pretrained(
87
+ model_name,
88
+ padding_side="left",
89
+ )
90
+ self.template = Template(TEMPLATE)
91
+
92
+ def decode_tigerscore_output(self, output):
93
+ """Decode the output of TIGERScore model into structured error explanations.
94
+
95
+ Args:
96
+ output (str):
97
+ the output of TIGERScore model.
98
+ Returns:
99
+ errors (List[Dict]):
100
+ structured error explanations for each error in the output.
101
+ Each error explanation is a dictionary with the following fields:
102
+ - error_location (str): the words that are wrong in the output
103
+ - error_aspect (str): the aspect of the error
104
+ - error_explanation (str): explanation why it's an error, and the correction suggestions
105
+ - error_severity (str): severity of the error ("Major" or "Minor")
106
+ - score_reduction (float): reduction of score (between 0.5 and 5 given the severity of the error)
107
+ There can be multiple errors in each input.
108
+ """
109
+ result = {}
110
+ result['num_errors'] = re.search(
111
+ r"(?<=The model-generated output contains )\d+(?= errors)", output).group(0)
112
+ result['score'] = re.search(
113
+ r"(?<=, with a total score reduction of )\d+", output).group(0)
114
+ result['num_errors'] = int(result['num_errors'])
115
+ result['score'] = -float(result['score'])
116
+ result['errors'] = {}
117
+ error_locations = re.findall(
118
+ r"(?<=Error location \d+:[ \n]*).*?(?=\n)", output)
119
+ error_aspects = re.findall(r"(?<=Error aspect \d+:[ \n]*).*?(?=\n)", output)
120
+ error_explanations = re.findall(
121
+ r"(?<=Explanation \d+:[ \n]*).*?(?=\n)", output)
122
+ error_severities = re.findall(r"(?<=Severity \d+:[ \n]*).*?(?=\n)", output)
123
+ score_reductions = re.findall(
124
+ r"(?<=\nScore reduction \d+:[ \n]*)(\d+\.\d+|\d+)", output)
125
+ assert len(error_locations) == len(error_aspects) == len(error_explanations) == len(error_severities) == len(score_reductions), \
126
+ "The number of errors does not match."
127
+ for i in range(len(error_locations)):
128
+ error = {}
129
+ error['location'] = error_locations[i].strip("\n ")
130
+ error['aspect'] = error_aspects[i].strip("\n ")
131
+ error['explanation'] = error_explanations[i].strip("\n ")
132
+ error['severity'] = error_severities[i].strip("\n ")
133
+ error['score_reduction'] = score_reductions[i].strip("\n ")
134
+ result['errors'][f"error_{i}"] = error
135
+ return result
136
+
137
+ def _run_batch(self, prompts: List[str], **generate_kwargs):
138
+ """Internal function to score a batch of inputs.
139
+ Args:
140
+ prompts (List[str]):
141
+ a list of prompts.
142
+ generate_kwargs:
143
+ keyword arguments for the model.generate() method.
144
+ See https://huggingface.co/transformers/main_classes/model.html
145
+ Returns:
146
+ completions (List[str]):
147
+ """
148
+ encodings = self.tokenizer(prompts, return_tensors="pt", padding=True,
149
+ truncation=True, max_length=self.tokenizer.model_max_length)
150
+ input_ids = encodings["input_ids"].to(self.model.device)
151
+ attention_mask = encodings["attention_mask"].to(self.model.device)
152
+ gen_params = {
153
+ "input_ids": input_ids,
154
+ "attention_mask": attention_mask,
155
+ "max_new_tokens": 1024,
156
+ "do_sample": False,
157
+ "top_p": 1.0,
158
+ "temperature": 0.7,
159
+ "num_return_sequences": 1,
160
+ }
161
+ gen_params.update(generate_kwargs)
162
+ outputs = self.model.generate(**gen_params)
163
+
164
+ # input_len = input_ids.shape[1]
165
+ # completion_ids = [output[input_len:] for output in outputs]
166
+ completion_ids = outputs
167
+ completions = [self.tokenizer.decode(
168
+ completion, skip_special_tokens=True) for completion in completion_ids]
169
+ return completions
170
+
171
+ def generate_stream(self, instruction, hypo_output, input_context=None, **generate_kwargs):
172
+ prompt_template = self.template
173
+ prompt = prompt_template.substitute(
174
+ generation_instruction=instruction,
175
+ input_context=input_context,
176
+ hypothesis_output=hypo_output
177
+ ).strip("\n ")
178
+
179
+ if self.use_llamacpp:
180
+ gen_params = {
181
+ "max_tokens": generate_kwargs.get("max_new_tokens", 1024),
182
+ "top_p": generate_kwargs.get("top_p", 1.0),
183
+ "top_k": generate_kwargs.get("top_k", 40),
184
+ "temperature": generate_kwargs.get("temperature", 0.7),
185
+ "frequency_penalty": generate_kwargs.get("frequency_penalty", 0.0),
186
+ "presence_penalty": generate_kwargs.get("presence_penalty", 0.0),
187
+ "echo": False,
188
+ "stream": True
189
+ }
190
+ unused_params = [key for key in generate_kwargs.keys() if key not in gen_params]
191
+ if len(unused_params) > 0:
192
+ print(f"Warning: the following parameters are not used in llamacpp inference: {unused_params}")
193
+ output = ""
194
+ for _output in self.model(prompt, **gen_params):
195
+ output += _output["choices"][0]["text"]
196
+ yield output
197
+ elif self.use_vllm:
198
+ raise NotImplementedError("VLLM does not support streaming generation.")
199
+ else:
200
+ from transformers import TextIteratorStreamer, pipeline
201
+ from threading import Thread
202
+ streamer = TextIteratorStreamer(self.tokenizer, skip_prompt=True, skip_special_tokens=True)
203
+ encodings = self.tokenizer(prompt, return_tensors="pt", padding=True,
204
+ truncation=True, max_length=self.tokenizer.model_max_length)
205
+ input_ids = encodings["input_ids"].to(self.model.device)
206
+ attention_mask = encodings["attention_mask"].to(self.model.device)
207
+ gen_params = {
208
+ "input_ids": input_ids,
209
+ "attention_mask": attention_mask,
210
+ "max_new_tokens": 1024,
211
+ "do_sample": False,
212
+ "top_p": 1.0,
213
+ "temperature": 0.7,
214
+ "num_return_sequences": 1,
215
+ "streamer": streamer,
216
+ }
217
+ gen_params.update(generate_kwargs)
218
+ thread = Thread(target=self.model.generate, kwargs=gen_params)
219
+ thread.start()
220
+ output = ""
221
+ for _output in streamer:
222
+ output += _output
223
+ yield output
224
+
225
+ # return output
226
+ def score(
227
+ self,
228
+ insts: List[str],
229
+ hypo_outputs: List[str],
230
+ input_contexts: List[str]=None,
231
+ batch_size: int = 2,
232
+ **generate_kwargs
233
+ ):
234
+ """Score and identify errors in the model-generated outputs
235
+
236
+ Example Usage:
237
+ ```python
238
+ import os
239
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
240
+ from datasets import load_dataset
241
+ from tigerscore import TIGERScorer
242
+ scorer = TIGERScorer(model_size="7b", quantized=True)
243
+ dataset = load_dataset("TIGER-Lab/MetricInstruct")
244
+ num_few_examples = 10
245
+ tasks = dataset["train_mix"]['task'][0:num_few_examples]
246
+ insts = dataset["train_mix"]['instruction'][0:num_few_examples]
247
+ input_contexts = dataset["train_mix"]['input_context'][0:num_few_examples]
248
+ hypo_output = dataset["train_mix"]['hypo_output'][0:num_few_examples]
249
+ results = scorer.score(tasks, insts, input_contexts, hypo_output)
250
+ scores = [result["score"] for result in results]
251
+ print(results)
252
+ ```
253
+
254
+ Args:
255
+ insts:
256
+ a list of instruction strings; One instruction example is:
257
+ "Translate the following text from German to English."
258
+ A instruction is a short description of the task.
259
+ It contains specific requirements for the model-generated output.
260
+ hypo_outputs:
261
+ a list of hypothesis outputs; One hypothesis output example is the model-generated English translation.
262
+ input_contexts:
263
+ a list of input contexts; One input context example is the source German text.
264
+ batch_size:
265
+ batch size for scoring.
266
+ use_vllm:
267
+ if True, use VLLM to inference.
268
+ generate_kwargs:
269
+ keyword arguments for the model.generate() method.
270
+ See https://huggingface.co/transformers/main_classes/model.html
271
+ Returns:
272
+ results (List[Dict]):
273
+ Contains the following fields:
274
+ - score (float): the TIGERScore score for the input.
275
+ - num_errors (int): the number of errors in the input.
276
+ - errors (List[Dict]): structured error explanations for each error in the input.
277
+ - location (str): the words that are wrong in the output
278
+ - aspect (str): the aspect of the error
279
+ - explanation (str): explanation why it's an error, and the correction suggestions
280
+ - severity (str): severity of the error ("Major" or "Minor")
281
+ - reduction (float): reduction of score (between 0.5 and 5 given the severity of the error)
282
+ - raw_output (str): the raw output of the TIGERScore model.
283
+ """
284
+ assert len(insts) == len(input_contexts) == len(hypo_outputs), \
285
+ "The number of inputs does not match."
286
+ prompt_template = self.template
287
+ prompts = [
288
+ prompt_template.substitute(
289
+ generation_instruction=inst,
290
+ input_context=input_context,
291
+ hypothesis_output=hypo_output
292
+ ).strip("\n ")
293
+ for inst, input_context, hypo_output in zip(insts, input_contexts, hypo_outputs)
294
+ ]
295
+
296
+ if self.use_llamacpp:
297
+ gen_params = {
298
+ "max_tokens": generate_kwargs.get("max_new_tokens", 1024),
299
+ "top_p": generate_kwargs.get("top_p", 1.0),
300
+ "top_k": generate_kwargs.get("top_k", 40),
301
+ "temperature": generate_kwargs.get("temperature", 0.7),
302
+ "frequency_penalty": generate_kwargs.get("frequency_penalty", 0.0),
303
+ "presence_penalty": generate_kwargs.get("presence_penalty", 0.0),
304
+ "echo": False,
305
+ "stream": generate_kwargs.get("stream", False),
306
+ }
307
+ unused_params = [key for key in generate_kwargs.keys() if key not in gen_params]
308
+ if len(unused_params) > 0:
309
+ print(f"Warning: the following parameters are not used in llamacpp inference: {unused_params}")
310
+ outputs = []
311
+ for prompt in tqdm(prompts, desc="TIGERScore (llamacpp) Batch Scoring"):
312
+ output = self.model(prompt, **gen_params)
313
+ outputs.append(output)
314
+ completions = [output['choices'][0]['text'] for output in outputs]
315
+ elif self.use_vllm:
316
+ import vllm
317
+ sampling_params = vllm.SamplingParams(
318
+ max_tokens=1024,
319
+ top_p=1.0,
320
+ temperature=0.7,
321
+ n=1,
322
+ )
323
+ for key, value in generate_kwargs.items():
324
+ if hasattr(sampling_params, key):
325
+ setattr(sampling_params, key, value)
326
+ vllm_outputs = self.model.generate(
327
+ prompts,
328
+ sampling_params=sampling_params,
329
+ )
330
+ completions = [output.outputs[0].text for output in vllm_outputs]
331
+ else:
332
+ completions = []
333
+ for i in tqdm(
334
+ range(0, len(prompts), batch_size),
335
+ desc="TIGERScore Batch Scoring",
336
+ total=len(prompts) // batch_size + 1
337
+ ):
338
+ batch_prompts = prompts[i:i+batch_size]
339
+ batch_completions = self._run_batch(batch_prompts, **generate_kwargs)
340
+ completions.extend(batch_completions)
341
+
342
+ tigerscore_results = []
343
+ for completion in completions:
344
+ try:
345
+ result = self.decode_tigerscore_output(completion)
346
+ result['score'] = result['score']
347
+ result['num_errors'] = result['num_errors']
348
+ result['errors'] = result['errors']
349
+ except Exception:
350
+ result = {}
351
+ result['score'] = None
352
+ result['num_errors'] = None
353
+ result['errors'] = None
354
+ result['raw_output'] = completion
355
+ tigerscore_results.append(result)
356
+ return tigerscore_results
357
+
358
+ if __name__ == "__main__":
359
+ instruction = "Write an apology letter."
360
+ input_context = "Reason: You canceled a plan at the last minute due to illness."
361
+ hypo_output = "Hey [Recipient],\n\nI'm really sorry for ditching our plan. I suddenly got an opportunity for a vacation so I took it. I know this might have messed up your plans and I regret that.\n\nDespite being under the weather, I would rather go for an adventure. I hope you can understand my perspective and I hope this incident doesn't change anything between us.\n\nWe can reschedule our plan for another time. Sorry again for the trouble.\n\nPeace out,\n[Your Name]\n\n---"
362
+
363
+ # scorer = TIGERScorer(model_name="TIGER-Lab/TIGERScore-7B")
364
+ scorer = TIGERScorer(model_name="TIGER-Lab/TIGERScore-7B", quantized=True)
365
+ # scorer = TIGERScorer(model_name="TIGER-Lab/TIGERScore-7B", use_vllm=True)
366
+ # scorer = TIGERScorer(model_name="TIGER-Lab/TIGERScore-7B-GGUF", use_llamacpp=True)
367
+ results = scorer.score([instruction], [hypo_output], [input_context])
368
+ print(results)
369
+ # {
370
+ # "num_errors": 2,
371
+ # "score": -8.0,
372
+ # "errors": {
373
+ # "error_0": {
374
+ # "location": "I suddenly got an opportunity for a vacation so I took it.",
375
+ # "aspect": "Incorrect reasoning",
376
+ # "explanation": "The error is in the reasoning provided for the cancellation. The original reason was due to illness, but the model generated an apology letter implying that the cancellation was due to a vacation opportunity, which is incorrect. The correction would be to maintain the original reason for the cancellation.",
377
+ # "severity": "Major",
378
+ # "score_reduction": "4.0"
379
+ # },
380
+ # "error_1": {
381
+ # "location": "Hey [Recipient]",
382
+ # "aspect": "Inappropriate language or tone",
383
+ # "explanation": "The opening salutation used by the model is too informal and not appropriate for an apology letter. The correction would be to use a more formal and respectful salutation such as \"Dear [Recipient]\".",
384
+ # "severity": "Major",
385
+ # "score_reduction": "4.0"
386
+ # }
387
+ # },
388
+ # }