Skip to content

Commit 0d42edf

Browse files
committed
move tasks to individual files
1 parent 25c1128 commit 0d42edf

16 files changed

Lines changed: 429 additions & 213 deletions

src/lighteval/metrics/metrics.py

Lines changed: 50 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -81,64 +81,64 @@
8181
from lighteval.utils.language import Language
8282

8383

84-
@scorer(metrics=[accuracy(), stderr()])
85-
def extractive_math_scorer():
86-
gold_extraction_target = (ExprExtractionConfig(), LatexExtractionConfig(boxed_match_priority=0))
87-
pred_extraction_target = (ExprExtractionConfig(), LatexExtractionConfig(boxed_match_priority=0))
88-
language = Language.ENGLISH
89-
fallback_mode = "first_match"
90-
extraction_mode = "first_match"
91-
timeout_seconds = 5
84+
# @scorer(metrics=[accuracy(), stderr()])
85+
# def extractive_math_scorer():
86+
# gold_extraction_target = (ExprExtractionConfig(), LatexExtractionConfig(boxed_match_priority=0))
87+
# pred_extraction_target = (ExprExtractionConfig(), LatexExtractionConfig(boxed_match_priority=0))
88+
# language = Language.ENGLISH
89+
# fallback_mode = "first_match"
90+
# extraction_mode = "first_match"
91+
# timeout_seconds = 5
9292

93-
gold_extraction_regexes = get_extraction_regexes(gold_extraction_target, language)
94-
pred_extraction_regexes = get_extraction_regexes(pred_extraction_target, language)
93+
# gold_extraction_regexes = get_extraction_regexes(gold_extraction_target, language)
94+
# pred_extraction_regexes = get_extraction_regexes(pred_extraction_target, language)
9595

96-
async def score(state: TaskState, target: Target):
97-
extracted_predictions = extract_target_from_pred(
98-
state.output.completion, pred_extraction_regexes, fallback_mode, extraction_mode, timeout_seconds
99-
)
100-
extracted_gold = extract_target_from_pred(
101-
target.text, gold_extraction_regexes, fallback_mode, extraction_mode, timeout_seconds
102-
)
103-
return Score(
104-
value="C" if extracted_predictions == extracted_gold else "I",
105-
explanation=state.output.completion,
106-
answer=str(extracted_predictions),
107-
)
96+
# async def score(state: TaskState, target: Target):
97+
# extracted_predictions = extract_target_from_pred(
98+
# state.output.completion, pred_extraction_regexes, fallback_mode, extraction_mode, timeout_seconds
99+
# )
100+
# extracted_gold = extract_target_from_pred(
101+
# target.text, gold_extraction_regexes, fallback_mode, extraction_mode, timeout_seconds
102+
# )
103+
# return Score(
104+
# value="C" if extracted_predictions == extracted_gold else "I",
105+
# explanation=state.output.completion,
106+
# answer=str(extracted_predictions),
107+
# )
108108

109-
return score
109+
# return score
110110

111111

112-
@scorer(metrics=[accuracy(), stderr()])
113-
def multichoice_scorer():
114-
language = Language.ENGLISH
115-
gold_extraction_target = (
116-
IndicesExtractionConfig(prefix_for_extraction="NativeLetters", try_extract_without_anchor=True),
117-
)
118-
pred_extraction_target = (
119-
IndicesExtractionConfig(prefix_for_extraction="NativeLetters", try_extract_without_anchor=True),
120-
)
121-
fallback_mode = "first_match"
122-
extraction_mode = "first_match"
123-
timeout_seconds = 5
112+
# @scorer(metrics=[accuracy(), stderr()])
113+
# def multichoice_scorer():
114+
# language = Language.ENGLISH
115+
# gold_extraction_target = (
116+
# IndicesExtractionConfig(prefix_for_extraction="NativeLetters", try_extract_without_anchor=True),
117+
# )
118+
# pred_extraction_target = (
119+
# IndicesExtractionConfig(prefix_for_extraction="NativeLetters", try_extract_without_anchor=True),
120+
# )
121+
# fallback_mode = "first_match"
122+
# extraction_mode = "first_match"
123+
# timeout_seconds = 5
124124

125-
gold_extraction_regexes = get_extraction_regexes(gold_extraction_target, language, len_choices=4)
126-
pred_extraction_regexes = get_extraction_regexes(pred_extraction_target, language, len_choices=4)
125+
# gold_extraction_regexes = get_extraction_regexes(gold_extraction_target, language, len_choices=4)
126+
# pred_extraction_regexes = get_extraction_regexes(pred_extraction_target, language, len_choices=4)
127127

128-
async def score(state: TaskState, target: Target):
129-
extracted_predictions = extract_target_from_pred(
130-
state.output.completion, pred_extraction_regexes, fallback_mode, extraction_mode, timeout_seconds
131-
)
132-
extracted_gold = extract_target_from_pred(
133-
target.text, gold_extraction_regexes, fallback_mode, extraction_mode, timeout_seconds
134-
)
135-
return Score(
136-
value="C" if extracted_predictions == extracted_gold else "I",
137-
explanation=state.output.completion,
138-
answer=str(extracted_predictions),
139-
)
128+
# async def score(state: TaskState, target: Target):
129+
# extracted_predictions = extract_target_from_pred(
130+
# state.output.completion, pred_extraction_regexes, fallback_mode, extraction_mode, timeout_seconds
131+
# )
132+
# extracted_gold = extract_target_from_pred(
133+
# target.text, gold_extraction_regexes, fallback_mode, extraction_mode, timeout_seconds
134+
# )
135+
# return Score(
136+
# value="C" if extracted_predictions == extracted_gold else "I",
137+
# explanation=state.output.completion,
138+
# answer=str(extracted_predictions),
139+
# )
140140

141-
return score
141+
# return score
142142

143143

144144
class Metrics(Enum):

src/lighteval/metrics/utils/extractive_match_utils.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
from sympy.parsing import parse_expr
3232

3333
from lighteval.metrics.utils.math_comparison import should_treat_as_complex
34+
from lighteval.tasks.requests import Doc
3435
from lighteval.tasks.templates.utils.formulation import ChoicePrefix, get_prefix
3536
from lighteval.tasks.templates.utils.translation_literals import TRANSLATION_LITERALS
3637
from lighteval.utils.imports import requires
@@ -344,14 +345,16 @@ def lazy_indices_regex(
344345

345346

346347
def get_extraction_regexes(
347-
target_types: Sequence[ExtractionTarget], language: Language, len_choices: int = 1
348+
# target_types: Sequence[ExtractionTarget], language: Language, len_choices: int = 1
349+
formatted_doc: Doc, target_types: Sequence[ExtractionTarget], language: Language
348350
) -> list[tuple[list[tuple[re.Pattern[str], int]], ExtractionTarget]]:
349351
extraction_regexes: list[tuple[list[tuple[re.Pattern[str], int]], ExtractionTarget]] = [
350352
(lazy_latex_regex(target_type, language), target_type)
351353
if isinstance(target_type, LatexExtractionConfig)
352354
else (lazy_expr_regex(target_type, language), target_type)
353355
if isinstance(target_type, ExprExtractionConfig)
354-
else (lazy_indices_regex(target_type, len_choices, language), target_type)
356+
# else (lazy_indices_regex(target_type, len_choices, language), target_type)
357+
else (lazy_indices_regex(target_type, len(formatted_doc.choices), language), target_type)
355358
for target_type in target_types
356359
]
357360

src/lighteval/tasks/__init__.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,50 @@
1919
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121
# SOFTWARE.
22+
23+
"""
24+
Automatically imports all task configs from the tasks/ directory.
25+
This module dynamically loads all Python files in tasks/ and exposes their LightevalTaskConfig objects.
26+
"""
27+
28+
import importlib
29+
import logging
30+
from pathlib import Path
31+
32+
from lighteval.tasks.lighteval_task import LightevalTaskConfig
33+
34+
35+
logger = logging.getLogger(__name__)
36+
37+
38+
# Get the tasks directory
39+
TASKS_DIR = Path(__file__).parent / "tasks"
40+
41+
42+
def _load_all_task_configs():
43+
"""Load all LightevalTaskConfig objects from all Python files in the tasks/ directory."""
44+
loaded_configs = {}
45+
46+
# Get all Python files in the tasks directory (excluding __init__.py and subdirectories)
47+
task_files = [f for f in TASKS_DIR.glob("*.py") if f.name != "__init__.py"]
48+
49+
for task_file in task_files:
50+
module_name = task_file.stem
51+
# Import the module
52+
module = importlib.import_module(f"lighteval.tasks.tasks.{module_name}")
53+
54+
# Find all LightevalTaskConfig objects in the module
55+
for attr_name in dir(module):
56+
attr = getattr(module, attr_name)
57+
if isinstance(attr, LightevalTaskConfig):
58+
loaded_configs[attr_name] = attr
59+
60+
return loaded_configs
61+
62+
63+
# Load all configs and add them to module namespace
64+
_configs = _load_all_task_configs()
65+
globals().update(_configs)
66+
67+
# Clean up
68+
del _configs

src/lighteval/tasks/default_prompts.py

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -888,16 +888,41 @@ def gpqa(line, task_name: str = None):
888888
)
889889

890890

891-
def gpqa_instruct(record):
891+
# def gpqa_instruct(record):
892+
# """Prompt template adapted from simple-evals: https://github.com/openai/simple-evals/blob/83ed7640a7d9cd26849bcb3340125002ef14abbe/common.py#L14"""
893+
# gold_index = random.randint(0, 3)
894+
# choices = [record["Incorrect Answer 1"], record["Incorrect Answer 2"], record["Incorrect Answer 3"]]
895+
# choices.insert(gold_index, record["Correct Answer"])
896+
897+
# return Sample(
898+
# input=record["Question"].strip(),
899+
# choices=choices,
900+
# target=LETTER_INDICES[gold_index],
901+
# )
902+
903+
def gpqa_instruct(line, task_name: str = None):
892904
"""Prompt template adapted from simple-evals: https://github.com/openai/simple-evals/blob/83ed7640a7d9cd26849bcb3340125002ef14abbe/common.py#L14"""
893905
gold_index = random.randint(0, 3)
894-
choices = [record["Incorrect Answer 1"], record["Incorrect Answer 2"], record["Incorrect Answer 3"]]
895-
choices.insert(gold_index, record["Correct Answer"])
906+
choices = [line["Incorrect Answer 1"], line["Incorrect Answer 2"], line["Incorrect Answer 3"]]
907+
choices.insert(gold_index, line["Correct Answer"])
908+
instruction = "Answer the following multiple choice question. The last line of your response should be of the following format: 'Answer: $LETTER' (without quotes) where LETTER is one of ABCD. Think step by step before answering."
909+
query_template = "{Instruction}\n\n{Question}\n\nA) {A}\nB) {B}\nC) {C}\nD) {D}"
910+
query = query_template.format(
911+
# Stripping to avoid accidental extra whitespaces, present in GPQA
912+
A=choices[0].strip(),
913+
B=choices[1].strip(),
914+
C=choices[2].strip(),
915+
D=choices[3].strip(),
916+
Question=line["Question"].strip(),
917+
Instruction=instruction,
918+
)
896919

897-
return Sample(
898-
input=record["Question"].strip(),
899-
choices=choices,
900-
target=LETTER_INDICES[gold_index],
920+
return Doc(
921+
task_name=task_name,
922+
query=query,
923+
choices=LETTER_INDICES[: len(choices)],
924+
gold_index=gold_index,
925+
instruction=instruction,
901926
)
902927

903928

src/lighteval/tasks/registry.py

Lines changed: 6 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,7 @@
3333
from pathlib import Path
3434
from types import ModuleType
3535

36-
import lighteval.tasks.default_tasks as default_tasks
37-
from lighteval.tasks.extended import AVAILABLE_EXTENDED_TASKS_MODULES
36+
import lighteval.tasks as default_tasks
3837
from lighteval.tasks.lighteval_task import LightevalTask, LightevalTaskConfig
3938

4039

@@ -227,51 +226,18 @@ def _load_full_registry(self) -> dict[str, LightevalTaskConfig]:
227226
228227
Example:
229228
{
230-
"lighteval|arc_easy": LightevalTaskConfig(name="arc_easy", suite="lighteval", ...),
229+
"arc_easy": LightevalTaskConfig(name="arc_easy", suite="lighteval", ...),
231230
}
232231
"""
233-
custom_tasks_registry = {}
234-
custom_tasks_module = []
235-
custom_task_configs = []
236232

237-
if self._custom_tasks is not None:
238-
custom_tasks_module.append(Registry.create_custom_tasks_module(custom_tasks=self._custom_tasks))
239-
240-
# Need to load extended tasks
241-
if self._load_extended:
242-
for extended_task_module in AVAILABLE_EXTENDED_TASKS_MODULES:
243-
custom_tasks_module.append(extended_task_module)
244-
245-
# Need to load community tasks
246-
if self._load_community:
247-
community_modules = load_community_tasks()
248-
for community_task_module in community_modules:
249-
custom_tasks_module.append(community_task_module)
233+
return Registry.create_task_config_dict()
250234

251235
# Need to load multilingual tasks
252236
if self._load_multilingual:
253-
import lighteval.tasks.multilingual.tasks as multilingual_tasks
254-
255-
custom_tasks_module.append(multilingual_tasks)
256-
257-
# We load all
258-
for module in custom_tasks_module:
259-
custom_task_configs.extend(module.TASKS_TABLE)
260-
logger.info(f"Found {len(module.TASKS_TABLE)} custom tasks in {module.__file__}")
261-
262-
if len(custom_task_configs) > 0:
263-
custom_tasks_registry = Registry.create_task_config_dict(meta_table=custom_task_configs)
264-
265-
default_tasks_registry = Registry.create_task_config_dict()
266-
267-
# Check the overlap between default_tasks_registry and custom_tasks_registry
268-
intersection = set(default_tasks_registry.keys()).intersection(set(custom_tasks_registry.keys()))
269-
if len(intersection) > 0:
270-
logger.warning(
271-
f"Following tasks ({intersection}) exists both in the default and custom tasks. Will use the custom ones on conflict."
272-
)
237+
pass
238+
tasks_registry = {}
273239

274-
return {**default_tasks_registry, **custom_tasks_registry}
240+
return tasks_registry
275241

276242
def _update_task_configs(self) -> dict[str, LightevalTaskConfig]: # noqa: C901
277243
"""

0 commit comments

Comments
 (0)