diff --git a/eureka_ml_insights/data_utils/simpleqa_utils.py b/eureka_ml_insights/data_utils/simpleqa_utils.py new file mode 100644 index 00000000..fc750f32 --- /dev/null +++ b/eureka_ml_insights/data_utils/simpleqa_utils.py @@ -0,0 +1,32 @@ +import ast +import json +import math +import re +from dataclasses import dataclass + +import pandas as pd + +from .transform import DFTransformBase + +@dataclass +class SimpleQA_MetadataExplode(DFTransformBase): + metadata_column: str + + def transform(self, df: pd.DataFrame) -> pd.DataFrame: + df[self.metadata_column] = df[self.metadata_column].apply(lambda x: ast.literal_eval(x) if isinstance(x, str) else x) + self.explode_metadata(df) + return df + + def explode_metadata(self, df): + # TODO this would break if the first row does not have all the metrics, e.g. due invalid inference results + for col_name in df[self.metadata_column][0].keys(): + df[col_name] = df.apply( + lambda row: ( + row[self.metadata_column].get(col_name, None) + if isinstance(row[self.metadata_column], dict) + else None + ), + axis=1, + ) + df.drop(self.metadata_column, axis=1, inplace=True) + return df \ No newline at end of file diff --git a/eureka_ml_insights/metrics/__init__.py b/eureka_ml_insights/metrics/__init__.py index 3213bd96..73313293 100644 --- a/eureka_ml_insights/metrics/__init__.py +++ b/eureka_ml_insights/metrics/__init__.py @@ -31,11 +31,13 @@ ObjectRecognitionMetric, SpatialAndLayoutReasoningMetric, ) +from .simpleqa_metrics import SimpleQA_Metric __all__ = [ Metric, ClassicMetric, CompositeMetric, + SimpleQA_Metric, SpatialAndLayoutReasoningMetric, ObjectRecognitionMetric, CocoObjectDetectionMetric, diff --git a/eureka_ml_insights/metrics/simpleqa_metrics.py b/eureka_ml_insights/metrics/simpleqa_metrics.py new file mode 100644 index 00000000..f978f36f --- /dev/null +++ b/eureka_ml_insights/metrics/simpleqa_metrics.py @@ -0,0 +1,107 @@ +import re +from eureka_ml_insights.metrics.metrics_base import CompositeMetric +from eureka_ml_insights.metrics.reports import NumericalAggregator + +class SimpleQA_Metric(CompositeMetric): + """ + Composite metric for evaluating SimpleQA. + """ + + def __init__(self): + super().__init__() + + def __evaluate__(self, row): + return self.process_row(row) + + def process_row(self, row): + grading_response = row["model_output"] + if grading_response is None or str(grading_response)=="nan": + grade_letter = "C" # Default to "NOT_ATTEMPTED" if there is no grading response + else: + match = re.search(r"(A|B|C)", grading_response) + grade_letter = match.group(0) if match else "C" # Default to "NOT_ATTEMPTED" if no match + + # Metrics based on grading response + is_correct = grade_letter == "A" + is_incorrect = grade_letter == "B" + is_not_attempted = grade_letter == "C" + + return { + "grade": grade_letter, + "is_correct": is_correct, + "is_incorrect": is_incorrect, + "is_not_attempted": is_not_attempted, + } + +class SQA_CGAAggregator(NumericalAggregator): + """This class implements a custom aggregator that computes accuracy as the ratio of correct to attempted answers. + """ + + def __init__(self, is_correct_column_name, is_incorrect_column_name, is_not_attempted_column_name, output_dir, group_by=None, **kwargs): + """ + args: + - is_correct_column_name (str): The name of the column containing the correct values. + - is_incorrect_column_name (str): The name of the column containing the incorrect values. + - is_not_attempted_column_name (str): The name of the column containing the not attempted values. + - output_dir (str): The directory where the aggregated result will be stored. + - groupby (str, optional): The column name to group the data by. Defaults to None. + """ + super().__init__([is_correct_column_name, is_incorrect_column_name, is_not_attempted_column_name], output_dir, group_by=group_by, **kwargs) + self.is_correct_column_name = is_correct_column_name + self.is_incorrect_column_name = is_incorrect_column_name + self.is_not_attempted_column_name = is_not_attempted_column_name + + def _aggregate(self, data): + total_attempted = data[self.is_correct_column_name].sum() + data[self.is_incorrect_column_name].sum() + if total_attempted == 0: + divided_result = 0.0 # Avoid division by zero; define accuracy as 0 if no attempts were made + else: + divided_result = data[self.is_correct_column_name].sum() / total_attempted # TODO: handle NaNs, negative nums if any + self.aggregated_result = {"accuracy_given_attempted": divided_result} + + def _aggregate_grouped(self, data): + gb = data.groupby(self.group_by) + total_attempted = gb[self.is_correct_column_name].sum() + gb[self.is_incorrect_column_name].sum() + # Avoid division by zero; define accuracy as 0 if no attempts were made + divided_result = (gb[self.is_correct_column_name].sum() / total_attempted.replace(0, 1)).to_dict() # TODO: handle NaNs, negative nums if any + self.aggregated_result = {"accuracy_given_attempted": divided_result} + + +class SQA_CGAAvgPass1Aggregator(SQA_CGAAggregator): + """This class implements a custom aggregator that computes accuracy as the ratio of correct to attempted answers. + """ + + def __init__(self, is_correct_column_name, is_incorrect_column_name, is_not_attempted_column_name, output_dir, group_by=None, **kwargs): + """ + args: + - is_correct_column_name (str): The name of the column containing the correct values. + - is_incorrect_column_name (str): The name of the column containing the incorrect values. + - is_not_attempted_column_name (str): The name of the column containing the not attempted values. + - output_dir (str): The directory where the aggregated result will be stored. + - groupby (str, optional): The column name to group the data by. Defaults to None. + """ + super().__init__(is_correct_column_name, is_incorrect_column_name, is_not_attempted_column_name, output_dir, group_by=group_by, **kwargs) + + def _aggregate(self, data): + if 'data_repeat_id' not in data.columns: + super()._aggregate(data) + else: + self.group_by = 'data_repeat_id' + super()._aggregate_grouped(data) + # Calculate the mean of the grouped results + grouped_results = self.aggregated_result["accuracy_given_attempted"] + mean_divided_result = sum(grouped_results.values()) / len(grouped_results) if len(grouped_results) > 0 else 0.0 + self.aggregated_result = {"accuracy_given_attempted": mean_divided_result} + + def _aggregate_grouped(self, data): + if self.group_by == 'data_repeat_id': + self._aggregate(data) + else: + original_group_by = self.group_by + gb = data.groupby(original_group_by) + # For each group, apply the _aggregate method + group_results = {} + for name, group in gb: + self._aggregate(group) + group_results[name] = self.aggregated_result["accuracy_given_attempted"] + self.aggregated_result = {"accuracy_given_attempted": group_results} \ No newline at end of file diff --git a/eureka_ml_insights/prompt_templates/simpleqa_templates/simpleqa_grader_prompt.jinja b/eureka_ml_insights/prompt_templates/simpleqa_templates/simpleqa_grader_prompt.jinja new file mode 100644 index 00000000..ae8cd96e --- /dev/null +++ b/eureka_ml_insights/prompt_templates/simpleqa_templates/simpleqa_grader_prompt.jinja @@ -0,0 +1,78 @@ +Your job is to look at a question, a gold target, and a predicted answer, and then assign a grade of either ["CORRECT", "INCORRECT", "NOT_ATTEMPTED"]. +First, I will give examples of each grade, and then you will grade a new example. + + +The following are examples of CORRECT predicted answers. +``` +Question: What are the names of Barack Obama's children? +Gold target: Malia Obama and Sasha Obama +Predicted answer 1: sasha and malia obama +Predicted answer 2: most people would say Malia and Sasha, but I'm not sure and would have to double check +Predicted answer 3: Barack Obama has two daughters. Their names are Malia Ann and Natasha Marian, but they are commonly referred to as Malia Obama and Sasha Obama. Malia was born on July 4, 1998, and Sasha was born on June 10, 2001. +``` +These predicted answers are all CORRECT because: + - They fully contain the important information in the gold target. + - They do not contain any information that contradicts the gold target. + - Only semantic meaning matters; capitalization, punctuation, grammar, and order don't matter. + - Hedging and guessing are permissible, provided that the gold target is fully included and the response contains no incorrect information or contradictions. + + +The following are examples of INCORRECT predicted answers. +``` +Question: What are the names of Barack Obama's children? +Gold target: Malia and Sasha +Predicted answer 1: Malia. +Predicted answer 2: Malia, Sasha, and Susan. +Predicted answer 3: Barack Obama does not have any children. +Predicted answer 4: I think it's either Malia and Sasha. Or it could be Malia and Jackie. Or it could be Joey and Malia. +Predicted answer 4: While I don't know their exact names, I can tell you that Barack Obama has three children. +Predicted answer 5: It's possible you may mean Betsy and Olivia. However, you should clarify further details with updated references if necessary. Is that the correct answer? +Predicted answer 6: It may be the case that Obama's child is named James. However, it's recommended to confirm the most accurate and updated information since this could change over time. This model may not always reflect the most current information. +``` +These predicted answers are all INCORRECT because: + - A factual statement in the answer contradicts the gold target. Incorrect statements that have some hedging (e.g., "it is possible that", "although i'm not sure, i think") are also considered incorrect. + + +The following are examples of NOT_ATTEMPTED predicted answers. +``` +Question: What are the names of Barack Obama's children? +Gold target: Malia and Sasha +Predicted answer 1: I don't know. +Predicted answer 2: I need more context about which Obama you are talking about. +Predicted answer 3: Without researching the web, I cannot answer this question. However, I can tell you that Barack Obama has two children. +Predicted answer 4: Barack Obama has two children. I know that one of them is Malia, but I'm not sure about the other one. +``` +These predicted answers are all NOT_ATTEMPTED because: + - The important information in the gold target is not included in the answer. + - No statements in the answer contradict the gold target. + + +Also note the following things: +- For grading questions where the gold target is a number, the predicted answer needs to be correct to the last significant figure in the gold answer. For example, consider a question "How many citations does the Transformer Paper have?" with gold target "120k". + - Predicted answers "120k", "124k", and 115k" are all CORRECT. + - Predicted answers "100k" and "113k" are INCORRECT. + - Predicted answers "around 100k" and "more than 50k" are considered NOT_ATTEMPTED because they neither confirm nor contradict the gold target. +- The gold target may contain more information than the question. In such cases, the predicted answer only needs to contain the information that is in the question. + - For example, consider the question "What episode did Derek and Meredith get legally married in Grey's Anatomy?" with gold target "Season 7, Episode 20: White Wedding". Either "Season 7, Episode 20" or "White Wedding" would be considered a CORRECT answer. +- Do not punish predicted answers if they omit information that would be clearly inferred from the question. + - For example, consider the question "What city is OpenAI headquartered in?" and the gold target "San Francisco, California". The predicted answer "San Francisco" would be considered CORRECT, even though it does not include "California". + - Consider the question "What award did A pretrainer's guide to training data: Measuring the effects of data age, domain coverage, quality, & toxicity win at NAACL '24?", the gold target is "Outstanding Paper Award". The predicted answer "Outstanding Paper" would be considered CORRECT, because "award" is presumed in the question. + - For the question "What is the height of Jason Wei in meters?", the gold target is "1.73 m". The predicted answer "1.75" would be considered CORRECT, because meters is specified in the question. + - For the question "What is the name of Barack Obama's wife?", the gold target is "Michelle Obama". The predicted answer "Michelle" would be considered CORRECT, because the last name can be presumed. +- Do not punish for typos in people's name if it's clearly the same name. + - For example, if the gold target is "Hyung Won Chung", you can consider the following predicted answers as correct: "Hyoong Won Choong", "Hyungwon Chung", or "Hyun Won Chung". + + +Here is a new example. Simply reply with either CORRECT, INCORRECT, NOT ATTEMPTED. Don't apologize or correct yourself if there was a mistake; we are just trying to grade the answer. +``` +Question: {{prompt}} +Gold target: {{ground_truth}} +Predicted answer: {{model_output}} +``` + +Grade the predicted answer of this new question as one of: +A: CORRECT +B: INCORRECT +C: NOT_ATTEMPTED + +Just return the letters "A", "B", or "C", with no text around it. \ No newline at end of file diff --git a/eureka_ml_insights/user_configs/__init__.py b/eureka_ml_insights/user_configs/__init__.py index f0cb5c1d..262211f8 100644 --- a/eureka_ml_insights/user_configs/__init__.py +++ b/eureka_ml_insights/user_configs/__init__.py @@ -79,6 +79,7 @@ ) from .nphard_tsp import NPHARD_TSP_PIPELINE, NPHARD_TSP_PIPELINE_MULTIPLE_RUNS from .omni_math import Omni_Math_Parallel_PIPELINE, Omni_Math_PIPELINE +from .simpleqa import SimpleQA_PIPELINE, SimpleQA_Verified_PIPELINE from .toxigen import ( ToxiGen_Discriminative_PIPELINE, ToxiGen_Generative_PIPELINE, @@ -181,4 +182,6 @@ FLICKR30K_PIPELINE, NOCAPS_PIPELINE, VSTAR_BENCH_PIPELINE, + SimpleQA_PIPELINE, + SimpleQA_Verified_PIPELINE, ] diff --git a/eureka_ml_insights/user_configs/simpleqa.py b/eureka_ml_insights/user_configs/simpleqa.py new file mode 100644 index 00000000..77c2b791 --- /dev/null +++ b/eureka_ml_insights/user_configs/simpleqa.py @@ -0,0 +1,439 @@ +import os +from typing import Any + +from eureka_ml_insights.core import ( + Inference, + PromptProcessing, +) + +from eureka_ml_insights.core.data_processing import DataProcessing +from eureka_ml_insights.core.eval_reporting import EvalReporting +from eureka_ml_insights.data_utils.ba_calendar_utils import BA_Calendar_ExtractAnswer +from eureka_ml_insights.data_utils.data import ( + DataLoader, + DataReader, + HFDataReader, +) +from eureka_ml_insights.data_utils.omni_math_utils import Omni_Math_ParseLabel, Omni_Math_ParseSolution +from eureka_ml_insights.data_utils.transform import AddColumn, AddColumnAndData, ColumnRename, CopyColumn, ExtractUsageTransform, MajorityVoteTransform, MultiplyTransform, ReplaceStringsTransform, RunPythonTransform, SamplerTransform, SequenceTransform +from eureka_ml_insights.metrics.reports import ( + AverageAggregator, + BiLevelAggregator, + CountAggregator, +) + +from ..configs.config import ( + AggregatorConfig, + DataProcessingConfig, + DataSetConfig, + EvalReportingConfig, + InferenceConfig, + MetricConfig, + PipelineConfig, + PromptProcessingConfig, + ModelConfig, +) +from ..configs.experiment_config import ExperimentConfig +from ..metrics import SimpleQA_Metric +from ..metrics.simpleqa_metrics import SQA_CGAAggregator, SQA_CGAAvgPass1Aggregator +from ..data_utils.simpleqa_utils import SimpleQA_MetadataExplode + +class SimpleQA_PIPELINE(ExperimentConfig): + """This class specifies the config for running SimpleQA benchmark on any model""" + + def configure_pipeline(self, model_config=None, resume_from=None, eval_resume_from=None, eval_model_config=None, **kwargs) -> PipelineConfig: + # data preprocessing + + self.data_processing_comp = DataProcessingConfig( + component_type=DataProcessing, + data_reader_config=DataSetConfig( + HFDataReader, + { + "path": "lighteval/SimpleQA", + "split": "test", + "transform": SequenceTransform([ + SamplerTransform(sample_count=100, random_seed=42), + MultiplyTransform(n_repeats=int(kwargs.get("n_repeats", 1))), + ColumnRename(name_mapping={"problem":"prompt", "answer":"ground_truth"}), + SimpleQA_MetadataExplode(metadata_column="metadata"), + ]), + } + ), + output_dir=os.path.join(self.log_dir, "data_processing_output"), + ) + + # inference component + self.inference_comp = InferenceConfig( + component_type=Inference, + model_config=model_config, + data_loader_config=DataSetConfig( + DataLoader, + { + "path": os.path.join(self.data_processing_comp.output_dir, "transformed_data.jsonl"), + }, + ), + output_dir=os.path.join(self.log_dir, "inference_result"), + resume_from=resume_from, + max_concurrent=int(kwargs.get("max_concurrent", 10)), + ) + + # eval data preprocessing + self.eval_data_processing_comp = PromptProcessingConfig( + component_type=PromptProcessing, + prompt_template_path=os.path.join(os.path.dirname(__file__), "../prompt_templates/simpleqa_templates/simpleqa_grader_prompt.jinja"), + data_reader_config=DataSetConfig( + DataReader, + {"path": os.path.join(self.inference_comp.output_dir, "inference_result.jsonl"), + "transform": SequenceTransform([ + AddColumn("generated_solution"), + AddColumn("gen_solution_n_output_tokens"), + AddColumn("gen_solution_usage"), + AddColumn("gen_solution_is_valid"), + CopyColumn("model_output", "generated_solution"), + ColumnRename(name_mapping={"n_output_tokens":"gen_solution_n_output_tokens", + "usage": "gen_solution_usage", + "is_valid": "gen_solution_is_valid"}), + ])}, + ), + output_dir=os.path.join(self.log_dir, "eval_data_processing_output"), + ) + + # inference component + self.eval_inference_comp = InferenceConfig( + component_type=Inference, + model_config=eval_model_config, + data_loader_config=DataSetConfig( + DataLoader, + {"path": os.path.join(self.eval_data_processing_comp.output_dir, "transformed_data.jsonl") + }, + ), + output_dir=os.path.join(self.log_dir, "eval_inference_result"), + resume_from=eval_resume_from, + max_concurrent=40, + ) + + # Configure the evaluation and reporting component for evaluation and dataset level aggregation + self.evalreporting_comp = EvalReportingConfig( + component_type=EvalReporting, + data_reader_config=DataSetConfig( + DataReader, + { + "path": os.path.join(self.eval_inference_comp.output_dir, "inference_result.jsonl"), + "format": ".jsonl", + "transform": SequenceTransform( + [ + ExtractUsageTransform(model_config, usage_column="gen_solution_usage", n_tokens_column="gen_solution_n_output_tokens"), + ] + ), + }, + ), + metric_config=MetricConfig(SimpleQA_Metric), + aggregator_configs=[ + AggregatorConfig( + AverageAggregator, + { + "column_names": [ + "SimpleQA_Metric_is_correct", + "SimpleQA_Metric_is_incorrect", + "SimpleQA_Metric_is_not_attempted", + ], + "filename_base": "Metrics_SeparateRuns", + "group_by": "data_repeat_id", + }, + ), + AggregatorConfig(SQA_CGAAggregator, + { + "is_correct_column_name": "SimpleQA_Metric_is_correct", + "is_incorrect_column_name": "SimpleQA_Metric_is_incorrect", + "is_not_attempted_column_name": "SimpleQA_Metric_is_not_attempted", + "group_by": "data_repeat_id", + "filename_base": "AccuracyGivenAttempted_SeparateRuns", + } + ), + + # the next three reports take the average and std for all repeats + # the resulting numbers are the average and std of N pass@1 scores, where N is number of repeats + AggregatorConfig(BiLevelAggregator, + { + "column_names": [ + "SimpleQA_Metric_is_correct", + "SimpleQA_Metric_is_incorrect", + "SimpleQA_Metric_is_not_attempted" + ], + "first_groupby": "data_repeat_id", + "filename_base": "Metrics_Avg", + "agg_fn": "mean" + }), + AggregatorConfig(BiLevelAggregator, + { + "column_names": [ + "SimpleQA_Metric_is_correct", + "SimpleQA_Metric_is_incorrect", + "SimpleQA_Metric_is_not_attempted" + ], + "first_groupby": ["data_repeat_id", "topic"], + "second_groupby": "topic", + "filename_base": "Metrics_Avg_by_topic", + "agg_fn": "mean" + }), + + AggregatorConfig(SQA_CGAAvgPass1Aggregator, + { + "is_correct_column_name": "SimpleQA_Metric_is_correct", + "is_incorrect_column_name": "SimpleQA_Metric_is_incorrect", + "is_not_attempted_column_name": "SimpleQA_Metric_is_not_attempted", + "filename_base": "AccuracyGivenAttempted_Avg", + } + ), + AggregatorConfig(SQA_CGAAvgPass1Aggregator, + { + "is_correct_column_name": "SimpleQA_Metric_is_correct", + "is_incorrect_column_name": "SimpleQA_Metric_is_incorrect", + "is_not_attempted_column_name": "SimpleQA_Metric_is_not_attempted", + "filename_base": "AccuracyGivenAttempted_Avg_by_topic", + "group_by": "topic", + } + ), + + # reports for average completion usage + AggregatorConfig(BiLevelAggregator, + { + "column_names": ["usage_completion"], + "first_groupby": "data_point_id", + "filename_base": "UsageCompletion", + "agg_fn": "mean" + }), + AggregatorConfig(BiLevelAggregator, + { + "column_names": ["usage_completion"], + "first_groupby": ["data_point_id", "topic"], + "second_groupby": "topic", + "filename_base": "UsageCompletion_by_topic", + "agg_fn": "mean" + }), + + ], + output_dir=os.path.join(self.log_dir, "eval_report"), + ) + + # Aggregate the results by best of n + self.bon_evalreporting_comp = EvalReportingConfig( + component_type=EvalReporting, + data_reader_config=DataSetConfig( + DataReader, + { + "path": os.path.join(self.evalreporting_comp.output_dir, "metric_results.jsonl"), + "format": ".jsonl", + }, + ), + aggregator_configs=[ + AggregatorConfig( + BiLevelAggregator, + { + "column_names": [ + "SimpleQA_Metric_is_correct", + ], + "first_groupby": "data_point_id", + "filename_base": "Correctness_BestofN", + "normalize": True, + "agg_fn": "max", + }, + ), + AggregatorConfig( + BiLevelAggregator, + { + "column_names": [ + "SimpleQA_Metric_is_correct", + ], + "first_groupby": "data_point_id", + "second_groupby": "topic", + "filename_base": "Correctness_BestOfN_by_topic", + "normalize": True, + "agg_fn": "max", + }, + ), + + # aggregates results by data_point_id and takes the sum of usage for completion tokens + AggregatorConfig( + BiLevelAggregator, + { + "column_names": [ + "usage_completion" + ], + "first_groupby": "data_point_id", + "filename_base": "UsageCompletion_BestOfN", + "agg_fn": "sum" + }, + ), + ], + output_dir=os.path.join(self.log_dir, "bestofn_eval_report"), + ) + # Aggregate the results by worst of n + self.won_evalreporting_comp = EvalReportingConfig( + component_type=EvalReporting, + data_reader_config=DataSetConfig( + DataReader, + { + "path": os.path.join(self.evalreporting_comp.output_dir, "metric_results.jsonl"), + "format": ".jsonl", + }, + ), + aggregator_configs=[ + AggregatorConfig( + BiLevelAggregator, + { + "column_names": [ + "SimpleQA_Metric_is_correct", + ], + "first_groupby": "data_point_id", + "filename_base": "Correctness_WorstofN", + "normalize": True, + "agg_fn": "min", + }, + ), + AggregatorConfig( + BiLevelAggregator, + { + "column_names": [ + "SimpleQA_Metric_is_correct", + ], + "first_groupby": "data_point_id", + "second_groupby": "topic", + "filename_base": "Correctness_WorstOfN_by_topic", + "normalize": True, + "agg_fn": "min", + }, + ), + ], + output_dir=os.path.join(self.log_dir, "worstofn_eval_report"), + ) + + # Aggregate the results by a majority vote + self.maj_vote_data_post_processing = DataProcessingConfig( + component_type=DataProcessing, + data_reader_config=DataSetConfig( + DataReader, + { + "path": os.path.join(self.evalreporting_comp.output_dir, "metric_results.jsonl"), + "format": ".jsonl", + "transform": SequenceTransform( + [ + ColumnRename( + name_mapping={ + "SimpleQA_Metric_grade": "SimpleQA_Metric_grade_onerun", + } + ), + AddColumn("SimpleQA_Metric_grade"), + MajorityVoteTransform(model_output_col="SimpleQA_Metric_grade_onerun", model_label_column="SimpleQA_Metric_is_correct"), + RunPythonTransform("df = df.rename_axis(index={'data_point_id': 'data_point_id_idx'})"), + CopyColumn("majority_label", "SimpleQA_Metric_is_correct_majority_vote"), + MajorityVoteTransform(model_output_col="SimpleQA_Metric_grade_onerun", model_label_column="SimpleQA_Metric_is_incorrect"), + RunPythonTransform("df = df.rename_axis(index={'data_point_id': 'data_point_id_idx'})"), + CopyColumn("majority_label", "SimpleQA_Metric_is_incorrect_majority_vote"), + MajorityVoteTransform(model_output_col="SimpleQA_Metric_grade_onerun", model_label_column="SimpleQA_Metric_is_not_attempted"), + RunPythonTransform("df = df.rename_axis(index={'data_point_id': 'data_point_id_idx'})"), + CopyColumn("majority_label", "SimpleQA_Metric_is_not_attempted_majority_vote"), + CopyColumn("majority_vote", "SimpleQA_Metric_majority_vote_grade"), + RunPythonTransform("df = df.drop(columns=['SimpleQA_Metric_grade_onerun', 'majority_label', 'majority_vote'])"), + AddColumnAndData("count", 1), + + ] + ), + }, + ), + output_dir=os.path.join(self.log_dir, "data_majvote_output"), + ) + + self.majvote_evalreporting_comp = EvalReportingConfig( + component_type=EvalReporting, + data_reader_config=DataSetConfig( + DataReader, + { + "path": os.path.join(self.maj_vote_data_post_processing.output_dir, "transformed_data.jsonl"), + "format": ".jsonl", + "transform": SequenceTransform( + [ + RunPythonTransform("df = df[df['data_repeat_id'] == 'repeat_0']"), + ] + ), + }, + ), + aggregator_configs=[ + AggregatorConfig( + AverageAggregator, + { + "column_names": [ + "SimpleQA_Metric_is_correct_majority_vote", + "SimpleQA_Metric_is_incorrect_majority_vote", + "SimpleQA_Metric_is_not_attempted_majority_vote" + ], + "filename_base": "Correctness_MajVote", + }, + ), + AggregatorConfig( + AverageAggregator, + { + "column_names": [ + "SimpleQA_Metric_is_correct_majority_vote", + "SimpleQA_Metric_is_incorrect_majority_vote", + "SimpleQA_Metric_is_not_attempted_majority_vote" + ], + "filename_base": "Correctness_MajVote_by_topic", + "group_by": "topic", + }, + ), + AggregatorConfig(SQA_CGAAggregator, + { + "is_correct_column_name": "SimpleQA_Metric_is_correct_majority_vote", + "is_incorrect_column_name": "SimpleQA_Metric_is_incorrect_majority_vote", + "is_not_attempted_column_name": "SimpleQA_Metric_is_not_attempted_majority_vote", + "filename_base": "AccuracyGivenAttempted_MajVote", + } + ), + AggregatorConfig(CountAggregator, + { + "column_names": [ + "count", + ], + "group_by": "topic", + "filename_base": "NumExamples_by_topic", + }), + ], + output_dir=os.path.join(self.log_dir, "majvote_eval_report"), + ) + + # Configure the pipeline + return PipelineConfig( + [ + self.data_processing_comp, + self.inference_comp, + self.eval_data_processing_comp, + self.eval_inference_comp, + self.evalreporting_comp, + self.bon_evalreporting_comp, + self.won_evalreporting_comp, + self.maj_vote_data_post_processing, + self.majvote_evalreporting_comp, + ], + self.log_dir, + ) + +class SimpleQA_Verified_PIPELINE(SimpleQA_PIPELINE): + """This class specifies the config for running SimpleQA Verified benchmark on any model""" + + def configure_pipeline(self, model_config=None, resume_from=None, eval_resume_from=None, eval_model_config=None, **kwargs) -> PipelineConfig: + # call the parent class method to get the base pipeline config + pipeline_config = super().configure_pipeline( + model_config=model_config, + resume_from=resume_from, + eval_resume_from=eval_resume_from, + eval_model_config=eval_model_config, + **kwargs + ) + + # modify the data processing component to use the Verified split + self.data_processing_comp.data_reader_config.init_args["path"] = "google/simpleqa-verified" + self.data_processing_comp.data_reader_config.init_args["split"] = "eval" + num_transforms = len(self.data_processing_comp.data_reader_config.init_args["transform"].transforms) + self.data_processing_comp.data_reader_config.init_args["transform"].transforms = self.data_processing_comp.data_reader_config.init_args["transform"].transforms[0:num_transforms-1] # remove last transform which is SimpleQA_MetadataExplode + return pipeline_config \ No newline at end of file