evalscope 0.16.0__py3-none-any.whl → 0.16.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of evalscope might be problematic. Click here for more details.

Files changed (61) hide show
  1. evalscope/app/__init__.py +28 -0
  2. evalscope/{report → app}/app.py +20 -25
  3. evalscope/app/constants.py +21 -0
  4. evalscope/arguments.py +2 -1
  5. evalscope/backend/opencompass/backend_manager.py +2 -1
  6. evalscope/backend/rag_eval/cmteb/arguments.py +4 -1
  7. evalscope/backend/rag_eval/cmteb/task_template.py +19 -3
  8. evalscope/backend/rag_eval/cmteb/tasks/CustomTask.py +1 -1
  9. evalscope/backend/rag_eval/utils/embedding.py +75 -35
  10. evalscope/benchmarks/benchmark.py +1 -0
  11. evalscope/benchmarks/data_adapter.py +97 -16
  12. evalscope/benchmarks/docmath/__init__.py +0 -0
  13. evalscope/benchmarks/docmath/docmath_adapter.py +84 -0
  14. evalscope/benchmarks/docmath/utils.py +220 -0
  15. evalscope/benchmarks/frames/__init__.py +0 -0
  16. evalscope/benchmarks/frames/frames_adapter.py +90 -0
  17. evalscope/benchmarks/frames/utils.py +37 -0
  18. evalscope/benchmarks/needle_haystack/__init__.py +0 -0
  19. evalscope/benchmarks/needle_haystack/needle_haystack_adapter.py +341 -0
  20. evalscope/benchmarks/needle_haystack/utils.py +79 -0
  21. evalscope/benchmarks/tool_bench/tool_bench_adapter.py +4 -1
  22. evalscope/benchmarks/tool_bench/utils.py +5 -4
  23. evalscope/benchmarks/utils.py +25 -0
  24. evalscope/cli/start_app.py +2 -2
  25. evalscope/collections/__init__.py +35 -3
  26. evalscope/collections/evaluator.py +18 -6
  27. evalscope/config.py +8 -2
  28. evalscope/evaluator/evaluator.py +38 -27
  29. evalscope/metrics/__init__.py +3 -1
  30. evalscope/metrics/bundled_rouge_score/rouge_scorer.py +1 -1
  31. evalscope/metrics/llm_judge.py +12 -5
  32. evalscope/metrics/math_parser.py +1 -1
  33. evalscope/models/adapters/server_adapter.py +2 -6
  34. evalscope/perf/arguments.py +2 -2
  35. evalscope/perf/benchmark.py +0 -9
  36. evalscope/perf/main.py +7 -0
  37. evalscope/perf/plugin/datasets/custom.py +15 -0
  38. evalscope/perf/utils/benchmark_util.py +1 -1
  39. evalscope/perf/utils/local_server.py +1 -0
  40. evalscope/perf/utils/log_utils.py +12 -5
  41. evalscope/perf/utils/rich_display.py +1 -1
  42. evalscope/report/__init__.py +36 -4
  43. evalscope/report/combinator.py +8 -0
  44. evalscope/report/generator.py +33 -9
  45. evalscope/report/utils.py +60 -3
  46. evalscope/run.py +12 -0
  47. evalscope/utils/logger.py +1 -1
  48. evalscope/utils/utils.py +12 -0
  49. evalscope/version.py +2 -2
  50. {evalscope-0.16.0.dist-info → evalscope-0.16.1.dist-info}/METADATA +13 -11
  51. {evalscope-0.16.0.dist-info → evalscope-0.16.1.dist-info}/RECORD +61 -50
  52. tests/aigc/test_t2i.py +40 -3
  53. tests/cli/test_all.py +39 -35
  54. tests/cli/test_collection.py +7 -6
  55. tests/cli/test_run.py +21 -11
  56. tests/rag/test_mteb.py +5 -5
  57. /evalscope/{report/app_arguments.py → app/arguments.py} +0 -0
  58. {evalscope-0.16.0.dist-info → evalscope-0.16.1.dist-info}/LICENSE +0 -0
  59. {evalscope-0.16.0.dist-info → evalscope-0.16.1.dist-info}/WHEEL +0 -0
  60. {evalscope-0.16.0.dist-info → evalscope-0.16.1.dist-info}/entry_points.txt +0 -0
  61. {evalscope-0.16.0.dist-info → evalscope-0.16.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,341 @@
1
+ from itertools import product
2
+ from tqdm import tqdm
3
+ from typing import TYPE_CHECKING, List, Union
4
+
5
+ from evalscope.benchmarks import Benchmark, DataAdapter
6
+ from evalscope.constants import AnswerKeys, EvalType
7
+ from evalscope.metrics import LLMJudge, exact_match
8
+ from evalscope.metrics.metrics import mean
9
+ from evalscope.utils import get_logger
10
+
11
+ if TYPE_CHECKING:
12
+ from evalscope.report import Report
13
+
14
+ logger = get_logger()
15
+
16
+ PROMPT_TEMPLATE = """Please read the following text and answer the question below.
17
+
18
+ <text>
19
+ {context}
20
+ </text>
21
+
22
+ <question>
23
+ {question}
24
+ </question>
25
+
26
+ Don't give information outside the document or repeat your findings."""
27
+
28
+
29
+ @Benchmark.register(
30
+ name='needle_haystack',
31
+ pretty_name='Needle in a Haystack',
32
+ description='Needle in a Haystack is a benchmark focused on information retrieval tasks. \
33
+ It requires the model to find specific information within a large corpus of text.',
34
+ dataset_id='AI-ModelScope/Needle-in-a-Haystack-Corpus',
35
+ metric_list=['AverageAccuracy'],
36
+ subset_list=['english', 'chinese'],
37
+ few_shot_num=0,
38
+ train_split=None,
39
+ eval_split='test',
40
+ system_prompt='You are a helpful AI bot that answers questions for a user. Keep your response short and direct',
41
+ prompt_template=PROMPT_TEMPLATE,
42
+ extra_params={
43
+ 'retrieval_question': 'What is the best thing to do in San Francisco?',
44
+ 'needles':
45
+ ['\nThe best thing to do in San Francisco is eat a sandwich and sit in Dolores Park on a sunny day.\n'],
46
+ 'context_lengths_min': 1000,
47
+ 'context_lengths_max': 32000,
48
+ 'context_lengths_num_intervals': 10,
49
+ 'document_depth_percent_min': 0,
50
+ 'document_depth_percent_max': 100,
51
+ 'document_depth_percent_intervals': 10,
52
+ 'tokenizer_path': 'Qwen/Qwen3-0.6B',
53
+ })
54
+ class NeedleHaystackAdapter(DataAdapter):
55
+
56
+ def __init__(self, **kwargs):
57
+ super().__init__(**kwargs)
58
+
59
+ self.llm_as_a_judge = True
60
+ # set extra params
61
+ extra_params = kwargs.get('extra_params', {})
62
+ self.retrieval_question = extra_params.get('retrieval_question',
63
+ 'What is the best thing to do in San Francisco?')
64
+ self.needles = extra_params.get(
65
+ 'needles',
66
+ ['\nThe best thing to do in San Francisco is eat a sandwich and sit in Dolores Park on a sunny day.\n'])
67
+ self.context_lengths_min = extra_params.get('context_lengths_min', 1000)
68
+ self.context_lengths_max = extra_params.get('context_lengths_max', 32000)
69
+ self.context_lengths_num_intervals = extra_params.get('context_lengths_num_intervals', 10)
70
+ self.document_depth_percent_min = extra_params.get('document_depth_percent_min', 0)
71
+ self.document_depth_percent_max = extra_params.get('document_depth_percent_max', 100)
72
+ self.document_depth_percent_intervals = extra_params.get('document_depth_percent_intervals', 10)
73
+ self.tokenizer_path = extra_params.get('tokenizer_path', 'Qwen/Qwen3-0.6B')
74
+
75
+ self.__init_tokenizer()
76
+ self.__init_length()
77
+
78
+ def __init_length(self):
79
+ """ Initialize context lengths and document depth percentages based on the provided parameters."""
80
+ import numpy as np
81
+
82
+ self.context_lengths = np.round(
83
+ np.linspace(
84
+ self.context_lengths_min,
85
+ self.context_lengths_max,
86
+ num=self.context_lengths_num_intervals,
87
+ endpoint=True)).astype(int)
88
+
89
+ self.document_depth_percents = np.round(
90
+ np.linspace(
91
+ self.document_depth_percent_min,
92
+ self.document_depth_percent_max,
93
+ num=self.document_depth_percent_intervals,
94
+ endpoint=True)).astype(int)
95
+
96
+ def __init_tokenizer(self):
97
+ """ Initialize the tokenizer based on the provided tokenizer path."""
98
+ from modelscope import AutoTokenizer
99
+ self.tokenizer = AutoTokenizer.from_pretrained(self.tokenizer_path)
100
+
101
+ def load(self, **kwargs):
102
+ # default load with snapshot
103
+ kwargs['file_structure'] = {'english': ['PaulGraham_Essays.txt'], 'chinese': ['Journey_to_the_West.txt']}
104
+ data_dict = super().load_with_snapshot(**kwargs)
105
+ return data_dict
106
+
107
+ def gen_prompts(self, data_dict: dict) -> dict:
108
+ """
109
+ Generate dataset prompts from raw input, unify the prompt format for different datasets.
110
+
111
+ Args:
112
+ data_dict: {'english': {'test': [sample_d_1, sample_d_2, ...]},
113
+ 'chinese': {'test': [sample_d_1, sample_d_2, ...]}}
114
+
115
+ Returns:
116
+ {'subset_name': [prompt_d_1, prompt_d_2, ...]}
117
+ prompt_d_i (dict): refer to the output of gen_prompt method.
118
+
119
+ e.g. train -- few-shot data, test -- target dataset to evaluate.
120
+ """
121
+ res_dict: dict = {}
122
+
123
+ for sub_name, sub_data_dict in data_dict.items():
124
+ res_dict[sub_name] = []
125
+ for sample_d in sub_data_dict[self.eval_split]:
126
+ # Generate prompts for each sample in the dataset
127
+ tokens_context = self._get_context_tokens(sample_d['text'])
128
+ for context_length, depth_percent in tqdm(
129
+ product(self.context_lengths, self.document_depth_percents),
130
+ desc=f'Generating {sub_name} prompts'):
131
+ # Insert needles into the context at the specified depth percentage
132
+ context = self._insert_needles(tokens_context, depth_percent, context_length)
133
+ # Build the input dictionary for the prompt
134
+ input_d = {
135
+ 'context_length': int(context_length),
136
+ 'depth_percent': int(depth_percent),
137
+ 'question': self.retrieval_question,
138
+ 'answer': '\n'.join(self.needles),
139
+ 'context': context,
140
+ }
141
+ prompt_d = self.gen_prompt(input_d=input_d)
142
+ prompt_d[AnswerKeys.RAW_INPUT] = input_d
143
+ res_dict[sub_name].append(prompt_d)
144
+
145
+ return res_dict
146
+
147
+ def _get_context_tokens(self, input_context: str) -> list:
148
+ """
149
+ Encodes the context string into tokens using the tokenizer, ensuring the tokenized context
150
+ is at least as long as the maximum context length required.
151
+
152
+ Args:
153
+ input_context (str): The context string to be tokenized.
154
+
155
+ Returns:
156
+ List[int]: A list of token IDs representing the context.
157
+ """
158
+ max_context_length = max(self.context_lengths)
159
+ context = input_context
160
+ tokens_context = self.tokenizer.encode(context, add_special_tokens=False)
161
+ # Repeat the context until reaching the required length
162
+ while len(tokens_context) < max_context_length:
163
+ context += '\n' + input_context
164
+ tokens_context = self.tokenizer.encode(context, add_special_tokens=False)
165
+ return tokens_context
166
+
167
+ def _insert_needles(self, tokens_context, depth_percent, context_length):
168
+ """
169
+ Inserts multiple needles (specific facts or pieces of information) into the original context string at
170
+ designated depth percentages, effectively distributing these needles throughout the context. This method
171
+ is designed to test a model's ability to retrieve specific information (needles) from a larger body of text
172
+ (haystack) based on the placement depth of these needles.
173
+
174
+ The method first encodes the context and each needle into tokens to calculate their lengths in tokens.
175
+ It then adjusts the context length to accommodate the final buffer length. This is crucial for ensuring
176
+ that the total token count (context plus needles) does not exceed the maximum allowable context length,
177
+ which might otherwise lead to information being truncated.
178
+
179
+ This approach calculates the initial insertion point for the first needle as before but then calculates even
180
+ spacing for the remaining needles based on the remaining context length. It ensures that needles are
181
+ distributed as evenly as possible throughout the context after the first insertion.
182
+
183
+ Args:
184
+ tokens_context (List[int]): The original context tokens.
185
+ depth_percent (float): The depth percent at which to insert the needles.
186
+ context_length (int): The total length of the context in tokens, adjusted for final buffer.
187
+
188
+ Returns:
189
+ str: The new context with needles inserted.
190
+ """
191
+
192
+ context_length -= 150
193
+
194
+ # Calculate the total length of all needles in tokens
195
+ total_needles_length = sum(len(self.tokenizer.encode(needle)) for needle in self.needles)
196
+
197
+ # Ensure context length accounts for needles
198
+ if len(tokens_context) + total_needles_length > context_length:
199
+ tokens_context = tokens_context[:context_length - total_needles_length]
200
+
201
+ # To evenly distribute the needles, we calculate the intervals they need to be inserted.
202
+ depth_percent_interval = (100 - depth_percent) / len(self.needles)
203
+
204
+ # Reset the insertion percentages list for the current context
205
+ self.insertion_percentages = []
206
+
207
+ # Insert needles at calculated points
208
+ for needle in self.needles:
209
+
210
+ tokens_needle = self.tokenizer.encode(needle)
211
+
212
+ if depth_percent == 100:
213
+ # If your depth percent is 100 (which means your needle is the last thing in the doc),
214
+ # throw it at the end
215
+ tokens_context = tokens_context + tokens_needle
216
+ else:
217
+ # Go get the position (in terms of tokens) to insert your needle
218
+ insertion_point = int(len(tokens_context) * (depth_percent / 100))
219
+
220
+ # tokens_new_context represents the tokens before the needle
221
+ tokens_new_context = tokens_context[:insertion_point]
222
+
223
+ # We want to make sure that we place our needle at a sentence break
224
+ # so we first see what token a '.' is
225
+ period_tokens = self.tokenizer.encode('.') + self.tokenizer.encode(
226
+ '。') # Handle both English and Chinese periods
227
+
228
+ # Then we iteration backwards until we find the first period
229
+ while tokens_new_context and tokens_new_context[-1] not in period_tokens:
230
+ insertion_point -= 1
231
+ tokens_new_context = tokens_context[:insertion_point]
232
+
233
+ # Insert the needle into the context at the found position
234
+ tokens_context = tokens_context[:insertion_point] + tokens_needle + tokens_context[insertion_point:]
235
+
236
+ # Log
237
+ insertion_percentage = (insertion_point / len(tokens_context)) * 100
238
+ self.insertion_percentages.append(insertion_percentage)
239
+ logger.debug(f"Inserted '{needle}' at {insertion_percentage:.2f}% of the context, "
240
+ f'total length now: {len(tokens_context)} tokens')
241
+
242
+ # Adjust depth for next needle
243
+ depth_percent += depth_percent_interval
244
+
245
+ new_context = self.tokenizer.decode(tokens_context)
246
+ return new_context
247
+
248
+ def gen_prompt(self, input_d: dict, **kwargs) -> dict:
249
+ """
250
+ Generate the prompt for each sample in the dataset.
251
+ Args:
252
+ input_d: A dictionary containing the input data for the prompt.
253
+ It should contain 'context' and optionally 'question'.
254
+ Returns:
255
+ A dictionary containing the prompt data
256
+ """
257
+ context = input_d.get('context')
258
+ question = input_d.get('question')
259
+
260
+ prompt = self.prompt_template.format(context=context, question=question)
261
+
262
+ return self.gen_prompt_data(prompt, system_prompt=self.system_prompt)
263
+
264
+ def get_gold_answer(self, input_d: dict) -> str:
265
+ """
266
+ Parse the raw input labels (gold).
267
+ """
268
+ return input_d.get('answer', '').strip()
269
+
270
+ def parse_pred_result(self, result: str, raw_input_d: dict = None, eval_type: str = EvalType.CHECKPOINT) -> str:
271
+ """
272
+ Parse the predicted result and extract proper answer.
273
+ """
274
+ return result
275
+
276
+ def match(self, gold: str, pred: str) -> float:
277
+ """
278
+ Match the gold answer and the predicted answer.
279
+ """
280
+ from .utils import normalize_answer
281
+ norm_gold = normalize_answer(gold)
282
+ norm_pred = normalize_answer(pred)
283
+ # Use exact match for Needle in a Haystack
284
+ return exact_match(gold=norm_gold, pred=norm_pred)
285
+
286
+ def llm_match(self, gold: str, pred: str, judge: LLMJudge, **kwargs) -> dict:
287
+ """
288
+ Use LLM as a judge to evaluate the predicted answer against the gold answer.
289
+ """
290
+ from .utils import GENERAL_ORM_PROMPT, ORM_USER_TEMPLATE, parse_score
291
+
292
+ raw_input = kwargs.get('raw_input', None)
293
+ question = raw_input.get('question')
294
+ context_length = raw_input.get('context_length')
295
+ depth_percent = raw_input.get('depth_percent')
296
+
297
+ # get grading response
298
+ prompt = ORM_USER_TEMPLATE.format(question=question, gold=gold, pred=pred)
299
+ orm_response = judge(prompt=prompt, system_prompt=GENERAL_ORM_PROMPT)
300
+
301
+ # parse grading score with regex, [[score]]
302
+ score = parse_score(orm_response) if orm_response else 0.0
303
+ return {f'Context#{context_length} Depth#{depth_percent}': score}
304
+
305
+ def compute_metric(self, review_res_list: Union[List[dict], List[List[dict]]], **kwargs) -> List[dict]:
306
+ """
307
+ compute weighted mean of the bleu score of all samples
308
+
309
+ Args:
310
+ review_res_list: [score1, score2, ...]
311
+
312
+ Returns:
313
+ avg_res: List[dict]
314
+
315
+ """
316
+ items = super().compute_dict_metric(review_res_list, **kwargs)
317
+ return [{'metric_name': k, 'score': mean(v), 'num': len(v)} for k, v in items.items()]
318
+
319
+ def post_process_report(self, report: 'Report', **kwargs):
320
+ try:
321
+ import os
322
+
323
+ from .utils import draw_score_chat
324
+
325
+ report_path = kwargs.get('report_path')
326
+ data_frame = report.to_dataframe()
327
+ # split `Metric` to `Context` and `Depth`
328
+ data_frame[['Context', 'Depth']] = data_frame['Metric'].str.split(' ', n=1, expand=True)
329
+ data_frame['Depth'] = data_frame['Depth'].str.replace('Depth#', '').astype(float)
330
+ data_frame['Context'] = data_frame['Context'].str.replace('Context#', '').astype(int)
331
+ # split by `Subset` to multi sub data frame
332
+ for subset in data_frame['Subset'].unique():
333
+ sub_df = data_frame[data_frame['Subset'] == subset]
334
+ # draw charts for each subset
335
+ pivot_table = sub_df.pivot_table(
336
+ values='Score', index=['Depth', 'Context'], aggfunc='mean').reset_index()
337
+ pivot_table = pivot_table.pivot(index='Depth', columns='Context', values='Score')
338
+ draw_score_chat(pivot_table, outpath=os.path.join(report_path, f'needle_haystack_heatmap_{subset}.png'))
339
+
340
+ except Exception as e:
341
+ logger.error(f'Error generating charts: {e}')
@@ -0,0 +1,79 @@
1
+ import matplotlib.pyplot as plt
2
+ import os
3
+ import re
4
+ import seaborn as sns
5
+ import string
6
+ from matplotlib.colors import LinearSegmentedColormap
7
+
8
+
9
+ def normalize_answer(s):
10
+
11
+ def remove_articles(text):
12
+ return re.sub(r'\b(a|an|the)\b', ' ', text)
13
+
14
+ def white_space_fix(text):
15
+ return ' '.join(text.split())
16
+
17
+ def remove_punc(text):
18
+ exclude = set(string.punctuation)
19
+ return ''.join(ch for ch in text if ch not in exclude)
20
+
21
+ def lower(text):
22
+ return text.lower()
23
+
24
+ return white_space_fix(remove_articles(remove_punc(lower(s))))
25
+
26
+
27
+ def parse_score(score_str: str) -> int:
28
+ """
29
+ Parses a score string and returns an integer score.
30
+ The score should be in the format [[score]].
31
+ """
32
+ score_match = re.search(r'\[\[(\d+)\]\]', score_str)
33
+ if score_match:
34
+ score = int(score_match.group(1))
35
+ return score / 10.0
36
+ else:
37
+ return 0.0
38
+
39
+
40
+ def draw_score_chat(pivot_table, outpath):
41
+ # Create a custom colormap. Go to https://coolors.co/ and pick cool colors
42
+ cmap = LinearSegmentedColormap.from_list('custom_cmap', ['#F0496E', '#EBB839', '#0CD79F'])
43
+
44
+ # Create the heatmap with better aesthetics
45
+ plt.figure(figsize=(17.5, 8)) # Can adjust these dimensions as needed
46
+ sns.heatmap(pivot_table, vmin=0.0, vmax=1.0, annot=True, fmt='.1f', cmap=cmap, cbar_kws={'label': 'Score'})
47
+
48
+ # More aesthetics
49
+ plt.title('Fact Retrieval Across Context Lengths ("Needle In A HayStack")') # Adds a title
50
+ plt.xlabel('Token Limit') # X-axis label
51
+ plt.ylabel('Depth Percent') # Y-axis label
52
+ plt.xticks(rotation=45) # Rotates the x-axis labels to prevent overlap
53
+ plt.yticks(rotation=0) # Ensures the y-axis labels are horizontal
54
+ plt.tight_layout() # Fits everything neatly into the figure area
55
+
56
+ # save the figure
57
+ plt.savefig(outpath, dpi=300, bbox_inches='tight')
58
+
59
+
60
+ GENERAL_ORM_PROMPT = """You are an expert in verifying if the model answer is correct based on the reference answer.
61
+ Your input is a question, a reference answer, and a model answer. You need to check if the model answer is correct based on the reference answer.
62
+ You should focus on the correctness of the model answer compared to the reference answer, without attempting to solve the original question.
63
+ You must provide your final score in the form of a number from 1 to 10, where:
64
+
65
+ Score 1: The answer is completely unrelated to the reference.
66
+ Score 3: The answer has minor relevance but does not align with the reference.
67
+ Score 5: The answer has moderate relevance but contains inaccuracies.
68
+ Score 7: The answer aligns with the reference but has minor omissions.
69
+ Score 10: The answer is completely accurate and aligns perfectly with the reference.
70
+
71
+ Only respond with a numberical score with formatted as [[score]].""" # noqa: E501
72
+
73
+ ORM_USER_TEMPLATE = """
74
+ Question: {question}
75
+
76
+ Reference Answer: {gold}
77
+
78
+ Model Answer: {pred}
79
+ """
@@ -31,7 +31,10 @@ class ToolBenchAdapter(DataAdapter):
31
31
  Generate model prompt from input data.
32
32
  """
33
33
  messages = input_d['messages']
34
- # use prepared messages
34
+ # use prepared messages and remove the name field
35
+ for message in messages:
36
+ if 'name' in message:
37
+ del message['name']
35
38
  return self.gen_prompt_data(prompt='', messages=messages)
36
39
 
37
40
  def get_gold_answer(self, input_d: dict) -> str:
@@ -1,13 +1,14 @@
1
1
  import json
2
- from rouge import Rouge
2
+
3
+ from evalscope.metrics import compute_rouge_score_one_sample
3
4
 
4
5
 
5
6
  def evaluate_rougel(cand_list: list, ref_list: list):
6
7
  if len(ref_list) == 0:
7
8
  return 0
8
- rouge = Rouge()
9
- rouge_score = rouge.get_scores(hyps=cand_list, refs=ref_list, avg=True)
10
- rougel = rouge_score['rouge-l']['f']
9
+ rouge_score = compute_rouge_score_one_sample(cand_list, ref_list)
10
+ rougel = rouge_score.get('rouge-l-f', 0)
11
+
11
12
  return rougel
12
13
 
13
14
 
@@ -33,3 +33,28 @@ def preprocess_decorator(func):
33
33
  return func(self, result, raw_input_d, **kwargs)
34
34
 
35
35
  return wrapper
36
+
37
+
38
+ def load_file_with_extension(file_path: Union[str, List[str]]) -> List[dict]:
39
+ """
40
+ Load a file with a specific extension and return its content as a list of dictionaries.
41
+ """
42
+ import json
43
+ import os
44
+
45
+ if isinstance(file_path, str):
46
+ file_path = [file_path]
47
+
48
+ data = []
49
+ for path in file_path:
50
+ if not os.path.exists(path):
51
+ raise FileNotFoundError(f'The file {path} does not exist.')
52
+
53
+ with open(path, 'r', encoding='utf-8') as f:
54
+ if path.endswith('.json'):
55
+ data.extend(json.load(f))
56
+ elif path.endswith('.jsonl'):
57
+ data.extend([json.loads(line) for line in f])
58
+ elif path.endswith('.txt'):
59
+ data.extend([{'text': f.read()}])
60
+ return data
@@ -21,13 +21,13 @@ class StartAppCMD(CLICommand):
21
21
  def define_args(parsers: ArgumentParser):
22
22
  """ define args for create pipeline template command.
23
23
  """
24
- from evalscope.report import add_argument
24
+ from evalscope.app import add_argument
25
25
 
26
26
  parser = parsers.add_parser(StartAppCMD.name)
27
27
  add_argument(parser)
28
28
  parser.set_defaults(func=subparser_func)
29
29
 
30
30
  def execute(self):
31
- from evalscope.report.app import create_app
31
+ from evalscope.app import create_app
32
32
 
33
33
  create_app(self.args)
@@ -1,3 +1,35 @@
1
- from evalscope.collections.evaluator import EvaluatorCollection
2
- from evalscope.collections.sampler import StratifiedSampler, UniformSampler, WeightedSampler
3
- from evalscope.collections.schema import CollectionSchema, DatasetInfo
1
+ # Copyright (c) Alibaba, Inc. and its affiliates.
2
+ from typing import TYPE_CHECKING
3
+
4
+ from evalscope.utils.import_utils import _LazyModule
5
+
6
+ if TYPE_CHECKING:
7
+ from .evaluator import EvaluatorCollection
8
+ from .sampler import StratifiedSampler, UniformSampler, WeightedSampler
9
+ from .schema import CollectionSchema, DatasetInfo
10
+
11
+ else:
12
+ _import_structure = {
13
+ 'evaluator': [
14
+ 'EvaluatorCollection',
15
+ ],
16
+ 'sampler': [
17
+ 'StratifiedSampler',
18
+ 'UniformSampler',
19
+ 'WeightedSampler',
20
+ ],
21
+ 'schema': [
22
+ 'CollectionSchema',
23
+ 'DatasetInfo',
24
+ ],
25
+ }
26
+
27
+ import sys
28
+
29
+ sys.modules[__name__] = _LazyModule(
30
+ __name__,
31
+ globals()['__file__'],
32
+ _import_structure,
33
+ module_spec=__spec__,
34
+ extra_objects={},
35
+ )
@@ -70,9 +70,13 @@ class EvaluatorCollection:
70
70
  dataset_name = os.path.splitext(os.path.basename(self.data_adapter.dataset_id))[0]
71
71
  raw_dataset = self.data_adapter.load()
72
72
  # random limit the dataset
73
- if self.task_cfg.limit:
74
- raw_dataset = random.sample(raw_dataset,
75
- self.task_cfg.limit) if len(raw_dataset) > self.task_cfg.limit else raw_dataset
73
+ limit = len(raw_dataset)
74
+ if self.task_cfg.limit is not None:
75
+ if isinstance(self.task_cfg.limit, int):
76
+ limit = self.task_cfg.limit
77
+ elif isinstance(self.task_cfg.limit, float):
78
+ limit = int(len(raw_dataset) * self.task_cfg.limit)
79
+ raw_dataset = random.sample(raw_dataset, min(limit, len(raw_dataset)))
76
80
  # index dataset
77
81
  datasets = []
78
82
  for sample in raw_dataset:
@@ -179,11 +183,19 @@ class EvaluatorCollection:
179
183
  logger.info(f'{level} Report:\n{table}')
180
184
 
181
185
  report = ReportGenerator.gen_collection_report(df, self.dataset_name, self.task_cfg.model_id)
186
+ # Make report analysis
187
+ if self.task_cfg.analysis_report:
188
+ logger.info('Generating report analysis, please wait ...')
189
+ analysis = report.generate_analysis(self.task_cfg.judge_model_args)
190
+ logger.info('Report analysis:\n%s', analysis)
191
+ else:
192
+ logger.info('Skipping report analysis (`analysis_report=False`).')
193
+
182
194
  # save report to JSON file
183
195
  report_file_path = os.path.join(self.outputs.reports_dir, self.task_cfg.model_id, f'{self.dataset_name}.json')
184
- os.makedirs(os.path.dirname(report_file_path), exist_ok=True)
185
- with open(report_file_path, 'w', encoding='utf-8') as f:
186
- json.dump(report.to_dict(), f, ensure_ascii=False, indent=4)
196
+ report.to_json(report_file_path)
197
+
198
+ logger.info(f'Report saved to {report_file_path}')
187
199
  return report
188
200
 
189
201
  def _filter_answer(self, pred_file_path):
evalscope/config.py CHANGED
@@ -13,6 +13,7 @@ from evalscope.models import CustomModel, DummyCustomModel
13
13
  from evalscope.utils import gen_hash
14
14
  from evalscope.utils.io_utils import dict_to_yaml, json_to_dict, yaml_to_dict
15
15
  from evalscope.utils.logger import get_logger
16
+ from evalscope.utils.utils import parse_int_or_float
16
17
 
17
18
  logger = get_logger()
18
19
 
@@ -45,7 +46,7 @@ class TaskConfig:
45
46
  eval_backend: str = EvalBackend.NATIVE
46
47
  eval_config: Union[str, Dict, None] = None
47
48
  stage: str = EvalStage.ALL
48
- limit: Optional[int] = None
49
+ limit: Optional[Union[int, float]] = None
49
50
  eval_batch_size: Optional[int] = None
50
51
 
51
52
  # Cache and working directory arguments
@@ -67,7 +68,8 @@ class TaskConfig:
67
68
  # LLMJudge arguments
68
69
  judge_strategy: str = JudgeStrategy.AUTO
69
70
  judge_worker_num: int = 1
70
- judge_model_args: Optional[Dict] = field(default_factory=lambda: {})
71
+ judge_model_args: Optional[Dict] = field(default_factory=dict)
72
+ analysis_report: bool = False
71
73
 
72
74
  def __post_init__(self):
73
75
  if self.model is None:
@@ -86,6 +88,10 @@ class TaskConfig:
86
88
  if self.eval_batch_size is None:
87
89
  self.eval_batch_size = 8 if self.eval_type == EvalType.SERVICE else 1
88
90
 
91
+ # Post process limit
92
+ if self.limit is not None:
93
+ self.limit = parse_int_or_float(self.limit)
94
+
89
95
  # Set default generation_config and model_args
90
96
  self.__init_default_generation_config()
91
97
  self.__init_default_model_args()