{"repo_name": "open-r1", "file_name": "/open-r1/src/open_r1/utils/data.py", "inference_info": {"prefix_code": "import logging\n\nimport datasets\nfrom datasets import DatasetDict, concatenate_datasets\n\nfrom ..configs import ScriptArguments\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_dataset(args: ScriptArguments) -> DatasetDict:\n \"\"\"Load a dataset or a mixture of datasets based on the configuration.\n\n Args:\n args (ScriptArguments): Script arguments containing dataset configuration.\n\n Returns:\n DatasetDict: The loaded datasets.\n \"\"\"\n ", "suffix_code": "\n", "middle_code": "if args.dataset_name and not args.dataset_mixture:\n logger.info(f\"Loading dataset: {args.dataset_name}\")\n return datasets.load_dataset(args.dataset_name, args.dataset_config)\n elif args.dataset_mixture:\n logger.info(f\"Creating dataset mixture with {len(args.dataset_mixture.datasets)} datasets\")\n seed = args.dataset_mixture.seed\n datasets_list = []\n for dataset_config in args.dataset_mixture.datasets:\n logger.info(f\"Loading dataset for mixture: {dataset_config.id} (config: {dataset_config.config})\")\n ds = datasets.load_dataset(\n dataset_config.id,\n dataset_config.config,\n split=dataset_config.split,\n )\n if dataset_config.columns is not None:\n ds = ds.select_columns(dataset_config.columns)\n if dataset_config.weight is not None:\n ds = ds.shuffle(seed=seed).select(range(int(len(ds) * dataset_config.weight)))\n logger.info(\n f\"Subsampled dataset '{dataset_config.id}' (config: {dataset_config.config}) with weight={dataset_config.weight} to {len(ds)} examples\"\n )\n datasets_list.append(ds)\n if datasets_list:\n combined_dataset = concatenate_datasets(datasets_list)\n combined_dataset = combined_dataset.shuffle(seed=seed)\n logger.info(f\"Created dataset mixture with {len(combined_dataset)} examples\")\n if args.dataset_mixture.test_split_size is not None:\n combined_dataset = combined_dataset.train_test_split(\n test_size=args.dataset_mixture.test_split_size, seed=seed\n )\n logger.info(\n f\"Split dataset into train and test sets with test size: {args.dataset_mixture.test_split_size}\"\n )\n return combined_dataset\n else:\n return DatasetDict({\"train\": combined_dataset})\n else:\n raise ValueError(\"No datasets were loaded from the mixture configuration\")\n else:\n raise ValueError(\"Either `dataset_name` or `dataset_mixture` must be provided\")", "code_description": null, "fill_type": "BLOCK_TYPE", "language_type": "python", "sub_task_type": "if_statement"}, "context_code": [["/open-r1/src/open_r1/configs.py", "# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom dataclasses import dataclass, field\nfrom typing import Any, Literal, Optional\n\nimport trl\n\n\n@dataclass\nclass DatasetConfig:\n \"\"\"Configuration for a dataset in a mixture.\"\"\"\n\n id: str\n config: Optional[str] = None\n split: str = \"train\"\n columns: Optional[list[str]] = None\n weight: Optional[float] = None\n\n\n@dataclass\nclass DatasetMixtureConfig:\n \"\"\"Configuration for a mixture of datasets.\"\"\"\n\n datasets: list[DatasetConfig]\n seed: int = 0\n test_split_size: Optional[float] = None\n\n\n@dataclass\nclass ScriptArguments(trl.ScriptArguments):\n \"\"\"\n Extended version of ScriptArguments with support for dataset mixtures.\n\n Args:\n dataset_mixture (`dict[str, Any]` or `None`, *optional*, defaults to `None`):\n Configuration for creating dataset mixtures with advanced options.\n Format:\n dataset_mixture:\n datasets:\n - id: dataset_id1\n config: config_name\n columns:\n - col1\n - col2\n weight: 0.5\n - id: dataset_id2\n config: config_name\n columns:\n - col1\n - col2\n weight: 0.5\n seed: 42\n test_split_size: 0.1\n \"\"\"\n\n # Override the dataset_name to make it optional\n dataset_name: Optional[str] = field(\n default=None, metadata={\"help\": \"Dataset name. Can be omitted if using dataset_mixture.\"}\n )\n dataset_mixture: Optional[dict[str, Any]] = field(\n default=None,\n metadata={\"help\": \"Configuration for creating dataset mixtures with advanced options like shuffling.\"},\n )\n\n def __post_init__(self):\n if self.dataset_name is None and self.dataset_mixture is None:\n raise ValueError(\"Either `dataset_name` or `dataset_mixture` must be provided\")\n\n if self.dataset_mixture is not None:\n if not isinstance(self.dataset_mixture, dict) or \"datasets\" not in self.dataset_mixture:\n raise ValueError(\n \"dataset_mixture must be a dictionary with a 'datasets' key. \"\n \"Expected format: {'datasets': [...], 'seed': int}\"\n )\n\n datasets_list = []\n datasets_data = self.dataset_mixture.get(\"datasets\", [])\n\n if isinstance(datasets_data, list):\n for dataset_config in datasets_data:\n datasets_list.append(\n DatasetConfig(\n id=dataset_config.get(\"id\"),\n config=dataset_config.get(\"config\"),\n split=dataset_config.get(\"split\", \"train\"),\n columns=dataset_config.get(\"columns\"),\n weight=dataset_config.get(\"weight\", 1.0),\n )\n )\n else:\n raise ValueError(\"'datasets' must be a list of dataset configurations\")\n\n self.dataset_mixture = DatasetMixtureConfig(\n datasets=datasets_list,\n seed=self.dataset_mixture.get(\"seed\", 0),\n test_split_size=self.dataset_mixture.get(\"test_split_size\", None),\n )\n\n # Check that column names are consistent across all dataset configs\n columns_sets = [set(dataset.columns) for dataset in datasets_list if dataset.columns is not None]\n if columns_sets:\n first_columns = columns_sets[0]\n if not all(columns == first_columns for columns in columns_sets):\n raise ValueError(\n \"Column names must be consistent across all dataset configurations in a mixture. \"\n f\"Found different column sets: {[list(cols) for cols in columns_sets]}\"\n )\n\n\n# TODO: add the shared options with a mixin to reduce code duplication\n@dataclass\nclass GRPOConfig(trl.GRPOConfig):\n \"\"\"\n args for callbacks, benchmarks etc\n \"\"\"\n\n benchmarks: list[str] = field(\n default_factory=lambda: [],\n metadata={\"help\": \"The benchmarks to run after training.\"},\n )\n callbacks: list[str] = field(\n default_factory=lambda: [],\n metadata={\"help\": \"The callbacks to run during training.\"},\n )\n chat_template: Optional[str] = field(default=None, metadata={\"help\": \"The chat template to use.\"})\n hub_model_revision: Optional[str] = field(\n default=\"main\", metadata={\"help\": \"The Hub model branch to push the model to.\"}\n )\n num_completions_to_print: int = field(default=0, metadata={\"help\": \"Number of completions to print.\"})\n overwrite_hub_revision: bool = field(default=False, metadata={\"help\": \"Whether to overwrite the Hub revision.\"})\n push_to_hub_revision: bool = field(default=False, metadata={\"help\": \"Whether to push to a Hub revision/branch.\"})\n system_prompt: Optional[str] = field(\n default=None,\n metadata={\"help\": \"The optional system prompt to use.\"},\n )\n wandb_log_unique_prompts: bool = field(\n default=True,\n metadata={\n \"help\": (\"Whether to log the unique prompts to wandb. This will create a new run for each unique prompt.\")\n },\n )\n wandb_entity: Optional[str] = field(\n default=None,\n metadata={\"help\": (\"The entity to store runs under.\")},\n )\n wandb_project: Optional[str] = field(\n default=None,\n metadata={\"help\": (\"The project to store runs under.\")},\n )\n wandb_run_group: Optional[str] = field(\n default=None,\n metadata={\"help\": (\"The group to store runs under.\")},\n )\n\n\n@dataclass\nclass SFTConfig(trl.SFTConfig):\n \"\"\"\n args for callbacks, benchmarks etc\n \"\"\"\n\n benchmarks: list[str] = field(\n default_factory=lambda: [],\n metadata={\"help\": \"The benchmarks to run after training.\"},\n )\n callbacks: list[str] = field(\n default_factory=lambda: [],\n metadata={\"help\": \"The callbacks to run during training.\"},\n )\n chat_template: Optional[str] = field(default=None, metadata={\"help\": \"The chat template to use.\"})\n system_prompt: Optional[str] = field(\n default=None,\n metadata={\"help\": \"The optional system prompt to use for benchmarking.\"},\n )\n hub_model_revision: Optional[str] = field(\n default=\"main\",\n metadata={\"help\": \"The Hub model branch to push the model to.\"},\n )\n overwrite_hub_revision: bool = field(default=False, metadata={\"help\": \"Whether to overwrite the Hub revision.\"})\n push_to_hub_revision: bool = field(default=False, metadata={\"help\": \"Whether to push to a Hub revision/branch.\"})\n wandb_entity: Optional[str] = field(\n default=None,\n metadata={\"help\": (\"The entity to store runs under.\")},\n )\n wandb_project: Optional[str] = field(\n default=None,\n metadata={\"help\": (\"The project to store runs under.\")},\n )\n wandb_run_group: Optional[str] = field(\n default=None,\n metadata={\"help\": (\"The group to store runs under.\")},\n )\n\n\n@dataclass\nclass GRPOScriptArguments(ScriptArguments):\n \"\"\"\n Script arguments for the GRPO training script.\n\n Args:\n reward_funcs (`list[str]`):\n List of reward functions. Possible values: 'accuracy', 'format', 'reasoning_steps', 'cosine', 'repetition_penalty', 'length', 'tag_count', 'code', 'ioi_code', 'code_format', 'soft_overlong_punishment'.\n cosine_min_value_wrong (`float`):\n Minimum reward for cosine scaling for wrong answers.\n cosine_max_value_wrong (`float`):\n Maximum reward for cosine scaling for wrong answers.\n cosine_min_value_correct (`float`):\n Minimum reward for cosine scaling for correct answers.\n cosine_max_value_correct (`float`):\n Maximum reward for cosine scaling for correct answers.\n cosine_max_len (`int`):\n Maximum length for cosine scaling.\n code_language (`str`):\n Language for code format reward.\n max_completion_len (`int`):\n Maximum number of tokens in completion.\n soft_punish_cache (`int`):\n Minimum number of tokens in completion.\n \"\"\"\n\n reward_funcs: list[str] = field(\n default_factory=lambda: [\"accuracy\", \"format\", \"tag_count\"],\n metadata={\n \"help\": \"List of reward functions. Possible values: 'accuracy', 'format', 'reasoning_steps', 'cosine', 'repetition_penalty', 'length', tag_count', 'code', 'code_format'\"\n },\n )\n cosine_min_value_wrong: float = field(\n default=0.0,\n metadata={\"help\": \"Minimum reward for wrong answers\"},\n )\n cosine_max_value_wrong: float = field(\n default=-0.5,\n metadata={\"help\": \"Maximum reward for wrong answers\"},\n )\n cosine_min_value_correct: float = field(\n default=0.5,\n metadata={\"help\": \"Minimum reward for correct answers\"},\n )\n cosine_max_value_correct: float = field(\n default=1.0,\n metadata={\"help\": \"Maximum reward for correct answers\"},\n )\n cosine_max_len: int = field(\n default=1000,\n metadata={\"help\": \"Maximum length for scaling\"},\n )\n repetition_n_grams: int = field(\n default=3,\n metadata={\"help\": \"Number of n-grams for repetition penalty reward\"},\n )\n repetition_max_penalty: float = field(\n default=-1.0,\n metadata={\"help\": \"Maximum (negative) penalty for for repetition penalty reward\"},\n )\n code_language: str = field(\n default=\"python\",\n # '(?:python|cpp)'\n metadata={\n \"help\": \"Language for code format reward. Based on E2B supported languages https://e2b.dev/docs/code-interpreting/supported-languages\",\n \"choices\": [\"python\", \"javascript\", \"r\", \"java\", \"bash\", \"cpp\"],\n },\n )\n code_eval_test_batch_size: int = field(\n default=1,\n metadata={\n \"help\": \"for each generation, evaluate these many test cases in parallel, then check if any of them failed (0 score): if so stop evaluating; otherwise continue with the next batch of test cases. Useful to avoid overloading the eval server + save time on wrong solutions\"\n },\n )\n code_eval_scoring_mode: Literal[\"pass_fail\", \"partial\", \"weighted_sum\"] = field(\n default=\"weighted_sum\",\n metadata={\"help\": \"use fraction of passed test cases as reward. If false, use 0/1 scoring.\"},\n )\n parallel_code_exec_per_proc: int = field(\n default=2,\n metadata={\n \"help\": \"Number of parallel E2B code executions per process. Default of 2 is suitable for the Free Hobby tier of E2B with 8 GPUs used for training.\"\n },\n )\n\n dataset_prompt_column: str = field(\n default=\"prompt\",\n metadata={\"help\": \"Column to use as prompts for training.\"},\n )\n\n e2b_router_url: Optional[str] = field(\n default=None,\n metadata={\"help\": \"URL for the E2B router. See scripts/e2b_router.py\"},\n )\n\n morph_router_url: Optional[str] = field(\n default=None,\n metadata={\"help\": \"URL for the MorphCloud router. See scripts/morph_router.py\"},\n )\n\n code_provider: Optional[str] = field(\n default=\"e2b\",\n metadata={\n \"help\": \"Provider for code execution. Options: 'e2b', 'local', 'morph'.\",\n \"choices\": [\"e2b\", \"local\", \"morph\"],\n },\n )\n\n ioi_provider: Optional[str] = field(\n default=\"piston\",\n metadata={\n \"help\": \"Provider for IOI code execution. Options: 'piston', 'morph'.\",\n \"choices\": [\"piston\", \"morph\"],\n },\n )\n\n max_completion_len: int = field(\n default=16384,\n metadata={\"help\": \"Maximum number of characters in completion.\"},\n )\n soft_punish_cache: int = field(\n default=4096,\n metadata={\"help\": \"Minimum number of characters in completion.\"},\n )\n"], ["/open-r1/src/open_r1/utils/wandb_logging.py", "import os\n\n\ndef init_wandb_training(training_args):\n \"\"\"\n Helper function for setting up Weights & Biases logging tools.\n \"\"\"\n if training_args.wandb_entity is not None:\n os.environ[\"WANDB_ENTITY\"] = training_args.wandb_entity\n if training_args.wandb_project is not None:\n os.environ[\"WANDB_PROJECT\"] = training_args.wandb_project\n if training_args.wandb_run_group is not None:\n os.environ[\"WANDB_RUN_GROUP\"] = training_args.wandb_run_group\n"], ["/open-r1/scripts/pass_rate_filtering/compute_pass_rate.py", "# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# example usage python scripts/filter_dataset.py --config recipes/dataset_filtering/config_demo.yaml\n\nimport logging\nfrom dataclasses import dataclass\nfrom git import Optional\nimport torch\nimport sys\n\nimport datasets\nimport transformers\nfrom datasets import load_dataset\nfrom transformers import set_seed\n\nfrom open_r1.configs import GRPOConfig, GRPOScriptArguments\nfrom open_r1.rewards import get_reward_funcs\nfrom open_r1.utils import get_tokenizer\nfrom trl import ModelConfig, TrlParser\nfrom trl.data_utils import apply_chat_template\nfrom vllm import LLM, SamplingParams\n\nlogger = logging.getLogger(__name__)\n\n@dataclass\nclass PassRateScriptArguments(GRPOScriptArguments):\n # we can be lazy and just use the same script args as GRPO\n output_dataset_name: Optional[str] = None\n pass_rate_min: float = 0.1\n pass_rate_max: float = 0.9\n dataset_start_index: Optional[int] = None\n dataset_end_index: Optional[int] = None\n dataset_split: str = \"train\"\n\n\ndef main(script_args, training_args, model_args):\n # Set seed for reproducibility\n set_seed(training_args.seed)\n\n ###############\n # Setup logging\n ###############\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n handlers=[logging.StreamHandler(sys.stdout)],\n )\n log_level = training_args.get_process_log_level()\n logger.setLevel(log_level)\n datasets.utils.logging.set_verbosity(log_level)\n transformers.utils.logging.set_verbosity(log_level)\n transformers.utils.logging.enable_default_handler()\n transformers.utils.logging.enable_explicit_format()\n\n logger.info(f\"Model parameters {model_args}\")\n logger.info(f\"Script parameters {script_args}\")\n logger.info(f\"Training parameters {training_args}\")\n\n # Load the dataset\n dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config, split=script_args.dataset_split)\n if script_args.dataset_start_index is not None and script_args.dataset_end_index is not None:\n dataset = dataset.select(range(script_args.dataset_start_index, script_args.dataset_end_index))\n\n # Get reward functions from the registry\n reward_funcs = get_reward_funcs(script_args)\n\n # Format into conversation\n def make_conversation(example, prompt_column: str = script_args.dataset_prompt_column):\n example[\"prompt_backup\"] = example[prompt_column]\n \n prompt = []\n\n if training_args.system_prompt is not None:\n prompt.append({\"role\": \"system\", \"content\": training_args.system_prompt})\n\n if prompt_column not in example:\n raise ValueError(f\"Dataset Question Field Error: {prompt_column} is not supported.\")\n\n prompt.append({\"role\": \"user\", \"content\": example[prompt_column]})\n return {\"prompt\": prompt}\n\n dataset = dataset.map(make_conversation)\n tokenizer = get_tokenizer(model_args, training_args)\n \n if \"messages\" in dataset.column_names:\n dataset = dataset.remove_columns(\"messages\")\n \n dataset = dataset.map(apply_chat_template, fn_kwargs={\"tokenizer\": tokenizer})\n llm = LLM(\n model=model_args.model_name_or_path,\n revision=model_args.model_revision,\n trust_remote_code=model_args.trust_remote_code,\n )\n\n sampling_params=SamplingParams(\n temperature=training_args.temperature,\n top_p=training_args.top_p,\n top_k=training_args.top_k,\n n=training_args.num_generations,\n max_tokens=training_args.max_completion_length,\n )\n \n def batch_score(examples):\n prompts = examples[\"prompt\"]\n \n outputs = llm.generate(\n prompts,\n sampling_params=sampling_params,\n use_tqdm=False,\n )\n repeated_prompts = []\n reward_completions = []\n grouped_completions = []\n for output in outputs:\n prompt = output.prompt\n group = []\n for completion in output.outputs:\n text = completion.text\n group.append(text)\n message = [{\"role\": \"assistant\", \"content\": text}]\n repeated_prompts.append(prompt)\n reward_completions.append(message)\n grouped_completions.append(group)\n \n def repeat_each_element_k_times(list_to_repeat: list, k: int) -> list:\n return [element for item in list_to_repeat for element in [item] * k]\n \n rewards_per_func = torch.zeros(len(repeated_prompts), len(reward_funcs))\n for i, reward_func in enumerate(reward_funcs):\n keys = [key for key in examples.data.keys() if key not in [\"prompt\", \"completion\"]]\n reward_kwargs = {key: repeat_each_element_k_times(examples[key], training_args.num_generations) for key in keys}\n output_reward_func = reward_func(prompts=repeated_prompts, completions=reward_completions, **reward_kwargs)\n # Convert None values to NaN\n output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func]\n\n rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32)\n \n reshaped_rewards = rewards_per_func.view(-1, training_args.num_generations)\n \n examples[\"pass_rate_generations\"] = grouped_completions\n examples[\"pass_rate_rewards\"] = reshaped_rewards.tolist()\n\n \n return examples\n \n dataset = dataset.map(batch_score, batched=True, batch_size=64)\n \n # we need to restore the prompt for the final dataset\n def restore_prompt(example):\n example[\"prompt\"] = example[\"prompt_backup\"]\n return example\n \n dataset = dataset.map(restore_prompt)\n dataset = dataset.remove_columns(\"prompt_backup\")\n \n if script_args.output_dataset_name is not None:\n output_dataset_name = script_args.output_dataset_name\n else:\n model_name = model_args.model_name_or_path\n if \"/\" in model_name:\n model_name = model_name.split(\"/\")[-1]\n model_revision = model_args.model_revision\n \n output_dataset_name = f\"{script_args.dataset_name}-{model_name}-{model_revision}-gen\"\n \n config_name=\"default\"\n filtered_config_name = f\"filt-{script_args.pass_rate_min}-{script_args.pass_rate_max}\"\n \n if script_args.dataset_start_index is not None and script_args.dataset_end_index is not None:\n config_name = f\"gen-{script_args.dataset_start_index}-{script_args.dataset_end_index}\"\n filtered_config_name = f\"{filtered_config_name}-{script_args.dataset_start_index}-{script_args.dataset_end_index}\"\n \n dataset.push_to_hub(output_dataset_name, config_name=config_name, revision=\"gen\")\n \n def filter_func(example):\n rewards = example[\"pass_rate_rewards\"]\n # get the mean of the rewards that are not None\n mean_reward = torch.nanmean(torch.tensor(rewards, dtype=torch.float32))\n \n return script_args.pass_rate_min < mean_reward < script_args.pass_rate_max\n \n logger.info(f\"Filtering dataset with low reward threshold {script_args.pass_rate_min} and high reward threshold {script_args.pass_rate_max}\")\n logger.info(f\"Dataset size before filtering: {dataset}\")\n dataset = dataset.filter(filter_func)\n logger.info(f\"Dataset size after filtering: {dataset}\")\n dataset.push_to_hub(output_dataset_name, config_name=filtered_config_name, revision=\"pass_rate\")\n \n \n\nif __name__ == \"__main__\":\n parser = TrlParser((PassRateScriptArguments, GRPOConfig, ModelConfig))\n script_args, training_args, model_args = parser.parse_args_and_config()\n main(script_args, training_args, model_args)\n"], ["/open-r1/scripts/decontaminate.py", "#!/usr/bin/env python\n# coding=utf-8\n# Copyright 2025 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThis script is used to decontaminate a dataset by checking for n-gram overlap with other datasets.\nIt uses the same approach presented in https://huggingface.co/papers/2501.19393,\nas found in: https://github.com/simplescaling/s1/blob/main/data/decontaminate_util.py\n\nUsage:\n\npython scripts/decontaminate.py \\\n --dataset open-r1/verifiable-coding-problems-python \\\n --split train \\\n --ngram_size 8 \\\n --problem_column problem \\\n --cleanup\n\"\"\"\n\nimport collections\n\nfrom tqdm import tqdm\n\n\ndef normalize_string(text: str) -> str:\n \"\"\"Basic string normalization.\"\"\"\n # Convert to lowercase and normalize whitespace\n text = text.lower().strip()\n # Replace multiple spaces with single space\n text = \" \".join(text.split())\n return text\n\n\ndef word_ngrams(text: str, n: int) -> list:\n \"\"\"Generate word-level n-grams from text.\"\"\"\n words = text.split()\n return [\" \".join(words[i : i + n]) for i in range(len(words) - n + 1)]\n\n\ndef build_ngram_lookup(documents: list[str], ngram_size: int = 8) -> dict[str, set[int]]:\n \"\"\"Build ngram lookup for documents.\"\"\"\n lookup = collections.defaultdict(set)\n\n for doc_id, document in enumerate(tqdm(documents)):\n normalized_text = normalize_string(document)\n ngrams = word_ngrams(normalized_text, ngram_size)\n for ngram in ngrams:\n lookup[ngram].add(doc_id)\n\n return lookup\n\n\ndef build_ngram_single(document: str, ngram_size: int = 8) -> set[str]:\n normalized_text = normalize_string(document)\n ngrams = word_ngrams(normalized_text, ngram_size)\n\n return set(ngrams)\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dataset\", type=str, required=True, help=\"Name of the dataset to check for contamination.\")\n parser.add_argument(\"--config\", type=str, default=None, help=\"Name of the dataset config to load.\")\n parser.add_argument(\"--split\", type=str, default=\"train\", help=\"Split to check for contamination, defaults to `train`.\")\n parser.add_argument(\"--ngram_size\", type=int, default=8, help=\"Size of n-grams to build, defaults to 8.\")\n parser.add_argument(\n \"--problem_column\", type=str, default=\"problem\", help=\"Name of the column containing the problem (prompt).\"\n )\n parser.add_argument(\n \"--cleanup\",\n action=\"store_true\",\n help=\"Whether to remove the contaminated rows before pushing the dataset.\",\n )\n parser.add_argument(\n \"--new_dataset_name\",\n type=str,\n default=None,\n help=\"New name for the dataset. If not provided, will reuse the name and add a `_decontaminated` to the name.\"\n )\n args = parser.parse_args()\n\n from datasets import load_dataset, Dataset\n\n # Load the dataset to check for contamination\n ds = load_dataset(args.dataset, name=args.config, split=args.split)\n\n eval_datasets = {\n \"aime_2024\": (load_dataset(\"HuggingFaceH4/aime_2024\", split=\"train\"), \"problem\"),\n \"aime_2025\": (load_dataset(\"yentinglin/aime_2025\", split=\"train\"), \"problem\"),\n \"math_500\": (load_dataset(\"HuggingFaceH4/MATH-500\", split=\"test\"), \"problem\"),\n \"gpqa\": (load_dataset(\"Idavidrein/gpqa\", \"gpqa_diamond\", split=\"train\", trust_remote_code=True), \"Question\"),\n \"lcb\": (\n load_dataset(\n \"livecodebench/code_generation_lite\", split=\"test\", version_tag=\"v4_v5\", trust_remote_code=True\n ),\n \"question_content\",\n ),\n }\n ngram_lookups = {}\n for ds_name, (eval_dataset, problem_col) in eval_datasets.items():\n ngram_lookups[ds_name] = build_ngram_lookup(eval_dataset[problem_col], ngram_size=args.ngram_size)\n\n for eval_name, ngram_lookup in ngram_lookups.items():\n # Update the ngram_lookup variable for each dataset\n def find_contaminated(row):\n # For each example we have to build the ngrams and check for all of them on each row\n ngrams = build_ngram_single(row[args.problem_column], ngram_size=args.ngram_size)\n row[f\"contaminated_{eval_name}\"] = any(set(ngram in ngram_lookup for ngram in ngrams))\n return row\n\n ds = ds.map(find_contaminated, num_proc=8)\n\n # Allow cleaning up via CLI args (removing the contaminated examples and dropping the columns)\n def cleanup(dataset: Dataset) -> Dataset:\n initial_size = len(dataset)\n contamination_cols = [col for col in dataset.column_names if col.startswith(\"contaminated_\")]\n for col in contamination_cols:\n if col.startswith(\"contaminated_\"):\n size_prior = len(dataset)\n dataset = dataset.filter(lambda x: not x[col], num_proc=8)\n if len(dataset) < size_prior:\n print(f\"Removed {size_prior - len(dataset)} samples from '{col.replace('contaminated_', '')}'\")\n dataset = dataset.remove_columns(contamination_cols)\n print(f\"Initial size: {initial_size}, Final size: {len(dataset)}\")\n return dataset\n\n if args.cleanup:\n ds = cleanup(ds)\n\n new_ds_name = args.new_dataset_name or f\"{args.dataset}_decontaminated\"\n config_name = args.config if args.config is not None else \"default\"\n url = ds.push_to_hub(new_ds_name, config_name=config_name, split=\"train\")\n print(f\"Decontaminated dataset: {url}\")\n"], ["/open-r1/src/open_r1/grpo.py", "# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport os\nimport sys\n\nimport datasets\nimport transformers\nfrom transformers import set_seed\nfrom transformers.trainer_utils import get_last_checkpoint\n\nfrom open_r1.configs import GRPOConfig, GRPOScriptArguments\nfrom open_r1.rewards import get_reward_funcs\nfrom open_r1.utils import get_dataset, get_model, get_tokenizer\nfrom open_r1.utils.callbacks import get_callbacks\nfrom open_r1.utils.wandb_logging import init_wandb_training\nfrom trl import GRPOTrainer, ModelConfig, TrlParser, get_peft_config\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef main(script_args, training_args, model_args):\n # Set seed for reproducibility\n set_seed(training_args.seed)\n\n ###############\n # Setup logging\n ###############\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n handlers=[logging.StreamHandler(sys.stdout)],\n )\n log_level = training_args.get_process_log_level()\n logger.setLevel(log_level)\n datasets.utils.logging.set_verbosity(log_level)\n transformers.utils.logging.set_verbosity(log_level)\n transformers.utils.logging.enable_default_handler()\n transformers.utils.logging.enable_explicit_format()\n\n # Log on each process a small summary\n logger.warning(\n f\"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}\"\n + f\" distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}\"\n )\n logger.info(f\"Model parameters {model_args}\")\n logger.info(f\"Script parameters {script_args}\")\n logger.info(f\"Training parameters {training_args}\")\n\n # Check for last checkpoint\n last_checkpoint = None\n if os.path.isdir(training_args.output_dir):\n last_checkpoint = get_last_checkpoint(training_args.output_dir)\n if last_checkpoint is not None and training_args.resume_from_checkpoint is None:\n logger.info(f\"Checkpoint detected, resuming training at {last_checkpoint=}.\")\n\n if \"wandb\" in training_args.report_to:\n init_wandb_training(training_args)\n\n # Load the dataset\n dataset = get_dataset(script_args)\n\n ################\n # Load tokenizer\n ################\n tokenizer = get_tokenizer(model_args, training_args)\n\n ##############\n # Load model #\n ##############\n logger.info(\"*** Loading model ***\")\n model = get_model(model_args, training_args)\n\n # Get reward functions from the registry\n reward_funcs = get_reward_funcs(script_args)\n\n # Format into conversation\n def make_conversation(example, prompt_column: str = script_args.dataset_prompt_column):\n prompt = []\n\n if training_args.system_prompt is not None:\n prompt.append({\"role\": \"system\", \"content\": training_args.system_prompt})\n\n if prompt_column not in example:\n raise ValueError(f\"Dataset Question Field Error: {prompt_column} is not supported.\")\n\n prompt.append({\"role\": \"user\", \"content\": example[prompt_column]})\n return {\"prompt\": prompt}\n\n dataset = dataset.map(make_conversation)\n\n for split in dataset:\n if \"messages\" in dataset[split].column_names:\n dataset[split] = dataset[split].remove_columns(\"messages\")\n\n #############################\n # Initialize the GRPO trainer\n #############################\n trainer = GRPOTrainer(\n model=model,\n reward_funcs=reward_funcs,\n args=training_args,\n train_dataset=dataset[script_args.dataset_train_split],\n eval_dataset=(dataset[script_args.dataset_test_split] if training_args.eval_strategy != \"no\" else None),\n peft_config=get_peft_config(model_args),\n callbacks=get_callbacks(training_args, model_args),\n processing_class=tokenizer,\n )\n\n ###############\n # Training loop\n ###############\n logger.info(\"*** Train ***\")\n checkpoint = None\n if training_args.resume_from_checkpoint is not None:\n checkpoint = training_args.resume_from_checkpoint\n elif last_checkpoint is not None:\n checkpoint = last_checkpoint\n train_result = trainer.train(resume_from_checkpoint=checkpoint)\n metrics = train_result.metrics\n metrics[\"train_samples\"] = len(dataset[script_args.dataset_train_split])\n trainer.log_metrics(\"train\", metrics)\n trainer.save_metrics(\"train\", metrics)\n trainer.save_state()\n\n ##################################\n # Save model and create model card\n ##################################\n logger.info(\"*** Save model ***\")\n # Align the model's generation config with the tokenizer's eos token\n # to avoid unbounded generation in the transformers `pipeline()` function\n trainer.model.generation_config.eos_token_id = tokenizer.eos_token_id\n trainer.save_model(training_args.output_dir)\n logger.info(f\"Model saved to {training_args.output_dir}\")\n\n # Save everything else on main process\n kwargs = {\n \"dataset_name\": script_args.dataset_name,\n \"tags\": [\"open-r1\"],\n }\n if trainer.accelerator.is_main_process:\n trainer.create_model_card(**kwargs)\n # Restore k,v cache for fast inference\n trainer.model.config.use_cache = True\n trainer.model.config.save_pretrained(training_args.output_dir)\n\n ##########\n # Evaluate\n ##########\n if training_args.do_eval:\n logger.info(\"*** Evaluate ***\")\n metrics = trainer.evaluate()\n metrics[\"eval_samples\"] = len(dataset[script_args.dataset_test_split])\n trainer.log_metrics(\"eval\", metrics)\n trainer.save_metrics(\"eval\", metrics)\n\n #############\n # push to hub\n #############\n if training_args.push_to_hub:\n logger.info(\"Pushing to hub...\")\n trainer.push_to_hub(**kwargs)\n\n\nif __name__ == \"__main__\":\n parser = TrlParser((GRPOScriptArguments, GRPOConfig, ModelConfig))\n script_args, training_args, model_args = parser.parse_args_and_config()\n main(script_args, training_args, model_args)\n"], ["/open-r1/src/open_r1/sft.py", "# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nSupervised fine-tuning script for decoder language models.\n\nUsage:\n\n# One 1 node of 8 x H100s\naccelerate launch --config_file=recipes/accelerate_configs/zero3.yaml src/open_r1/sft.py \\\n --model_name_or_path open-r1/Qwen2.5-Math-7B-RoPE-300k \\\n --dataset_name open-r1/Mixture-of-Thoughts \\\n --dataset_config all \\\n --eos_token '<|im_end|>' \\\n --learning_rate 4.0e-5 \\\n --num_train_epochs 5 \\\n --max_seq_length 32768 \\\n --per_device_train_batch_size 2 \\\n --gradient_checkpointing \\\n --bf16 \\\n --use_liger_kernel \\\n --output_dir data/OpenR1-Distill-7B\n\"\"\"\n\nimport logging\nimport os\nimport sys\n\nimport datasets\nimport transformers\nfrom transformers import set_seed\nfrom transformers.trainer_utils import get_last_checkpoint\n\nfrom open_r1.configs import ScriptArguments, SFTConfig\nfrom open_r1.utils import get_dataset, get_model, get_tokenizer\nfrom open_r1.utils.callbacks import get_callbacks\nfrom open_r1.utils.wandb_logging import init_wandb_training\nfrom trl import ModelConfig, SFTTrainer, TrlParser, get_peft_config, setup_chat_format\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef main(script_args, training_args, model_args):\n set_seed(training_args.seed)\n\n ###############\n # Setup logging\n ###############\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n handlers=[logging.StreamHandler(sys.stdout)],\n )\n log_level = training_args.get_process_log_level()\n logger.setLevel(log_level)\n datasets.utils.logging.set_verbosity(log_level)\n transformers.utils.logging.set_verbosity(log_level)\n transformers.utils.logging.enable_default_handler()\n transformers.utils.logging.enable_explicit_format()\n\n logger.info(f\"Model parameters {model_args}\")\n logger.info(f\"Script parameters {script_args}\")\n logger.info(f\"Training parameters {training_args}\")\n\n # Check for last checkpoint\n last_checkpoint = None\n if os.path.isdir(training_args.output_dir):\n last_checkpoint = get_last_checkpoint(training_args.output_dir)\n if last_checkpoint is not None and training_args.resume_from_checkpoint is None:\n logger.info(f\"Checkpoint detected, resuming training at {last_checkpoint=}.\")\n\n if \"wandb\" in training_args.report_to:\n init_wandb_training(training_args)\n\n ######################################\n # Load dataset, tokenizer, and model #\n ######################################\n dataset = get_dataset(script_args)\n tokenizer = get_tokenizer(model_args, training_args)\n model = get_model(model_args, training_args)\n\n if tokenizer.chat_template is None:\n logger.info(\"No chat template provided, defaulting to ChatML.\")\n model, tokenizer = setup_chat_format(model, tokenizer, format=\"chatml\")\n\n ############################\n # Initialize the SFT Trainer\n ############################\n trainer = SFTTrainer(\n model=model,\n args=training_args,\n train_dataset=dataset[script_args.dataset_train_split],\n eval_dataset=(dataset[script_args.dataset_test_split] if training_args.eval_strategy != \"no\" else None),\n processing_class=tokenizer,\n peft_config=get_peft_config(model_args),\n callbacks=get_callbacks(training_args, model_args),\n )\n\n ###############\n # Training loop\n ###############\n logger.info(\"*** Train ***\")\n checkpoint = None\n if training_args.resume_from_checkpoint is not None:\n checkpoint = training_args.resume_from_checkpoint\n elif last_checkpoint is not None:\n checkpoint = last_checkpoint\n train_result = trainer.train(resume_from_checkpoint=checkpoint)\n metrics = train_result.metrics\n metrics[\"train_samples\"] = len(dataset[script_args.dataset_train_split])\n trainer.log_metrics(\"train\", metrics)\n trainer.save_metrics(\"train\", metrics)\n trainer.save_state()\n\n ##################################\n # Save model and create model card\n ##################################\n logger.info(\"*** Save model ***\")\n # Align the model's generation config with the tokenizer's eos token\n # to avoid unbounded generation in the transformers `pipeline()` function\n trainer.model.generation_config.eos_token_id = tokenizer.eos_token_id\n trainer.save_model(training_args.output_dir)\n logger.info(f\"Model saved to {training_args.output_dir}\")\n\n # Save everything else on main process\n kwargs = {\n \"dataset_name\": script_args.dataset_name,\n \"tags\": [\"open-r1\"],\n }\n if trainer.accelerator.is_main_process:\n trainer.create_model_card(**kwargs)\n # Restore k,v cache for fast inference\n trainer.model.config.use_cache = True\n trainer.model.config.save_pretrained(training_args.output_dir)\n\n ##########\n # Evaluate\n ##########\n if training_args.do_eval:\n logger.info(\"*** Evaluate ***\")\n metrics = trainer.evaluate()\n metrics[\"eval_samples\"] = len(dataset[script_args.dataset_test_split])\n trainer.log_metrics(\"eval\", metrics)\n trainer.save_metrics(\"eval\", metrics)\n\n #############\n # push to hub\n #############\n if training_args.push_to_hub:\n logger.info(\"Pushing to hub...\")\n trainer.push_to_hub(**kwargs)\n\n\nif __name__ == \"__main__\":\n parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))\n script_args, training_args, model_args = parser.parse_args_and_config()\n main(script_args, training_args, model_args)\n"], ["/open-r1/src/open_r1/generate.py", "# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Optional\n\nfrom distilabel.llms import OpenAILLM\nfrom distilabel.pipeline import Pipeline\nfrom distilabel.steps import StepResources\nfrom distilabel.steps.tasks import TextGeneration\n\n\ndef build_distilabel_pipeline(\n model: str,\n base_url: str = \"http://localhost:8000/v1\",\n prompt_column: Optional[str] = None,\n prompt_template: str = \"{{ instruction }}\",\n temperature: Optional[float] = None,\n top_p: Optional[float] = None,\n max_new_tokens: int = 8192,\n num_generations: int = 1,\n input_batch_size: int = 64,\n client_replicas: int = 1,\n timeout: int = 900,\n retries: int = 0,\n) -> Pipeline:\n generation_kwargs = {\"max_new_tokens\": max_new_tokens}\n\n if temperature is not None:\n generation_kwargs[\"temperature\"] = temperature\n\n if top_p is not None:\n generation_kwargs[\"top_p\"] = top_p\n\n with Pipeline().ray() as pipeline:\n TextGeneration(\n llm=OpenAILLM(\n base_url=base_url,\n api_key=\"something\",\n model=model,\n timeout=timeout,\n max_retries=retries,\n generation_kwargs=generation_kwargs,\n ),\n template=prompt_template,\n input_mappings=({\"instruction\": prompt_column} if prompt_column is not None else {}),\n input_batch_size=input_batch_size,\n num_generations=num_generations,\n group_generations=True,\n resources=StepResources(replicas=client_replicas),\n )\n\n return pipeline\n\n\nif __name__ == \"__main__\":\n import argparse\n\n from datasets import load_dataset\n\n parser = argparse.ArgumentParser(description=\"Run distilabel pipeline for generating responses with DeepSeek R1\")\n parser.add_argument(\n \"--hf-dataset\",\n type=str,\n required=True,\n help=\"HuggingFace dataset to load\",\n )\n parser.add_argument(\n \"--hf-dataset-config\",\n type=str,\n required=False,\n help=\"Dataset config to use\",\n )\n parser.add_argument(\n \"--hf-dataset-split\",\n type=str,\n default=\"train\",\n help=\"Dataset split to use\",\n )\n parser.add_argument(\n \"--prompt-column\",\n type=str,\n default=\"prompt\",\n )\n parser.add_argument(\n \"--prompt-template\",\n type=str,\n default=\"{{ instruction }}\",\n help=\"Template string for formatting prompts.\",\n )\n parser.add_argument(\n \"--model\",\n type=str,\n required=True,\n help=\"Model name to use for generation\",\n )\n parser.add_argument(\n \"--vllm-server-url\",\n type=str,\n default=\"http://localhost:8000/v1\",\n help=\"URL of the vLLM server\",\n )\n parser.add_argument(\n \"--temperature\",\n type=float,\n help=\"Temperature for generation\",\n )\n parser.add_argument(\n \"--top-p\",\n type=float,\n help=\"Top-p value for generation\",\n )\n parser.add_argument(\n \"--max-new-tokens\",\n type=int,\n default=8192,\n help=\"Maximum number of new tokens to generate\",\n )\n parser.add_argument(\n \"--num-generations\",\n type=int,\n default=1,\n help=\"Number of generations per problem\",\n )\n parser.add_argument(\n \"--input-batch-size\",\n type=int,\n default=64,\n help=\"Batch size for input processing\",\n )\n parser.add_argument(\n \"--client-replicas\",\n type=int,\n default=1,\n help=\"Number of client replicas for parallel processing\",\n )\n parser.add_argument(\n \"--timeout\",\n type=int,\n default=600,\n help=\"Request timeout in seconds (default: 600)\",\n )\n parser.add_argument(\n \"--retries\",\n type=int,\n default=0,\n help=\"Number of retries for failed requests (default: 0)\",\n )\n parser.add_argument(\n \"--hf-output-dataset\",\n type=str,\n required=False,\n help=\"HuggingFace repo to push results to\",\n )\n parser.add_argument(\n \"--private\",\n action=\"store_true\",\n help=\"Whether to make the output dataset private when pushing to HF Hub\",\n )\n\n args = parser.parse_args()\n\n print(\"\\nRunning with arguments:\")\n for arg, value in vars(args).items():\n print(f\" {arg}: {value}\")\n print()\n\n print(f\"Loading '{args.hf_dataset}' (config: {args.hf_dataset_config}, split: {args.hf_dataset_split}) dataset...\")\n dataset = load_dataset(args.hf_dataset, args.hf_dataset_config, split=args.hf_dataset_split)\n print(\"Dataset loaded!\")\n\n pipeline = build_distilabel_pipeline(\n model=args.model,\n base_url=args.vllm_server_url,\n prompt_template=args.prompt_template,\n prompt_column=args.prompt_column,\n temperature=args.temperature,\n top_p=args.top_p,\n max_new_tokens=args.max_new_tokens,\n num_generations=args.num_generations,\n input_batch_size=args.input_batch_size,\n client_replicas=args.client_replicas,\n timeout=args.timeout,\n retries=args.retries,\n )\n\n print(\"Running generation pipeline...\")\n distiset = pipeline.run(\n dataset=dataset,\n dataset_batch_size=args.input_batch_size * 1000,\n use_cache=False,\n )\n print(\"Generation pipeline finished!\")\n\n if args.hf_output_dataset:\n print(f\"Pushing resulting dataset to '{args.hf_output_dataset}'...\")\n distiset.push_to_hub(args.hf_output_dataset, private=args.private)\n print(\"Dataset pushed!\")\n"], ["/open-r1/scripts/generate_reasoning.py", "import argparse\nimport asyncio\nimport hashlib\nimport json\nimport os\nimport random\nfrom asyncio import Lock\nfrom typing import Set\n\nfrom datasets import load_dataset\nfrom tqdm.asyncio import tqdm\n\nimport aiofiles\nimport aiohttp\nimport uvloop\n\n\nfile_lock = Lock()\n\n\nasync def generate_completion(session, prompt, args):\n retry_budget = 10\n while retry_budget > 0:\n try:\n await asyncio.sleep(random.uniform(0.0, 0.1))\n async with session.post(\n f\"http://{args.api_addr}/v1/chat/completions\",\n json={\n \"model\": \"default\",\n \"messages\": [{\"role\": \"user\", \"content\": prompt}],\n \"max_tokens\": args.max_tokens,\n \"temperature\": args.temperature,\n \"top_p\": args.top_p,\n },\n headers={\"Authorization\": \"Bearer EMPTY\"},\n ) as response:\n return await response.json(content_type=None)\n except Exception as e:\n print(f\"API error (will retry): {e}\")\n retry_budget -= 1\n await asyncio.sleep(10)\n return None\n\n\nasync def process_example(example, session, args, output_file, pbar):\n prompt = args.prompt_template.format(prompt=example[args.prompt_column])\n\n try:\n tasks = [generate_completion(session, prompt, args) for _ in range(args.num_generations)]\n\n completions = await asyncio.gather(*tasks)\n\n if any(completion is None for completion in completions):\n print(f\"Error processing example\")\n pbar.update(1)\n return None\n\n generations = []\n finish_reasons = []\n api_metadata = []\n\n for completion in completions:\n generations.append(completion[\"choices\"][0][\"message\"][\"content\"])\n finish_reasons.append(completion[\"choices\"][0][\"finish_reason\"])\n api_metadata.append(completion[\"usage\"])\n\n # Combine original dataset fields with generations\n result = {\n **example, # Preserve all original dataset fields\n \"generations\": generations,\n \"finish_reasons\": finish_reasons,\n \"api_metadata\": api_metadata,\n }\n\n # Write to file with lock\n async with file_lock:\n async with aiofiles.open(output_file, mode=\"a\") as f:\n await f.write(json.dumps(result) + \"\\n\")\n await f.flush()\n\n pbar.set_postfix(active=len(pbar.active_tasks), refresh=False)\n pbar.update(1)\n\n return result\n except Exception as e:\n print(f\"Error processing example: {e}\")\n pbar.update(1)\n return None\n\n\nasync def load_processed_uuids(output_file, uuid_column):\n processed_uuids = set()\n if os.path.exists(output_file):\n async with aiofiles.open(output_file, mode=\"r\") as f:\n async for line in f:\n try:\n data = json.loads(line)\n processed_uuids.add(hashlib.md5(str(data[uuid_column]).encode()).hexdigest())\n except json.JSONDecodeError:\n continue\n return processed_uuids\n\n\nasync def main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dataset-name\", type=str, required=True)\n parser.add_argument(\"--output-file\", type=str, required=True)\n parser.add_argument(\"--prompt-column\", type=str, required=True)\n parser.add_argument(\"--uuid-column\", type=str, required=True)\n parser.add_argument(\"--api-addr\", type=str, default=\"localhost:39876\")\n parser.add_argument(\"--num-generations\", type=int, default=4)\n parser.add_argument(\n \"--prompt-template\",\n type=str,\n default=\"You will be given a problem. Please reason step by step, and put your final answer within \\\\boxed{{}}:\\n{prompt}\",\n )\n parser.add_argument(\"--temperature\", type=float, default=0.6)\n parser.add_argument(\"--top-p\", type=float, default=0.95)\n parser.add_argument(\"--max-tokens\", type=int, default=16384)\n parser.add_argument(\"--max-concurrent\", type=int, default=1000)\n args = parser.parse_args()\n\n dataset = load_dataset(args.dataset_name, split=\"train\").shuffle()\n processed_uuids = await load_processed_uuids(args.output_file, args.uuid_column)\n if processed_uuids:\n print(f\"Found {len(processed_uuids)} already processed examples, resuming from there...\")\n\n if not os.path.exists(args.output_file):\n async with aiofiles.open(args.output_file, mode=\"w\") as f:\n await f.write(\"\")\n\n active_tasks: Set[asyncio.Task] = set()\n\n pbar = tqdm(\n total=len(dataset) - len(processed_uuids),\n desc=\"Generating responses\",\n unit=\"row\",\n mininterval=2,\n smoothing=0.0001,\n )\n pbar.active_tasks = active_tasks\n\n async with aiohttp.ClientSession(\n timeout=aiohttp.ClientTimeout(total=60 * 60),\n connector=aiohttp.TCPConnector(limit=args.max_concurrent, ttl_dns_cache=300, keepalive_timeout=60 * 60),\n ) as session:\n for example in dataset:\n uuid = hashlib.md5(str(example[args.uuid_column]).encode()).hexdigest()\n if uuid not in processed_uuids:\n # Wait if we've hit the concurrency limit\n while len(active_tasks) >= args.max_concurrent:\n done, active_tasks = await asyncio.wait(active_tasks, return_when=asyncio.FIRST_COMPLETED)\n for task in done:\n try:\n await task\n except Exception as e:\n print(f\"Task failed: {e}\")\n\n task = asyncio.create_task(process_example(example, session, args, args.output_file, pbar))\n active_tasks.add(task)\n task.add_done_callback(active_tasks.discard)\n\n pbar.set_postfix(active=len(active_tasks), refresh=True)\n\n # Wait for remaining tasks\n if active_tasks:\n await asyncio.gather(*active_tasks, return_exceptions=True)\n\n pbar.close()\n\n\nif __name__ == \"__main__\":\n uvloop.install()\n asyncio.run(main())\n"], ["/open-r1/src/open_r1/rewards.py", "# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Reward functions for GRPO training.\"\"\"\n\nimport asyncio\nimport json\nimport math\nimport re\nfrom functools import partial, update_wrapper\nfrom typing import Callable, Dict, Literal, Optional\n\nfrom latex2sympy2_extended import NormalizationConfig\nfrom math_verify import LatexExtractionConfig, parse, verify\n\nfrom .utils.code_providers import get_provider\nfrom .utils.competitive_programming import (\n SubtaskResult,\n add_includes,\n get_morph_client_from_env,\n get_piston_client_from_env,\n)\nfrom .utils.competitive_programming import patch_code as cf_patch_code\nfrom .utils.competitive_programming import score_submission as cf_score_submission\nfrom .utils.competitive_programming import score_subtask\n\n\ndef accuracy_reward(completions: list[list[dict[str, str]]], solution: list[str], **kwargs) -> list[Optional[float]]:\n \"\"\"Reward function that checks if the completion is the same as the ground truth.\"\"\"\n contents = [completion[0][\"content\"] for completion in completions]\n rewards = []\n for content, sol in zip(contents, solution):\n gold_parsed = parse(\n sol,\n extraction_mode=\"first_match\",\n )\n if len(gold_parsed) != 0:\n # We require the answer to be provided in correct latex (no malformed operators)\n answer_parsed = parse(\n content,\n extraction_config=[\n LatexExtractionConfig(\n normalization_config=NormalizationConfig(\n nits=False,\n malformed_operators=False,\n basic_latex=True,\n equations=True,\n boxed=\"all\",\n units=True,\n ),\n # Ensures that boxed is tried first\n boxed_match_priority=0,\n try_extract_without_anchor=False,\n )\n ],\n extraction_mode=\"first_match\",\n )\n # Compute binary rewards if verifiable, `None` otherwise to skip this example\n try:\n reward = float(verify(gold_parsed, answer_parsed))\n except Exception as e:\n print(f\"verify failed: {e}, answer: {answer_parsed}, gold: {gold_parsed}\")\n reward = None\n else:\n # If the gold solution is not parseable, we assign `None` to skip this example\n reward = None\n print(\"Failed to parse gold solution: \", sol)\n rewards.append(reward)\n\n return rewards\n\n\ndef format_reward(completions, **kwargs):\n \"\"\"Reward function that checks if the reasoning process is enclosed within and tags, while the final answer is enclosed within and tags.\"\"\"\n pattern = r\"^\\n.*?\\n\\n\\n.*?\\n$\"\n completion_contents = [completion[0][\"content\"] for completion in completions]\n matches = [re.match(pattern, content, re.DOTALL | re.MULTILINE) for content in completion_contents]\n return [1.0 if match else 0.0 for match in matches]\n\n\ndef tag_count_reward(completions, **kwargs) -> list[float]:\n \"\"\"Reward function that checks if we produce the desired number of think and answer tags associated with `format_reward()`.\n\n Adapted from: https://gist.github.com/willccbb/4676755236bb08cab5f4e54a0475d6fb#file-grpo_demo-py-L90\n \"\"\"\n\n def count_tags(text: str) -> float:\n count = 0.0\n if text.count(\"\\n\") == 1:\n count += 0.25\n if text.count(\"\\n\\n\") == 1:\n count += 0.25\n if text.count(\"\\n\\n\") == 1:\n count += 0.25\n if text.count(\"\\n\") == 1:\n count += 0.25\n return count\n\n contents = [completion[0][\"content\"] for completion in completions]\n return [count_tags(c) for c in contents]\n\n\ndef reasoning_steps_reward(completions, **kwargs):\n r\"\"\"Reward function that checks for clear step-by-step reasoning.\n Regex pattern:\n Step \\d+: - matches \"Step 1:\", \"Step 2:\", etc.\n ^\\d+\\. - matches numbered lists like \"1.\", \"2.\", etc. at start of line\n \\n- - matches bullet points with hyphens\n \\n\\* - matches bullet points with asterisks\n First,|Second,|Next,|Finally, - matches transition words\n \"\"\"\n pattern = r\"(Step \\d+:|^\\d+\\.|\\n-|\\n\\*|First,|Second,|Next,|Finally,)\"\n completion_contents = [completion[0][\"content\"] for completion in completions]\n matches = [len(re.findall(pattern, content)) for content in completion_contents]\n\n # Magic number 3 to encourage 3 steps and more, otherwise partial reward\n return [min(1.0, count / 3) for count in matches]\n\n\ndef len_reward(completions: list[Dict[str, str]], solution: list[str], **kwargs) -> float:\n \"\"\"Compute length-based rewards to discourage overthinking and promote token efficiency.\n\n Taken from the Kimi 1.5 tech report: https://huggingface.co/papers/2501.12599\n\n Args:\n completions: List of model completions\n solution: List of ground truth solutions\n\n Returns:\n List of rewards where:\n - For correct answers: reward = 0.5 - (len - min_len)/(max_len - min_len)\n - For incorrect answers: reward = min(0, 0.5 - (len - min_len)/(max_len - min_len))\n \"\"\"\n contents = [completion[0][\"content\"] for completion in completions]\n\n # First check correctness of answers\n correctness = []\n for content, sol in zip(contents, solution):\n gold_parsed = parse(\n sol,\n extraction_mode=\"first_match\",\n extraction_config=[LatexExtractionConfig()],\n )\n if len(gold_parsed) == 0:\n # Skip unparseable examples\n correctness.append(True) # Treat as correct to avoid penalizing\n print(\"Failed to parse gold solution: \", sol)\n continue\n\n answer_parsed = parse(\n content,\n extraction_config=[\n LatexExtractionConfig(\n normalization_config=NormalizationConfig(\n nits=False,\n malformed_operators=False,\n basic_latex=True,\n equations=True,\n boxed=True,\n units=True,\n ),\n boxed_match_priority=0,\n try_extract_without_anchor=False,\n )\n ],\n extraction_mode=\"first_match\",\n )\n correctness.append(verify(answer_parsed, gold_parsed))\n\n # Calculate lengths\n lengths = [len(content) for content in contents]\n min_len = min(lengths)\n max_len = max(lengths)\n\n # If all responses have the same length, return zero rewards\n if max_len == min_len:\n return [0.0] * len(completions)\n\n rewards = []\n for length, is_correct in zip(lengths, correctness):\n lambda_val = 0.5 - (length - min_len) / (max_len - min_len)\n\n if is_correct:\n reward = lambda_val\n else:\n reward = min(0, lambda_val)\n\n rewards.append(float(reward))\n\n return rewards\n\n\ndef get_cosine_scaled_reward(\n min_value_wrong: float = -1.0,\n max_value_wrong: float = -0.5,\n min_value_correct: float = 0.5,\n max_value_correct: float = 1.0,\n max_len: int = 1000,\n):\n def cosine_scaled_reward(completions, solution, **kwargs):\n \"\"\"Reward function that scales based on completion length using a cosine schedule.\n\n Shorter correct solutions are rewarded more than longer ones.\n Longer incorrect solutions are penalized less than shorter ones.\n\n Args:\n completions: List of model completions\n solution: List of ground truth solutions\n\n This function is parameterized by the following arguments:\n min_value_wrong: Minimum reward for wrong answers\n max_value_wrong: Maximum reward for wrong answers\n min_value_correct: Minimum reward for correct answers\n max_value_correct: Maximum reward for correct answers\n max_len: Maximum length for scaling\n \"\"\"\n contents = [completion[0][\"content\"] for completion in completions]\n rewards = []\n\n for content, sol in zip(contents, solution):\n gold_parsed = parse(\n sol,\n extraction_mode=\"first_match\",\n extraction_config=[LatexExtractionConfig()],\n )\n if len(gold_parsed) == 0:\n rewards.append(1.0) # Skip unparseable examples\n print(\"Failed to parse gold solution: \", sol)\n continue\n\n answer_parsed = parse(\n content,\n extraction_config=[\n LatexExtractionConfig(\n normalization_config=NormalizationConfig(\n nits=False,\n malformed_operators=False,\n basic_latex=True,\n equations=True,\n boxed=True,\n units=True,\n ),\n boxed_match_priority=0,\n try_extract_without_anchor=False,\n )\n ],\n extraction_mode=\"first_match\",\n )\n\n is_correct = verify(answer_parsed, gold_parsed)\n gen_len = len(content)\n\n # Apply cosine scaling based on length\n progress = gen_len / max_len\n cosine = math.cos(progress * math.pi)\n\n if is_correct:\n min_value = min_value_correct\n max_value = max_value_correct\n else:\n # Swap min/max for incorrect answers\n min_value = max_value_wrong\n max_value = min_value_wrong\n\n reward = min_value + 0.5 * (max_value - min_value) * (1.0 + cosine)\n rewards.append(float(reward))\n\n return rewards\n\n return cosine_scaled_reward\n\n\ndef get_repetition_penalty_reward(ngram_size: int, max_penalty: float, language: str = \"en\"):\n \"\"\"\n Computes N-gram repetition penalty as described in Appendix C.2 of https://huggingface.co/papers/2502.03373.\n Reference implementation from: https://github.com/eddycmu/demystify-long-cot/blob/release/openrlhf/openrlhf/reward/repetition.py\n\n Args:\n ngram_size: size of the n-grams\n max_penalty: Maximum (negative) penalty for wrong answers\n language: Language of the text, defaults to `en`. Used to choose the way to split the text into n-grams.\n \"\"\"\n if max_penalty > 0:\n raise ValueError(f\"max_penalty {max_penalty} should not be positive\")\n\n if language == \"en\":\n\n def zipngram(text: str, ngram_size: int):\n words = text.lower().split()\n return zip(*[words[i:] for i in range(ngram_size)]), words\n\n elif language == \"zh\":\n from transformers.utils.import_utils import _is_package_available\n\n if not _is_package_available(\"jieba\"):\n raise ValueError(\"Please install jieba to use Chinese language\")\n\n def zipngram(text: str, ngram_size: int):\n import jieba\n\n seg_list = list(jieba.cut(text))\n return zip(*[seg_list[i:] for i in range(ngram_size)]), seg_list\n\n else:\n raise ValueError(\n f\"Word splitting for language `{language}` is not yet implemented. Please implement your own zip-ngram function.\"\n )\n\n def repetition_penalty_reward(completions, **kwargs) -> float:\n \"\"\"\n reward function the penalizes repetitions\n ref implementation: https://github.com/eddycmu/demystify-long-cot/blob/release/openrlhf/openrlhf/reward/repetition.py\n\n Args:\n completions: List of model completions\n \"\"\"\n\n contents = [completion[0][\"content\"] for completion in completions]\n rewards = []\n for completion in contents:\n if completion == \"\":\n rewards.append(0.0)\n continue\n\n ngrams = set()\n total = 0\n ngram_array, words = zipngram(completion, ngram_size)\n\n if len(words) < ngram_size:\n rewards.append(0.0)\n continue\n\n for ng in ngram_array:\n ngrams.add(ng)\n total += 1\n\n scaling = 1 - len(ngrams) / total\n reward = scaling * max_penalty\n rewards.append(reward)\n return rewards\n\n return repetition_penalty_reward\n\n\ndef _init_event_loop():\n \"\"\"Initialize or get the current event loop.\"\"\"\n try:\n loop = asyncio.get_event_loop()\n except RuntimeError:\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n return loop\n\n\ndef ioi_code_reward(completions, test_batch_size: int = 1, provider_type: str = \"piston\", **kwargs) -> list[float]:\n \"\"\"Reward function that evaluates IOI problems using a specified execution client.\n\n Assumes the dataset has the same format as hf.co/datasets/open-r1/ioi\n\n Args:\n completions: List of model completions to evaluate\n test_batch_size: Evaluate these many test cases in parallel, then check if any of them failed (0 score):\n if so stop evaluating; otherwise continue with the next batch of test cases.\n provider_type: The execution provider to use (default: \"piston\"). Supported values: \"piston\", \"morph\"\n **kwargs: Additional arguments passed from the dataset\n \"\"\"\n # Get the appropriate client based on provider_type\n if provider_type == \"morph\":\n execution_client = get_morph_client_from_env()\n else:\n # for info on setting up piston workers, see slurm/piston/README.md\n execution_client = get_piston_client_from_env()\n\n code_snippets = [\n # note: grading is automatically skipped if no code is extracted\n add_includes(extract_code(completion[-1][\"content\"], \"cpp\"), problem_id)\n for completion, problem_id in zip(completions, kwargs[\"id\"])\n ]\n\n async def run_catch_exceptions(task):\n try:\n return await task\n except Exception as e:\n print(f\"Error from {provider_type} worker: {e}\")\n return SubtaskResult()\n\n problems_data = [dict(zip(kwargs.keys(), values)) for values in zip(*kwargs.values())]\n\n loop = _init_event_loop()\n evals = [\n loop.create_task(\n run_catch_exceptions(\n score_subtask(\n execution_client,\n problem_data,\n code,\n test_batch_size=test_batch_size,\n )\n )\n )\n for problem_data, code in zip(problems_data, code_snippets)\n ]\n results = loop.run_until_complete(asyncio.gather(*evals))\n\n return [result.score for result in results]\n\n\ndef cf_code_reward(\n completions,\n test_batch_size: int = 1,\n patch_code: bool = False,\n scoring_mode: Literal[\"pass_fail\", \"partial\", \"weighted_sum\"] = \"weighted_sum\",\n **kwargs,\n) -> list[float]:\n \"\"\"Reward function that evaluates Codeforces problems using Piston+our CF package.\n\n Assumes the dataset has the same format as hf.co/datasets/open-r1/codeforces (verifiable-prompts subset)\n\n test_batch_size: evaluate these many test cases in parallel, then check if any of them failed (0 score): if so stop evaluating; otherwise continue with the next batch of test cases.\n \"\"\"\n # for info on setting up piston workers, see slurm/piston/README.md\n piston_client = get_piston_client_from_env()\n\n languages = kwargs[\"language\"] if \"language\" in kwargs else [None] * len(completions)\n code_snippets = [\n # note: grading is automatically skipped if a problem has no tests\n cf_patch_code(extract_code(completion[-1][\"content\"], language), language)\n if patch_code\n else extract_code(completion[-1][\"content\"], language)\n for completion, language in zip(completions, languages)\n ]\n\n async def run_catch_exceptions(task):\n try:\n return await task\n except Exception as e:\n print(f\"Error from Piston worker: {e}\")\n return None\n\n # load problem data. undo separating kwargs by column\n problems_data = [dict(zip(kwargs.keys(), values)) for values in zip(*kwargs.values())]\n\n loop = _init_event_loop()\n evals = [\n loop.create_task(\n run_catch_exceptions(\n cf_score_submission(\n piston_client,\n problem_data,\n code,\n test_batch_size=test_batch_size,\n scoring_mode=scoring_mode,\n submission_language=problem_data.get(\"language\", None),\n )\n )\n )\n for problem_data, code in zip(problems_data, code_snippets)\n ]\n results = loop.run_until_complete(asyncio.gather(*evals))\n\n return results\n\n\ndef extract_code(completion: str, language: str | None = \"python\") -> str:\n if language is None:\n return \"\"\n pattern = re.compile(rf\"```{language}\\n(.*?)```\", re.DOTALL)\n matches = pattern.findall(completion)\n extracted_answer = matches[-1] if len(matches) >= 1 else \"\"\n return extracted_answer\n\n\ndef binary_code_reward(\n completions,\n num_parallel: int = 2,\n provider_type: str = \"e2b\",\n enforce_same_language: bool = False,\n **kwargs,\n) -> list[float]:\n rewards = code_reward(\n completions,\n num_parallel=num_parallel,\n provider_type=provider_type,\n enforce_same_language=enforce_same_language,\n **kwargs,\n )\n BINARY_THRESHOLD = 0.99\n\n output = []\n for reward in rewards:\n if reward is None:\n output.append(None)\n else:\n output.append(1.0 if reward > BINARY_THRESHOLD else 0.0)\n\n return output\n\n\ndef code_reward(\n completions,\n num_parallel: int = 2,\n provider_type: str = \"e2b\",\n enforce_same_language: bool = False,\n **kwargs,\n) -> list[float]:\n \"\"\"Reward function that evaluates code snippets using a code execution provider.\n\n Assumes the dataset contains a `verification_info` column with test cases.\n\n Args:\n completions: List of model completions to evaluate\n num_parallel: Number of parallel code executions (default: 2)\n provider_type: Which code execution provider to use (default: \"e2b\")\n enforce_same_language: If True, verify all problems use the same language (default: False)\n **kwargs: Additional arguments passed to the verification\n \"\"\"\n evaluation_script_template = \"\"\"\n import subprocess\n import json\n\n def evaluate_code(code, test_cases):\n passed = 0\n total = len(test_cases)\n exec_timeout = 5\n\n for case in test_cases:\n process = subprocess.run(\n [\"python3\", \"-c\", code],\n input=case[\"input\"],\n text=True,\n capture_output=True,\n timeout=exec_timeout\n )\n\n if process.returncode != 0: # Error in execution\n continue\n\n output = process.stdout.strip()\n\n # TODO: implement a proper validator to compare against ground truth. For now we just check for exact string match on each line of stdout.\n all_correct = True\n for line1, line2 in zip(output.split('\\\\n'), case['output'].split('\\\\n')):\n all_correct = all_correct and line1.strip() == line2.strip()\n\n if all_correct:\n passed += 1\n\n success_rate = (passed / total)\n return success_rate\n\n code_snippet = {code}\n test_cases = json.loads({test_cases})\n\n evaluate_code(code_snippet, test_cases)\n \"\"\"\n\n code_snippets = [extract_code(completion[-1][\"content\"]) for completion in completions]\n verification_info = kwargs[\"verification_info\"]\n\n template = evaluation_script_template\n\n scripts = [\n template.format(code=json.dumps(code), test_cases=json.dumps(json.dumps(info[\"test_cases\"])))\n for code, info in zip(code_snippets, verification_info)\n ]\n\n language = verification_info[0][\"language\"]\n\n if enforce_same_language:\n all_same_language = all(v[\"language\"] == language for v in verification_info)\n if not all_same_language:\n raise ValueError(\"All verification_info must have the same language\", verification_info)\n\n execution_provider = get_provider(\n provider_type=provider_type,\n num_parallel=num_parallel,\n **kwargs,\n )\n\n return execution_provider.execute_scripts(scripts, [\"python\"] * len(scripts))\n\n\ndef get_code_format_reward(language: str = \"python\"):\n \"\"\"Format reward function specifically for code responses.\n\n Args:\n language: Programming language supported by E2B https://e2b.dev/docs/code-interpreting/supported-languages\n \"\"\"\n\n def code_format_reward(completions, **kwargs):\n # if there is a language field, use it instead of the default language. This way we can have mixed language training.\n languages = kwargs[\"language\"] if \"language\" in kwargs else [language] * len(completions)\n\n completion_contents = [completion[0][\"content\"] for completion in completions]\n matches = [\n re.match(\n rf\"^\\n.*?\\n\\n\\n.*?```{sample_language}.*?```.*?\\n$\",\n content,\n re.DOTALL | re.MULTILINE,\n )\n for content, sample_language in zip(completion_contents, languages)\n ]\n return [1.0 if match else 0.0 for match in matches]\n\n return code_format_reward\n\n\ndef get_soft_overlong_punishment(max_completion_len, soft_punish_cache):\n \"\"\"\n Reward function that penalizes overlong completions. It is used to penalize overlong completions,\n but not to reward shorter completions. Reference: Eq. (13) from the DAPO paper (https://huggingface.co/papers/2503.14476)\n\n Args:\n max_completion_len: Maximum length of the completion\n soft_punish_cache: Minimum length of the completion. If set to 0, no minimum length is applied.\n \"\"\"\n\n def soft_overlong_punishment_reward(completion_ids: list[list[int]], **kwargs) -> list[float]:\n \"\"\"Reward function that penalizes overlong completions.\"\"\"\n rewards = []\n for ids in completion_ids:\n completion_length = len(ids)\n if completion_length <= max_completion_len - soft_punish_cache:\n rewards.append(0.0)\n elif max_completion_len - soft_punish_cache < completion_length <= max_completion_len:\n rewards.append((max_completion_len - soft_punish_cache - completion_length) / soft_punish_cache)\n else:\n rewards.append(-1.0)\n return rewards\n\n return soft_overlong_punishment_reward\n\n\ndef get_reward_funcs(script_args) -> list[Callable]:\n REWARD_FUNCS_REGISTRY = {\n \"accuracy\": accuracy_reward,\n \"format\": format_reward,\n \"reasoning_steps\": reasoning_steps_reward,\n \"cosine\": get_cosine_scaled_reward(\n min_value_wrong=script_args.cosine_min_value_wrong,\n max_value_wrong=script_args.cosine_max_value_wrong,\n min_value_correct=script_args.cosine_min_value_correct,\n max_value_correct=script_args.cosine_max_value_correct,\n max_len=script_args.cosine_max_len,\n ),\n \"repetition_penalty\": get_repetition_penalty_reward(\n ngram_size=script_args.repetition_n_grams,\n max_penalty=script_args.repetition_max_penalty,\n ),\n \"length\": len_reward,\n \"code\": update_wrapper(\n partial(\n code_reward,\n num_parallel=script_args.parallel_code_exec_per_proc,\n provider_type=script_args.code_provider,\n enforce_same_language=getattr(script_args, \"enforce_same_language\", False),\n ),\n code_reward,\n ),\n \"binary_code\": update_wrapper(\n partial(\n binary_code_reward,\n num_parallel=script_args.parallel_code_exec_per_proc,\n provider_type=script_args.code_provider,\n enforce_same_language=getattr(script_args, \"enforce_same_language\", False),\n ),\n binary_code_reward,\n ),\n \"ioi_code\": update_wrapper(\n partial(\n ioi_code_reward,\n test_batch_size=script_args.code_eval_test_batch_size,\n provider_type=getattr(script_args, \"ioi_provider\", \"piston\"),\n ),\n ioi_code_reward,\n ),\n \"cf_code\": update_wrapper(\n partial(\n cf_code_reward,\n test_batch_size=script_args.code_eval_test_batch_size,\n scoring_mode=script_args.code_eval_scoring_mode,\n ),\n cf_code_reward,\n ),\n \"code_format\": get_code_format_reward(language=script_args.code_language),\n \"tag_count\": tag_count_reward,\n \"soft_overlong_punishment\": get_soft_overlong_punishment(\n max_completion_len=script_args.max_completion_len,\n soft_punish_cache=script_args.soft_punish_cache,\n ),\n }\n reward_funcs = [REWARD_FUNCS_REGISTRY[func] for func in script_args.reward_funcs]\n\n return reward_funcs\n"], ["/open-r1/src/open_r1/utils/competitive_programming/morph_client.py", "import asyncio\nimport json\nimport logging\nimport os\nimport tempfile\nfrom typing import Any, Dict, Optional, Tuple\n\nfrom dotenv import load_dotenv\nfrom open_r1.utils.import_utils import is_morph_available\n\n\n# Replace direct imports with conditional imports\nif is_morph_available():\n from morphcloud.api import Instance, InstanceExecResponse, MorphCloudClient\nelse:\n Instance = None\n InstanceExecResponse = None\n MorphCloudClient = None\n\n\n# Silence verbose logs from dependencies\nlogging.getLogger(\"paramiko\").setLevel(logging.ERROR)\nlogging.getLogger(\"httpx\").setLevel(logging.ERROR)\n\n\nclass MorphCloudError(Exception):\n pass\n\n\nclass MorphCloudExecutionClient:\n def __init__(\n self,\n api_key: Optional[str] = None,\n base_url: Optional[str] = None,\n spans_log_path: Optional[str] = None,\n ):\n \"\"\"\n Initialize the MorphCloud execution client.\n\n Args:\n api_key: Optional API key for MorphCloud. If not provided, will use MORPH_API_KEY env var.\n base_url: Optional base URL for MorphCloud API. If not provided, will use default.\n spans_log_path: Path to log API call spans to. Defaults to 'logs/morph_api_spans.jsonl'.\n \"\"\"\n\n self.client = MorphCloudClient(api_key=api_key, base_url=base_url)\n self._snapshot_lock = asyncio.Lock()\n\n async def _prepare_instance(self, snapshot_id=None) -> Instance:\n \"\"\"\n Prepare and start a MorphCloud instance.\n\n Args:\n snapshot_id: Optional snapshot ID to use. If None, will get or create base snapshot.\n\n Returns:\n Instance: The ready-to-use MorphCloud instance\n\n Raises:\n TimeoutError: If instance fails to start or become ready\n \"\"\"\n\n if not snapshot_id:\n snapshot = await self._get_or_create_base_snapshot()\n snapshot_id = snapshot.id\n\n try:\n instance = await self.client.instances.astart(\n snapshot_id, ttl_seconds=600\n ) # Auto-terminate after 10 minutes\n await instance.await_until_ready(timeout=300)\n return instance\n except asyncio.TimeoutError as e:\n print(f\"Timeout while preparing instance: {str(e)}\")\n if instance:\n try:\n await instance.astop()\n except Exception:\n pass\n raise\n\n async def _prepare_files(self, data: Dict[str, Any], temp_dir: str) -> Tuple[str, Dict[str, Any], Dict[str, str]]:\n \"\"\"\n Process files, determine problem ID, and prepare configuration.\n\n Args:\n data: Dictionary containing file information\n temp_dir: Local temporary directory for file operations\n\n Returns:\n tuple: (problem_id, grader_config, local_files)\n\n Raises:\n ValueError: If problem ID cannot be determined\n \"\"\"\n # Extract problem ID\n problem_id = None\n graders_files = []\n for file in data[\"files\"]:\n if file[\"name\"].startswith(\"graders/\") and file[\"name\"].endswith(\".cpp\"):\n potential_id = os.path.basename(file[\"name\"]).split(\".\")[0]\n if potential_id not in [\"grader\", \"manager\", \"stub\"]:\n problem_id = potential_id\n\n if file[\"name\"].startswith(\"graders/\"):\n graders_files.append(file)\n\n if not problem_id:\n raise ValueError(\"Could not determine problem ID from files\")\n\n grader_config = {\n \"task_type\": \"Batch\",\n \"code\": problem_id,\n \"time_limit\": data[\"run_timeout\"] / 1000,\n \"memory_limit\": data[\"run_memory_limit\"] * 1024 * 1024,\n }\n\n for file in graders_files:\n if \"manager.cpp\" in file[\"name\"]:\n grader_config[\"task_type\"] = \"Communication\"\n grader_config[\"task_type_parameters_Communication_num_processes\"] = 1\n grader_config[\"task_type_parameters_Communication_user_io\"] = \"std_io\"\n break\n\n config_path = os.path.join(temp_dir, \"grader_config.json\")\n with open(config_path, \"w\") as f:\n json.dump(grader_config, f)\n\n local_files = {\"grader_config.json\": config_path}\n\n for file in data[\"files\"]:\n local_path = os.path.join(temp_dir, os.path.basename(file[\"name\"]))\n with open(local_path, \"w\") as f:\n f.write(file[\"content\"])\n local_files[file[\"name\"]] = local_path\n\n return problem_id, grader_config, local_files\n\n async def _upload_files(self, instance: Instance, local_files: Dict[str, str]) -> bool:\n \"\"\"\n Upload all necessary files to the instance.\n\n Args:\n instance: The MorphCloud instance\n local_files: Dictionary mapping remote paths to local file paths\n\n Returns:\n bool: True if all uploads were successful\n\n Raises:\n TimeoutError: If uploads time out\n \"\"\"\n for remote_name, local_path in local_files.items():\n target_path = f\"/workspace/{remote_name}\"\n dir_path = os.path.dirname(target_path)\n\n if dir_path != \"/workspace\":\n await instance.aexec(f\"mkdir -p {dir_path}\")\n\n await instance.aupload(local_path, target_path)\n\n await instance.aupload(local_files[\"grader_config.json\"], \"/workspace/graders/grader_config.json\")\n\n return True\n\n async def _compile_code(self, instance: Instance) -> InstanceExecResponse:\n \"\"\"\n Compile the code on the instance.\n\n Args:\n instance: The MorphCloud instance\n\n Returns:\n InstanceExecResponse: Result of compilation\n\n Raises:\n RuntimeError: If compilation fails\n \"\"\"\n compile_result = await instance.aexec(\"cd /workspace && ./compile\")\n\n if compile_result.exit_code != 0:\n raise RuntimeError(f\"Compilation error exit code {compile_result.exit_code}\\n{compile_result.stderr}\")\n\n return compile_result\n\n async def _run_tests(self, instance: Instance, data: Dict[str, Any]) -> Tuple[str, str]:\n \"\"\"\n Run tests and evaluate results.\n\n Args:\n instance: The MorphCloud instance\n data: Dictionary containing runtime parameters\n\n Returns:\n tuple: (score, feedback)\n\n Raises:\n TimeoutError: If test execution times out\n \"\"\"\n hard_timeout = data[\"run_timeout\"] / 1000 + 3\n run_command = f\"cd /workspace && timeout {hard_timeout}s ./run\"\n\n run_result = await instance.aexec(run_command)\n\n if run_result.exit_code == 124 or run_result.exit_code == 137 or run_result.exit_code == 143:\n return \"0\", \"Time limit exceeded\"\n\n if run_result.exit_code != 0 and \"Memory limit exceeded\" in run_result.stderr:\n return \"0\", \"Memory limit exceeded\"\n\n if run_result.stdout:\n return run_result.stdout.strip(), run_result.stderr.strip()\n\n if run_result.exit_code != 0:\n return (\n \"0\",\n f\"Runtime error with exit code {run_result.exit_code}\\n{run_result.stderr}\",\n )\n\n return \"0\", \"Unknown error\"\n\n async def _execute_with_instance(self, instance: Instance, data: Dict[str, Any], temp_dir: str) -> Tuple[str, str]:\n \"\"\"Execute code using a prepared instance.\n\n Args:\n instance: Ready MorphCloud instance\n data: Execution data\n temp_dir: Temporary directory for file operations\n\n Returns:\n Tuple of (score, feedback)\n\n Raises:\n Exception: Passes through exceptions for retry handling\n \"\"\"\n await instance.await_until_ready(timeout=300)\n\n problem_id, grader_config, local_files = await self._prepare_files(data, temp_dir)\n\n await self._upload_files(instance, local_files)\n\n try:\n await self._compile_code(instance)\n except RuntimeError as e:\n return \"0\", str(e)\n\n score, feedback = await self._run_tests(instance, data)\n return score, feedback\n\n async def _execute(self, data: Dict[str, Any]) -> Tuple[str, str]:\n \"\"\"\n Internal implementation of execute with no retry logic.\n\n Args:\n data: Dictionary containing execution data\n\n Returns:\n Tuple of (score, feedback)\n\n Raises:\n Exception: If execution fails\n \"\"\"\n instance = None\n\n # Set timeouts to ensure we don't block indefinitely\n # INSTANCE_TIMEOUT = 300 # 5 minutes for instance operations\n TOTAL_EXECUTION_TIMEOUT = 600 # 10 minutes total execution time\n\n with tempfile.TemporaryDirectory(prefix=\"morph_exec_\") as temp_dir:\n snapshot = await self._get_or_create_base_snapshot()\n instance = await self.client.instances.astart(\n snapshot.id, ttl_seconds=600\n ) # Auto-terminate after 10 minutes\n\n async with instance:\n # Use asyncio.wait_for to add overall timeout to the execution process\n return await asyncio.wait_for(\n self._execute_with_instance(instance, data, temp_dir),\n timeout=TOTAL_EXECUTION_TIMEOUT,\n )\n\n async def execute(self, data: Dict[str, Any]) -> Tuple[str, str]:\n \"\"\"\n Execute code on MorphCloud based on the provided data with enhanced debugging and recovery.\n\n Orchestrates the following steps with proper error handling and retries:\n 1. Prepare an instance (with retry)\n 2. Set up workspace (with retry)\n 3. Prepare and upload files (with retry)\n 4. Compile code (with retry)\n 5. Run tests (with retry)\n\n Args:\n data: Dictionary containing:\n - files: List of file objects with name and content fields\n - run_timeout: Timeout in milliseconds\n - run_memory_limit: Memory limit in MB\n\n Returns:\n Tuple of (score, feedback) where:\n - score is a string representation of a float between 0.0 and 1.0\n - feedback is a string with execution details\n \"\"\"\n # TODO: would be faster to pass info about the subtask as well to create a snapshot per subtask\n # would cache the uploads of all files other than the submission: input.txt, correct_output.txt, grader files\n # rather than reusing the snapshot that only has the compile/run scripts on it\n # currently, run_submission -> client.execute(data) does not easily pass subtask info\n\n # Retry configuration\n max_retries = 4\n base_delay = 1.0\n\n # Try execution with retries and exponential backoff\n for attempt in range(max_retries + 1):\n try:\n return await self._execute(data)\n\n except asyncio.TimeoutError:\n if attempt < max_retries:\n print(f\"Execution timed out, retrying ({attempt + 1}/{max_retries})\")\n else:\n return \"0\", \"Execution timed out after multiple retries\"\n\n except Exception as e:\n # Calculate exponential backoff\n if attempt < max_retries:\n retry_delay = min(base_delay * (2**attempt), 30) # Exponential backoff, capped at 30 seconds\n\n print(\n f\"Execution failed with {type(e).__name__}: {str(e)}, retrying in {retry_delay:.2f}s ({attempt + 1}/{max_retries})\"\n )\n await asyncio.sleep(retry_delay)\n else:\n print(f\"Execution failed after {max_retries} retries: {type(e).__name__}: {str(e)}\")\n return \"0\", f\"Execution failed after multiple retries: {str(e)}\"\n\n async def _get_or_create_base_snapshot(self):\n \"\"\"Get or create a snapshot with the necessary dependencies and scripts for evaluation.\"\"\"\n\n async with self._snapshot_lock:\n base_snapshots = await self.client.snapshots.alist(digest=\"ioi-evaluation-morph\")\n\n if not base_snapshots:\n print(\"Creating base snapshot with build-essential cmake and g++\")\n\n # Create base snapshot with minimal specs\n base_snapshot = await self.client.snapshots.acreate(\n vcpus=2,\n memory=4096,\n disk_size=10240,\n metadata={\"purpose\": \"ioi_evaluation\"},\n )\n\n # Start a temporary instance from the base snapshot\n temp_instance = await self.client.instances.astart(\n base_snapshot.id, ttl_seconds=900\n ) # Auto-terminate after 15 minutes\n\n try:\n # Wait for the instance to be ready\n await temp_instance.await_until_ready(timeout=300)\n\n # Get script contents\n compile_script = await self._get_compile_script()\n run_script = await self._get_run_script()\n\n # Use temporary directory to store scripts\n with tempfile.TemporaryDirectory(prefix=\"morph_setup_\") as temp_dir:\n # Create paths for script files\n compile_path = os.path.join(temp_dir, \"compile.sh\")\n run_path = os.path.join(temp_dir, \"run.sh\")\n\n # Write scripts to temp files\n with open(compile_path, \"w\") as f:\n f.write(compile_script)\n\n with open(run_path, \"w\") as f:\n f.write(run_script)\n\n async with temp_instance:\n # Install dependencies\n await temp_instance.aexec(\"apt-get update && apt-get install -y build-essential cmake g++\")\n\n # Create workspace directory\n await temp_instance.aexec(\n \"mkdir -p /workspace && mkdir -p /workspace/graders && chmod 777 /workspace\"\n )\n\n # Upload scripts to instance\n await temp_instance.aupload(compile_path, \"/workspace/compile\")\n await temp_instance.aupload(run_path, \"/workspace/run\")\n\n # Make scripts executable\n await temp_instance.aexec(\"chmod +x /workspace/compile /workspace/run\")\n\n # Create snapshot from the prepared instance\n final_snapshot = await temp_instance.asnapshot(digest=\"ioi-evaluation-morph\")\n\n except Exception as e:\n # Ensure instance is stopped if anything fails\n await temp_instance.astop()\n raise e\n else:\n final_snapshot = base_snapshots[0]\n\n return final_snapshot\n\n async def _get_compile_script(self):\n \"\"\"Get the compile script content.\"\"\"\n return \"\"\"#!/bin/bash\n\nmanager_files=() # Array to store manager filenames\ncurrent_dir=\"$(pwd)\"\n\n# Checker compilation path\nchecker_dir=\"$current_dir/checker\"\nchecker_src=\"$checker_dir/checker.cpp\"\n\nif [ -e \"$checker_src\" ]; then\n echo \"Compiling checker\"\n checker_exe=\"$checker_dir/checker\"\n g++ -x c++ -std=gnu++17 -O2 -o \"$checker_exe\" \"$checker_src\"\n chmod +x \"$checker_exe\"\n if [ $? -ne 0 ]; then\n echo \"Could not compile checker\" >&2\n exit 1\n fi\n echo \"Compiled checker\"\nelse\n echo \"No checker found at $checker_src\"\nfi\n\n# Graders path\ngraders_dir=\"$current_dir/graders\"\nif [ ! -e \"$graders_dir\" ]; then\n echo \"Grader folder was not found\" >&2\n exit 1\nfi\n\n# Find and compile manager if it exists\nmanager_src=\"$graders_dir/manager.cpp\"\nif [ -e \"$manager_src\" ]; then\n echo \"Compiling manager\"\n manager_exe=\"$graders_dir/manager\"\n g++ -x c++ -std=gnu++17 -O2 -o \"$manager_exe\" \"$manager_src\"\n chmod +x \"$manager_exe\"\n if [ $? -ne 0 ]; then\n echo \"Could not compile manager\" >&2\n exit 1\n fi\n manager_files+=(\"manager\")\nfi\n\n# Process other graders\ngraders_list=($(ls \"$graders_dir\" | grep -v 'manager.cpp'))\nfor grader_name in \"${graders_list[@]}\"; do\n manager_files+=(\"$grader_name\")\ndone\n\n# Extract problem name and compile necessary files\nproblem_name='?'\nfor file in \"${manager_files[@]}\"; do\n if [[ \"$file\" == *.h && \"$file\" != \"testlib.h\" ]]; then\n problem_name=\"${file%.h}\"\n echo \"Problem name: $problem_name\"\n break\n fi\ndone\n\nfiles_to_compile=(\"graders/$problem_name.cpp\")\n[ -e graders/grader.cpp ] && files_to_compile+=(\"graders/grader.cpp\")\n[ -e graders/stub.cpp ] && files_to_compile+=(\"graders/stub.cpp\")\n\ng++ -DEVAL -std=gnu++17 -O2 -pipe -s -o graders/\"$problem_name\" \"${files_to_compile[@]}\"\nif [ $? -ne 0 ]; then\n echo \"Failed to compile $problem_name\" >&2\n exit 1\nfi\nchmod +x graders/\"$problem_name\"\necho \"Compiled $problem_name from ${files_to_compile[@]} successfully\"\n\necho \"Manager files: ${manager_files[@]}\"\n\"\"\"\n\n async def _get_run_script(self):\n \"\"\"Get the run script content.\"\"\"\n return \"\"\"#!/usr/bin/env bash\n# disable stack limit so you don't get RE with recursion\nulimit -s unlimited\n# some problems have 10MB+ input/output files in their test cases and you might get RE. uncomment if needed\n# ulimit -f 2097152\n\n# Check if grader_config.json exists\nif [ ! -f \"graders/grader_config.json\" ]; then\n echo \"Error: graders/grader_config.json not found\" >&2\n echo \"Current directory contents:\" >&2\n find . -type f -o -type d | sed -e 's/[^-][^\\/]*\\// |/g' -e 's/|\\([^ ]\\)/|-\\1/' >&2\n exit 1\nfi\n\n# Read task type, code, and time limit from grader_config.json using grep and sed\nTASK_TYPE=$(grep -o '\"task_type\":[^,}]*' graders/grader_config.json | sed 's/\"task_type\":\\\\s*\"\\\\([^\"]*\\\\)\"/\\\\1/')\nTASK_NAME=$(grep -o '\"code\":[^,}]*' graders/grader_config.json | sed 's/\"code\":\\\\s*\"\\\\([^\"]*\\\\)\"/\\\\1/')\nTIME_LIMIT=$(grep -o '\"time_limit\":[^,}]*' graders/grader_config.json | sed 's/\"time_limit\":\\\\s*\\\\([^,}]*\\\\)/\\\\1/')\nMEMORY_LIMIT=$(grep -o '\"memory_limit\":[^,}]*' graders/grader_config.json | sed 's/\"memory_limit\":\\\\s*\\\\([^,}]*\\\\)/\\\\1/')\nTASK_EXECUTABLE=\"graders/$TASK_NAME\"\n\n# Set memory limit in KB (convert from bytes)\nMEMORY_LIMIT_KB=0\nif [ -n \"$MEMORY_LIMIT\" ]; then\n MEMORY_LIMIT_KB=$(($MEMORY_LIMIT / 1024))\n # Set the memory limit for the entire script and all child processes\n ulimit -v $MEMORY_LIMIT_KB\nfi\n\n# \"Securely\" handle the correct output file\nCORRECT_OUTPUT=\"\"\nif [ -f \"correct_output.txt\" ]; then\n # Read the content and immediately remove the file\n CORRECT_OUTPUT=$(cat correct_output.txt)\n rm -f correct_output.txt\nfi\n\n# Create a temporary file for solution output\nSOLUTION_OUTPUT=$(mktemp)\n\n# Global variables for process tracking\ndeclare -a ALL_PIDS\ndeclare -a FIFO_DIRS\n\n# Define cleanup function - simplified assuming timeout exists\nfunction cleanup {\n # Kill all tracked processes silently\n exec 2>/dev/null\n for pid in \"${ALL_PIDS[@]:-}\"; do\n kill -9 \"$pid\" 2>/dev/null || true\n done\n\n # Clean up FIFO directories\n for dir in \"${FIFO_DIRS[@]:-}\"; do\n [ -d \"$dir\" ] && rm -rf \"$dir\"\n done\n\n # Clean up temporary files\n rm -f \"$SOLUTION_OUTPUT\" || true\n exec 2>&2\n}\n\n# Set up signal handling\ntrap cleanup EXIT INT TERM\n\n# Function to handle exit codes consistently across task types\nfunction handle_exit_code {\n local exit_code=$1\n\n # Check for known timeout exit codes:\n # - 124: standard timeout exit code\n # - 137: SIGKILL (128+9), used for hard timeouts\n # - 143: SIGTERM (128+15), can also be used for timeouts\n if [ $exit_code -eq 124 ] || [ $exit_code -eq 137 ] || [ $exit_code -eq 143 ]; then\n echo \"0\"\n echo \"Time limit exceeded (${TIME_LIMIT}s)\" >&2\n return 124\n # All other non-zero exit codes should be treated as runtime errors\n elif [ $exit_code -ne 0 ]; then\n echo \"0\"\n echo \"Runtime error with exit code $exit_code\" >&2\n return $exit_code\n fi\n\n # Success case - return 0\n return 0\n}\n\n# Function to run a command with timeout (simplified assuming timeout exists)\nfunction run_with_timeout {\n local soft_limit=$1; shift\n local command_to_run=\"$@\"\n\n timeout --preserve-status \"$soft_limit\" \"$@\"\n return $?\n}\n\ncase \"$TASK_TYPE\" in\n \"Batch\")\n # Simple batch execution with timeout\n run_with_timeout \"$TIME_LIMIT\" ./$TASK_EXECUTABLE < input.txt > \"$SOLUTION_OUTPUT\"\n exit_code=$?\n\n # Handle non-zero exit codes\n handle_exit_code $exit_code\n if [ $? -ne 0 ]; then\n exit $?\n fi\n\n # Check the output if we have a correct output\n if [ -n \"$CORRECT_OUTPUT\" ]; then\n # Restore the correct output file\n echo \"$CORRECT_OUTPUT\" > correct_output.txt\n\n # Check if there's a custom checker\n if [ -f \"checker/checker\" ]; then\n # Let the checker handle everything\n ./checker/checker input.txt correct_output.txt \"$SOLUTION_OUTPUT\"\n exit $?\n else\n # Simple diff-based checking\n if diff -bq <(echo \"$CORRECT_OUTPUT\") \"$SOLUTION_OUTPUT\" >/dev/null; then\n echo \"1\"\n echo \"Output is correct (diff)\" >&2\n else\n echo \"0\"\n echo \"Output isn't correct (diff)\" >&2\n exit 0\n fi\n fi\n else\n # If no correct output was provided, just output the solution's output\n cat \"$SOLUTION_OUTPUT\"\n fi\n ;;\n\n \"Communication\")\n # Read Communication-specific parameters\n NUM_PROCESSES=$(grep -o '\"task_type_parameters_Communication_num_processes\":[^,}]*' graders/grader_config.json | sed 's/.*:\\\\s*\\\\([0-9]*\\\\)/\\\\1/' || true)\n if [ -z \"$NUM_PROCESSES\" ]; then\n NUM_PROCESSES=1\n fi\n USER_IO=$(grep -o '\"task_type_parameters_Communication_user_io\":[^,}]*' graders/grader_config.json | sed 's/.*:\\\\s*\"\\\\([^\"]*\\\\)\"/\\\\1/' || echo \"std_io\")\n\n # Read custom manager arguments if they exist\n MANAGER_CUSTOM_ARGS=\"\"\n if grep -q '\"task_type_parameters_Communication_manager_args\"' graders/grader_config.json; then\n MANAGER_CUSTOM_ARGS=$(grep -o '\"task_type_parameters_Communication_manager_args\":[^,}]*' graders/grader_config.json | sed 's/.*:\\\\s*\"\\\\([^\"]*\\\\)\"/\\\\1/')\n fi\n\n # Create temporary directories for FIFOs\n for i in $(seq 0 $((NUM_PROCESSES-1))); do\n FIFO_DIRS[$i]=$(mktemp -d)\n\n # Create FIFOs for this process\n mkfifo \"${FIFO_DIRS[$i]}/u${i}_to_m\"\n mkfifo \"${FIFO_DIRS[$i]}/m_to_u${i}\"\n chmod 755 \"${FIFO_DIRS[$i]}\"\n chmod 666 \"${FIFO_DIRS[$i]}/u${i}_to_m\" \"${FIFO_DIRS[$i]}/m_to_u${i}\"\n done\n\n # Prepare manager arguments\n MANAGER_ARGS=\"\"\n for i in $(seq 0 $((NUM_PROCESSES-1))); do\n MANAGER_ARGS=\"$MANAGER_ARGS ${FIFO_DIRS[$i]}/u${i}_to_m ${FIFO_DIRS[$i]}/m_to_u${i}\"\n done\n\n # Add custom manager arguments if specified\n if [ -n \"$MANAGER_CUSTOM_ARGS\" ]; then\n MANAGER_ARGS=\"$MANAGER_ARGS $MANAGER_CUSTOM_ARGS\"\n fi\n\n # Start all user processes first\n for i in $(seq 0 $((NUM_PROCESSES-1))); do\n if [ \"$USER_IO\" = \"fifo_io\" ]; then\n # Pass FIFOs as arguments\n ARGS=\"${FIFO_DIRS[$i]}/m_to_u${i} ${FIFO_DIRS[$i]}/u${i}_to_m\"\n if [ \"$NUM_PROCESSES\" -ne 1 ]; then\n ARGS=\"$ARGS $i\"\n fi\n ./$TASK_EXECUTABLE $ARGS &\n ALL_PIDS+=($!)\n else\n # Use stdin/stdout redirection\n if [ \"$NUM_PROCESSES\" -ne 1 ]; then\n ./$TASK_EXECUTABLE \"$i\" < \"${FIFO_DIRS[$i]}/m_to_u${i}\" > \"${FIFO_DIRS[$i]}/u${i}_to_m\" 2>/dev/null &\n ALL_PIDS+=($!)\n else\n ./$TASK_EXECUTABLE < \"${FIFO_DIRS[$i]}/m_to_u${i}\" > \"${FIFO_DIRS[$i]}/u${i}_to_m\" 2>/dev/null &\n ALL_PIDS+=($!)\n fi\n fi\n done\n\n # Run the manager with timeout using direct pipe from input.txt\n run_with_timeout \"$TIME_LIMIT\" ./graders/manager $MANAGER_ARGS < input.txt > \"$SOLUTION_OUTPUT\"\n\n exit_code=$?\n\n # Handle non-zero exit codes\n handle_exit_code $exit_code\n if [ $? -ne 0 ]; then\n exit $?\n fi\n\n # Check the output if we have a correct output AND there's a checker (otherwise we assume the manager handles everything)\n if [ -n \"$CORRECT_OUTPUT\" ] && [ -f \"checker/checker\" ]; then\n # Restore the correct output file\n echo \"$CORRECT_OUTPUT\" > correct_output.txt\n\n # Let the checker handle it\n ./checker/checker input.txt correct_output.txt \"$SOLUTION_OUTPUT\"\n exit $?\n else\n # we assume the manager handles it\n cat \"$SOLUTION_OUTPUT\"\n fi\n ;;\n\n *)\n echo \"0\"\n echo \"Unsupported task type \\\"$TASK_TYPE\\\"\" >&2\n exit 1\n ;;\nesac\n\"\"\"\n\n\ndef get_morph_client_from_env(session=None) -> MorphCloudExecutionClient:\n \"\"\"\n Creates a MorphCloudExecutionClient instance using environment variables.\n\n Environment variables:\n MORPH_API_KEY: API key for MorphCloud\n\n Args:\n session: Optional aiohttp.ClientSession to use for HTTP requests\n\n Returns:\n MorphCloudExecutionClient: A configured MorphCloud execution client\n \"\"\"\n if not is_morph_available():\n raise ImportError(\n \"MorphCloud is not available and required for this function. Please install MorphCloud with \"\n \"`pip install morphcloud` and add an API key to a `.env` file.\"\n )\n\n load_dotenv()\n api_key = os.environ.get(\"MORPH_API_KEY\")\n if not api_key:\n raise ValueError(\"MORPH_API_KEY environment variable is required\")\n\n return MorphCloudExecutionClient(api_key=api_key)\n\n\n# noqa: W293\n"], ["/open-r1/scripts/morph_router.py", "# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport asyncio\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel, ConfigDict\nfrom typing import Optional, List\nfrom fastapi import FastAPI, Request\nimport uvicorn\nfrom dotenv import load_dotenv\nimport os\n\nload_dotenv()\n\nclass BatchRequest(BaseModel):\n \"\"\"\n BatchRequest is a data model representing a batch processing request.\n\n Attributes:\n scripts (list[str]): A list of script names or paths to be executed.\n languages (List[str]): The programming languages for each script in the list.\n timeout (int): The maximum allowed execution time for each script in seconds.\n request_timeout (int): The maximum allowed time for the entire batch request in seconds.\n \"\"\"\n scripts: List[str]\n languages: List[str]\n timeout: int\n request_timeout: int\n\nclass ScriptResult(BaseModel):\n \"\"\"\n ScriptResult is a Pydantic model that represents the result of a script execution.\n Attributes:\n text (Optional[str]): The output text from the script execution.\n exception_str (Optional[str]): An optional string that captures the exception \n message or details if an error occurred during the script's execution.\n model_config (ConfigDict): A configuration dictionary that allows arbitrary \n types to be used within the Pydantic model.\n \"\"\"\n text: Optional[str]\n exception_str: Optional[str]\n \n \n model_config = ConfigDict(arbitrary_types_allowed=True)\n \ndef create_app(args):\n \"\"\"\n Creates and configures a FastAPI application instance for the MorphCloud router.\n \n Args:\n args: An object containing configuration parameters for the application.\n - max_num_sandboxes (int): The maximum number of concurrent sandboxes allowed.\n - api_key (str): The MorphCloud API key to use.\n \n Returns:\n FastAPI: A configured FastAPI application instance.\n \"\"\"\n app = FastAPI()\n \n from morphcloud.api import MorphCloudClient\n from morphcloud.sandbox import Sandbox\n \n app.state.client = MorphCloudClient(api_key=args.api_key)\n app.state.Sandbox = Sandbox\n\n app.state.sandbox_semaphore = asyncio.Semaphore(args.max_num_sandboxes)\n\n @app.get(\"/health\")\n async def health():\n return {\"status\": \"ok\"}\n\n @app.post(\"/execute_batch\")\n async def execute_batch(batch: BatchRequest, request: Request):\n semaphore = request.app.state.sandbox_semaphore\n client = request.app.state.client\n Sandbox = request.app.state.Sandbox\n \n languages = batch.languages\n timeout = batch.timeout\n request_timeout = batch.request_timeout\n asyncio_timeout = batch.timeout + 1\n \n async def run_script(script: str, language: str) -> ScriptResult:\n sandbox = None\n sandbox_id = \"unknown\"\n\n async with semaphore:\n try:\n sandbox = await asyncio.to_thread(\n Sandbox.new,\n client=client,\n ttl_seconds=timeout\n )\n \n sandbox_id = getattr(sandbox, 'id', None) or getattr(sandbox._instance, 'id', 'unknown')\n \n execution = await asyncio.wait_for(\n asyncio.to_thread(\n sandbox.run_code,\n script,\n language=language,\n timeout=timeout * 1000 \n ),\n timeout=asyncio_timeout,\n )\n \n if hasattr(execution, 'text') and execution.text:\n return ScriptResult(text=execution.text, exception_str=None)\n elif hasattr(execution, 'stdout') and execution.stdout:\n return ScriptResult(text=execution.stdout, exception_str=None)\n else:\n return ScriptResult(text=\"\", exception_str=\"No output from execution\")\n\n except Exception as e:\n return ScriptResult(text=None, exception_str=str(e))\n \n finally:\n if sandbox:\n try:\n await asyncio.to_thread(sandbox.close)\n await asyncio.to_thread(sandbox.shutdown)\n except Exception:\n pass\n\n tasks = [run_script(script, lang) for script, lang in zip(batch.scripts, batch.languages)]\n return await asyncio.gather(*tasks)\n\n return app\n\ndef parse_args():\n \"\"\"\n Parse command-line arguments for the morph_router script.\n\n Arguments:\n --host (str): The hostname or IP address to bind the server to. Defaults to \"0.0.0.0\".\n --port (int): The port number on which the server will listen. Defaults to 8001.\n --max_num_sandboxes (int): The maximum number of sandboxes that can be created simultaneously. Defaults to 20.\n --api_key (str): The MorphCloud API key. If not provided, it will be read from the MORPH_API_KEY environment variable.\n\n Returns:\n argparse.Namespace: Parsed command-line arguments as an object.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--host\", default=\"0.0.0.0\")\n parser.add_argument(\"--port\", type=int, default=8001)\n parser.add_argument(\"--max_num_sandboxes\", type=int, default=20)\n parser.add_argument(\"--api_key\", default=os.getenv(\"MORPH_API_KEY\"))\n args = parser.parse_args()\n \n if not args.api_key:\n raise ValueError(\"MorphCloud API key not provided. Please set MORPH_API_KEY environment variable or use --api_key.\")\n \n return args\n\nif __name__ == \"__main__\":\n args = parse_args()\n app = create_app(args)\n \n print(f\"Starting MorphCloud Router on {args.host}:{args.port}\")\n uvicorn.run(app, host=args.host, port=args.port)"], ["/open-r1/src/open_r1/utils/hub.py", "#!/usr/bin/env python\n# coding=utf-8\n# Copyright 2025 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport re\nfrom concurrent.futures import Future\n\nfrom transformers import AutoConfig\n\nfrom huggingface_hub import (\n create_branch,\n create_repo,\n get_safetensors_metadata,\n list_repo_commits,\n list_repo_files,\n list_repo_refs,\n repo_exists,\n upload_folder,\n)\nfrom trl import GRPOConfig, SFTConfig\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef push_to_hub_revision(training_args: SFTConfig | GRPOConfig, extra_ignore_patterns=[]) -> Future:\n \"\"\"Pushes the model to branch on a Hub repo.\"\"\"\n\n # Create a repo if it doesn't exist yet\n repo_url = create_repo(repo_id=training_args.hub_model_id, private=True, exist_ok=True)\n # Get initial commit to branch from\n initial_commit = list_repo_commits(training_args.hub_model_id)[-1]\n # Now create the branch we'll be pushing to\n create_branch(\n repo_id=training_args.hub_model_id,\n branch=training_args.hub_model_revision,\n revision=initial_commit.commit_id,\n exist_ok=True,\n )\n logger.info(f\"Created target repo at {repo_url}\")\n logger.info(f\"Pushing to the Hub revision {training_args.hub_model_revision}...\")\n ignore_patterns = [\"checkpoint-*\", \"*.pth\"]\n ignore_patterns.extend(extra_ignore_patterns)\n future = upload_folder(\n repo_id=training_args.hub_model_id,\n folder_path=training_args.output_dir,\n revision=training_args.hub_model_revision,\n commit_message=f\"Add {training_args.hub_model_revision} checkpoint\",\n ignore_patterns=ignore_patterns,\n run_as_future=True,\n )\n logger.info(f\"Pushed to {repo_url} revision {training_args.hub_model_revision} successfully!\")\n\n return future\n\n\ndef check_hub_revision_exists(training_args: SFTConfig | GRPOConfig):\n \"\"\"Checks if a given Hub revision exists.\"\"\"\n if repo_exists(training_args.hub_model_id):\n if training_args.push_to_hub_revision is True:\n # First check if the revision exists\n revisions = [rev.name for rev in list_repo_refs(training_args.hub_model_id).branches]\n # If the revision exists, we next check it has a README file\n if training_args.hub_model_revision in revisions:\n repo_files = list_repo_files(\n repo_id=training_args.hub_model_id,\n revision=training_args.hub_model_revision,\n )\n if \"README.md\" in repo_files and training_args.overwrite_hub_revision is False:\n raise ValueError(\n f\"Revision {training_args.hub_model_revision} already exists. \"\n \"Use --overwrite_hub_revision to overwrite it.\"\n )\n\n\ndef get_param_count_from_repo_id(repo_id: str) -> int:\n \"\"\"Function to get model param counts from safetensors metadata or find patterns like 42m, 1.5b, 0.5m or products like 8x7b in a repo ID.\"\"\"\n try:\n metadata = get_safetensors_metadata(repo_id)\n return list(metadata.parameter_count.values())[0]\n except Exception:\n # Pattern to match products (like 8x7b) and single values (like 42m)\n pattern = r\"((\\d+(\\.\\d+)?)(x(\\d+(\\.\\d+)?))?)([bm])\"\n matches = re.findall(pattern, repo_id.lower())\n\n param_counts = []\n for full_match, number1, _, _, number2, _, unit in matches:\n if number2: # If there's a second number, it's a product\n number = float(number1) * float(number2)\n else: # Otherwise, it's a single value\n number = float(number1)\n\n if unit == \"b\":\n number *= 1_000_000_000 # Convert to billion\n elif unit == \"m\":\n number *= 1_000_000 # Convert to million\n\n param_counts.append(number)\n\n if len(param_counts) > 0:\n # Return the largest number\n return int(max(param_counts))\n else:\n # Return -1 if no match found\n return -1\n\n\ndef get_gpu_count_for_vllm(model_name: str, revision: str = \"main\", num_gpus: int = 8) -> int:\n \"\"\"vLLM enforces a constraint that the number of attention heads must be divisible by the number of GPUs and 64 must be divisible by the number of GPUs.\n This function calculates the number of GPUs to use for decoding based on the number of attention heads in the model.\n \"\"\"\n config = AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=True)\n # Get number of attention heads\n num_heads = config.num_attention_heads\n # Reduce num_gpus so that num_heads is divisible by num_gpus and 64 is divisible by num_gpus\n while num_heads % num_gpus != 0 or 64 % num_gpus != 0:\n logger.info(f\"Reducing num_gpus from {num_gpus} to {num_gpus - 1} to make num_heads divisible by num_gpus\")\n num_gpus -= 1\n return num_gpus\n"], ["/open-r1/scripts/upload_details.py", "# coding=utf-8\n# Copyright 2025 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nPush the details from a LightEval run to the Hub.\n\nUsage:\n\npython src/open_r1/utils/upload_details.py \\\n --data_files {path_to_parquet_file} \\\n --hub_repo_id {hub_repo_id} \\\n --config_name {config_name}\n\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import List\n\nfrom datasets import load_dataset\nfrom transformers import HfArgumentParser\n\n\n@dataclass\nclass ScriptArguments:\n data_files: List[str] = field(default_factory=list)\n hub_repo_id: str = None\n config_name: str = None\n\n\ndef main():\n parser = HfArgumentParser(ScriptArguments)\n args = parser.parse_args_into_dataclasses()[0]\n\n if all(file.endswith(\".json\") for file in args.data_files):\n ds = load_dataset(\"json\", data_files=args.data_files)\n elif all(file.endswith(\".jsonl\") for file in args.data_files):\n ds = load_dataset(\"json\", data_files=args.data_files)\n else:\n ds = load_dataset(\"parquet\", data_files=args.data_files)\n url = ds.push_to_hub(args.hub_repo_id, config_name=args.config_name, private=True)\n print(f\"Dataset available at: {url}\")\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/open-r1/scripts/e2b_router.py", "# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport asyncio\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel, ConfigDict\nfrom typing import Optional\nfrom fastapi import FastAPI, Request\nimport argparse\nimport asyncio\nfrom fastapi import FastAPI\nimport uvicorn\nfrom e2b_code_interpreter.models import Execution\nfrom dotenv import load_dotenv\nfrom e2b_code_interpreter import AsyncSandbox\n\nload_dotenv()\n\nclass BatchRequest(BaseModel):\n \"\"\"\n BatchRequest is a data model representing a batch processing request.\n\n Attributes:\n scripts (list[str]): A list of script names or paths to be executed.\n languages (list[str]): The programming languages for each script in the list.\n timeout (int): The maximum allowed execution time for each script in seconds.\n request_timeout (int): The maximum allowed time for the entire batch request in seconds.\n \"\"\"\n scripts: list[str]\n languages: list[str]\n timeout: int\n request_timeout: int\n\nclass ScriptResult(BaseModel):\n \"\"\"\n ScriptResult is a Pydantic model that represents the result of a script execution.\n Attributes:\n execution (Optional[Execution]): An optional instance of the `Execution` class \n that contains details about the script's execution, such as status, output, \n or any other relevant metadata.\n exception_str (Optional[str]): An optional string that captures the exception \n message or details if an error occurred during the script's execution.\n model_config (ConfigDict): A configuration dictionary that allows arbitrary \n types to be used within the Pydantic model. This is necessary to support \n custom types like `Execution` within the model.\n \"\"\"\n execution: Optional[Execution]\n exception_str: Optional[str]\n \n # required to allow arbitrary types in pydantic models such as Execution\n model_config = ConfigDict(arbitrary_types_allowed=True)\n \ndef create_app(args):\n \"\"\"\n Creates and configures a FastAPI application instance.\n Args:\n args: An object containing configuration parameters for the application.\n - num_sandboxes (int): The maximum number of concurrent sandboxes allowed.\n Returns:\n FastAPI: A configured FastAPI application instance.\n The application includes the following endpoints:\n 1. GET /health:\n - Returns the health status of the application.\n - Response: {\"status\": \"ok\"}\n 2. POST /execute_batch:\n - Executes a batch of scripts in an isolated sandbox environment.\n - Request Body: BatchRequest object containing:\n - languages (list[str]): The programming languages of the scripts (python or javascript).\n - timeout (int): The maximum execution time for each script.\n - request_timeout (int): The timeout for the request itself.\n - scripts (List[str]): A list of scripts to execute.\n - Response: A list of ScriptResult objects for each script, containing:\n - execution: The result of the script execution.\n - exception_str: Any exception encountered during execution.\n Notes:\n - A semaphore is used to limit the number of concurrent sandboxes.\n - Each script execution is wrapped in a timeout to prevent hanging.\n - Sandboxes are cleaned up after execution, even in case of errors.\n \"\"\"\n app = FastAPI()\n\n # Instantiate semaphore and attach it to app state\n app.state.sandbox_semaphore = asyncio.Semaphore(args.max_num_sandboxes)\n\n @app.get(\"/health\")\n async def health():\n return {\"status\": \"ok\"}\n\n @app.post(\"/execute_batch\")\n async def execute_batch(batch: BatchRequest, request: Request):\n semaphore = request.app.state.sandbox_semaphore\n languages = batch.languages\n timeout = batch.timeout\n request_timeout = batch.request_timeout\n asyncio_timeout = batch.timeout + 1\n \n async def run_script(script: str, language: str) -> ScriptResult:\n\n async with semaphore:\n try:\n sandbox = await AsyncSandbox.create(\n timeout=timeout,\n request_timeout=request_timeout,\n )\n execution = await asyncio.wait_for(\n sandbox.run_code(script, language=language),\n timeout=asyncio_timeout,\n )\n return ScriptResult(execution=execution, exception_str=None)\n\n except Exception as e:\n return ScriptResult(execution=None, exception_str=str(e))\n \n finally:\n try:\n await sandbox.kill()\n except Exception:\n pass\n\n tasks = [run_script(script, lang) for script, lang in zip(batch.scripts, batch.languages)]\n return await asyncio.gather(*tasks)\n\n return app\n\n\ndef parse_args():\n \"\"\"\n Parse command-line arguments for the e2b_router script.\n\n Arguments:\n --host (str): The hostname or IP address to bind the server to. Defaults to \"0.0.0.0\" (binds to all interfaces).\n --port (int): The port number on which the server will listen. Defaults to 8000.\n --max_num_sandboxes (int): The maximum number of sandboxes that can be created or managed simultaneously. Defaults to 20.\n\n Returns:\n argparse.Namespace: Parsed command-line arguments as an object.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--host\", default=\"0.0.0.0\")\n parser.add_argument(\"--port\", type=int, default=8000)\n parser.add_argument(\"--max_num_sandboxes\", type=int, default=20)\n return parser.parse_args()\n\nif __name__ == \"__main__\":\n args = parse_args()\n app = create_app(args)\n\n uvicorn.run(app, host=args.host, port=args.port)"], ["/open-r1/src/open_r1/utils/competitive_programming/ioi_scoring.py", "import asyncio\nfrom dataclasses import asdict, dataclass, field\nfrom typing import Union\n\nfrom .ioi_utils import load_ioi_tests\nfrom .piston_client import PistonClient, PistonError\nfrom .utils import batched\n\n\n@dataclass\nclass TestResult:\n \"\"\"\n Represents the result of a single test case execution.\n\n Attributes:\n test_name: Name of the test case\n score: Score achieved for this test (0.0 to 1.0)\n status: Status code of the test result (e.g., 'AC', 'WA', 'TLE')\n feedback: Detailed feedback message from the judge or an error message\n \"\"\"\n\n test_name: str\n score: float = 0.0\n status: str = \"SKIPPED\"\n feedback: str = None\n\n\n@dataclass\nclass SubtaskResult:\n \"\"\"\n Represents the result of a subtask containing multiple test cases.\n\n Attributes:\n problem: Problem identifier\n subtask: Subtask identifier\n points: Maximum points available for this subtask\n score_precision: Number of decimal places for score rounding\n test_results: List of individual test case results\n \"\"\"\n\n problem: str = None\n subtask: str = None\n\n points: float = 0.0\n score_precision: int = 2\n\n test_results: list[TestResult] = field(default_factory=list)\n\n @property\n def status(self):\n \"\"\"\n Determines the overall status of the subtask based on the worst status among test results.\n Status priorities are ordered from worst to best.\n\n Returns:\n str: The status with the highest priority (lowest value)\n \"\"\"\n status_prios = {\"CE\": -1, \"RE\": 0, \"WA\": 1, \"MLE\": 2, \"TLE\": 3, \"PA\": 4, \"AC\": 5, \"SKIPPED\": 999}\n return min([x.status for x in self.test_results], key=lambda x: status_prios[x])\n\n @property\n def score(self):\n \"\"\"\n Calculates the raw score for the subtask as the minimum score across all test results.\n\n Returns:\n float: The rounded minimum score\n \"\"\"\n return (\n 0\n if not self.test_results\n else round(min([test_result.score for test_result in self.test_results]), self.score_precision)\n )\n\n @property\n def weighted_score(self):\n \"\"\"\n Calculates the weighted score by multiplying the raw score by the available points.\n\n Returns:\n float: The rounded weighted score\n \"\"\"\n return (\n 0\n if not self.test_results\n else round(\n min([test_result.score for test_result in self.test_results]) * self.points, self.score_precision\n )\n )\n\n def to_dict(self):\n \"\"\"\n Converts the SubtaskResult to a dictionary representation.\n\n Returns:\n dict: Dictionary containing all subtask result data\n \"\"\"\n return {\n \"problem\": self.problem,\n \"subtask\": self.subtask,\n \"score\": self.score,\n \"weighted_score\": self.weighted_score,\n \"points\": self.points,\n \"score_precision\": self.score_precision,\n \"status\": self.status,\n \"test_results\": [asdict(test_result) for test_result in self.test_results],\n }\n\n\ndef _extract_single_status(score: float, feedback: str) -> str:\n \"\"\"\n Determines the status code based on the score and feedback message.\n\n Args:\n score: The numeric score (0.0 to 1.0)\n feedback: The feedback message from the execution\n\n Returns:\n str: Status code ('CE', 'MLE', 'TLE', 'WA', 'RE', 'AC', or 'PA')\n \"\"\"\n if score == 0.0:\n if \"Compilation error\" in feedback:\n return \"CE\"\n elif \"Memory limit exceeded\" in feedback:\n return \"MLE\"\n elif \"Time limit exceeded\" in feedback:\n return \"TLE\"\n elif \"Output isn't correct\" in feedback:\n return \"WA\"\n else:\n return \"RE\"\n elif score == 1.0:\n return \"AC\"\n else:\n return \"PA\"\n\n\nasync def score_single_test_case(\n client: PistonClient, subtask: dict, test_name: str, test_input: str, test_output: str, submission: str\n) -> TestResult:\n \"\"\"\n Scores a single test case by running the submission against the provided input and output.\n\n Args:\n client: PistonClient instance for executing code\n subtask: Dictionary containing subtask configuration\n test_name: Name of the test case\n test_input: Input data for the test case\n test_output: Expected output for the test case\n submission: Source code of the submission\n\n Returns:\n TestResult: Result of the test case execution\n \"\"\"\n # Run submission for this test case\n score, feedback = await run_submission(client, subtask, test_input, submission, test_output)\n score = float(score)\n\n return TestResult(\n test_name=test_name, score=score, status=_extract_single_status(score, feedback), feedback=feedback\n )\n\n\nasync def score_subtask(\n client: PistonClient,\n subtask: dict,\n submission: str,\n test_case_run_cache: Union[dict, None] = None,\n test_batch_size: int = 1,\n) -> SubtaskResult:\n \"\"\"\n Scores all test cases in a subtask.\n\n Args:\n client: PistonClient instance for executing code\n subtask: Dictionary containing subtask configuration\n test_cases: Dictionary mapping test names to (input, output) tuples\n submission: Source code of the submission\n test_case_run_cache: Optional cache of previously run test cases\n test_batch_size: evaluate these many test cases in parallel, then check if any of them failed (0 score): if so stop evaluating; otherwise continue with the next batch of test cases.\n -1 to evaluate all test cases in parallel\n Returns:\n SubtaskResult: Result of the subtask evaluation\n \"\"\"\n subtask_result = SubtaskResult(\n problem=subtask[\"id\"],\n subtask=subtask[\"subtask\"],\n points=subtask[\"score\"],\n score_precision=subtask[\"score_precision\"],\n test_results=[],\n )\n\n # tests that are not cached\n tests_to_run = [\n (ti, test_name)\n for ti, test_name in enumerate(subtask[\"test_names\"])\n if test_case_run_cache is None or test_name not in test_case_run_cache\n ]\n\n # initialize test results with cached results or empty (SKIPPED) TestResult objects\n subtask_result.test_results = [\n test_case_run_cache[test_name]\n if test_case_run_cache is not None and test_name in test_case_run_cache\n else TestResult(test_name=test_name)\n for test_name in subtask[\"test_names\"]\n ]\n\n # we skip submissions where no code was extracted\n # no need to do anything, as we have a failed cached result\n if not submission or any(\n test_result.status != \"SKIPPED\" and test_result.score == 0.0 for test_result in subtask_result.test_results\n ):\n return subtask_result\n\n if \"test_cases\" in subtask:\n test_cases = subtask[\"test_cases\"]\n if isinstance(subtask[\"test_cases\"], list):\n test_cases = {test_name: test for test_name, test in zip(subtask[\"test_names\"], subtask[\"test_cases\"])}\n else:\n test_cases = load_ioi_tests(subtask[\"year\"], subtask[\"id\"])\n\n # run one batch, check if any of them failed (0 score): if so stop evaluating; otherwise continue with the next batch of test cases.\n for test_batch_to_run in batched(tests_to_run, test_batch_size):\n results = await asyncio.gather(\n *[\n asyncio.create_task(\n score_single_test_case(\n client, subtask, test_name, test_cases[test_name][0], test_cases[test_name][1], submission\n )\n )\n for _, test_name in test_batch_to_run\n ]\n )\n for (ti, test_name), test_result in zip(test_batch_to_run, results):\n if test_case_run_cache is not None:\n test_case_run_cache[test_name] = test_result\n subtask_result.test_results[ti] = test_result\n\n # Stop early if it failed\n if any(test_result.score == 0.0 for test_result in results):\n break\n\n return subtask_result\n\n\nasync def score_subtasks(\n client: PistonClient, subtasks: list[dict], submission: str, skip_mode: bool = True\n) -> list[SubtaskResult]:\n \"\"\"\n Scores multiple subtasks for a submission.\n\n Args:\n client: PistonClient instance for executing code\n subtasks: List of dictionaries containing subtask configurations\n submission: Source code of the submission\n skip_mode: If True, evaluates test by test and stops after the first failure. Otherwise, runs all tests in parallel. Should be True when evaluating a large number of submissions.\n\n Returns:\n list[SubtaskResult]: Results for all subtasks\n \"\"\"\n # avoid rerunning tests present in multiple subtasks\n test_case_run_cache = {}\n\n return [await score_subtask(client, subtask, submission, test_case_run_cache, skip_mode) for subtask in subtasks]\n\n\nasync def run_submission(\n client: PistonClient, problem: dict, test_input: str, submission: str, test_output: str | None = None\n) -> tuple[str, str]:\n \"\"\"\n Executes a submission against a test case using the Piston execution environment.\n\n Args:\n client: PistonClient instance for executing code\n problem: Dictionary containing problem configuration\n test_input: Input data for the test case\n submission: Source code of the submission\n test_output: Optional expected output for the test case\n\n Returns:\n tuple[str, str]: A tuple containing (score, feedback)\n \"\"\"\n data = {\n \"files\": [\n # the actual submission\n {\"name\": f\"graders/{problem['id'].lower()}.cpp\", \"content\": submission},\n # pass the input\n {\"name\": \"input.txt\", \"content\": test_input},\n # pass the expected output\n *([{\"name\": \"correct_output.txt\", \"content\": test_output}] if test_output else []),\n # grader files\n *({\"name\": name, \"content\": content} for name, content in problem[\"grader_files\"] if content),\n ],\n \"run_timeout\": round(\n (problem[\"time_limit\"] + 3) * 1000\n ), # +3 seconds hard limit. time limits are handled by the ioi script\n \"run_memory_limit\": problem[\"memory_limit\"],\n }\n return await execute_ioi(client, data)\n\n\nasync def execute_ioi(client, data) -> tuple[str, str]:\n \"\"\"\n Requests to the IOI package return the score as a float in the stdout, as well as optional feedback/errors in stderr.\n Returns a tuple of (score, feedback).\n \"\"\"\n response = await client.send_execute(data)\n\n if \"message\" in response:\n raise PistonError(response[\"message\"])\n\n if \"compile\" in response and response[\"compile\"][\"code\"] != 0:\n return \"0\", \"Compilation error exit code \" + str(response[\"compile\"][\"code\"]) + \"\\n\" + response[\"compile\"][\n \"stderr\"\n ]\n\n if \"run\" not in response:\n raise PistonError(response)\n\n if response[\"run\"][\"code\"] == 1 and \"MemoryError\" in response[\"run\"][\"stderr\"]:\n return \"0\", \"Memory limit exceeded\"\n\n # successful result\n if response[\"run\"][\"stdout\"]:\n return response[\"run\"][\"stdout\"], response[\"run\"][\"stderr\"]\n\n if response[\"run\"][\"signal\"] == \"SIGKILL\":\n return \"0\", \"Time limit exceeded\"\n\n # other issues\n if response[\"run\"][\"code\"] != 0:\n raise PistonError(\n f\"language={response['language']}, version={response['version']}, exit code={response['run']['code']}, stderr={response['run']['stderr']}, signal={response['run']['signal']}\"\n )\n return \"0\", \"Unknown error\"\n"], ["/open-r1/src/open_r1/utils/callbacks.py", "#!/usr/bin/env python\n# coding=utf-8\n# Copyright 2025 The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport subprocess\nfrom typing import List\n\nfrom transformers import TrainerCallback\nfrom transformers.trainer_callback import TrainerControl, TrainerState\nfrom transformers.training_args import TrainingArguments\n\nfrom .evaluation import run_benchmark_jobs\nfrom .hub import push_to_hub_revision\n\n\ndef is_slurm_available() -> bool:\n # returns true if a slurm queueing system is available\n try:\n subprocess.run([\"sinfo\"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n return True\n except FileNotFoundError:\n return False\n\n\nclass DummyConfig:\n def __init__(self, **kwargs):\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n\nclass PushToHubRevisionCallback(TrainerCallback):\n def __init__(self, model_config) -> None:\n self.model_config = model_config\n\n def on_save(\n self,\n args: TrainingArguments,\n state: TrainerState,\n control: TrainerControl,\n **kwargs,\n ):\n if state.is_world_process_zero:\n global_step = state.global_step\n\n # WARNING: if you use dataclasses.replace(args, ...) the accelerator dist state will be broken, so I do this workaround\n # Also if you instantiate a new SFTConfig, the accelerator dist state will be broken\n dummy_config = DummyConfig(\n hub_model_id=args.hub_model_id,\n hub_model_revision=f\"{args.hub_model_revision}-step-{global_step:09d}\",\n output_dir=f\"{args.output_dir}/checkpoint-{global_step}\",\n system_prompt=args.system_prompt,\n )\n\n future = push_to_hub_revision(\n dummy_config, extra_ignore_patterns=[\"*.pt\"]\n ) # don't push the optimizer states\n\n if is_slurm_available():\n dummy_config.benchmarks = args.benchmarks\n\n def run_benchmark_callback(_):\n print(f\"Checkpoint {global_step} pushed to hub.\")\n run_benchmark_jobs(dummy_config, self.model_config)\n\n future.add_done_callback(run_benchmark_callback)\n\n\nCALLBACKS = {\n \"push_to_hub_revision\": PushToHubRevisionCallback,\n}\n\n\ndef get_callbacks(train_config, model_config) -> List[TrainerCallback]:\n callbacks = []\n for callback_name in train_config.callbacks:\n if callback_name not in CALLBACKS:\n raise ValueError(f\"Callback {callback_name} not found in CALLBACKS.\")\n callbacks.append(CALLBACKS[callback_name](model_config))\n\n return callbacks\n"], ["/open-r1/src/open_r1/utils/code_providers.py", "# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Code execution providers for executing and evaluating code snippets.\"\"\"\n\nimport abc\nimport asyncio\nfrom typing import List, Optional\n\nfrom ..utils import is_e2b_available, is_morph_available\n\n\nif is_e2b_available():\n from e2b_code_interpreter import AsyncSandbox\n from e2b_code_interpreter.models import Execution\n\n from .routed_sandbox import RoutedSandbox\nelse:\n AsyncSandbox = None\n Execution = None\n RoutedSandbox = None\n\nif is_morph_available():\n from morphcloud.api import MorphCloudClient\n from morphcloud.sandbox import Sandbox\n\n from .routed_morph import RoutedMorphSandbox\nelse:\n MorphCloudClient = None\n Sandbox = None\n RoutedMorphSandbox = None\n\n\nclass CodeExecutionProvider(abc.ABC):\n \"\"\"Abstract base class for code execution providers.\"\"\"\n\n @abc.abstractmethod\n def execute_scripts(self, scripts: List[str], languages: List[str]) -> List[float]:\n \"\"\"Execute multiple scripts and return their reward values.\n\n Args:\n scripts: List of code scripts to execute\n language: The programming language of the scripts\n\n Returns:\n List of float rewards (one per script)\n \"\"\"\n pass\n\n\nclass E2BProvider(CodeExecutionProvider):\n \"\"\"Provider that executes code using E2B sandboxes.\"\"\"\n\n def __init__(self, num_parallel: int = 2, e2b_router_url: Optional[str] = None):\n \"\"\"Initialize the E2B provider.\n\n Args:\n num_parallel: Number of parallel sandboxes to use\n e2b_router_url: URL for the E2B router (if using router mode)\n \"\"\"\n if not is_e2b_available():\n raise ImportError(\n \"E2B is not available and required for this provider. Please install E2B with \"\n \"`pip install e2b-code-interpreter` and add an API key to a `.env` file.\"\n )\n\n self.num_parallel = num_parallel\n self.e2b_router_url = e2b_router_url\n\n def execute_scripts(self, scripts: List[str], languages: List[str]) -> List[float]:\n \"\"\"Execute scripts using E2B sandboxes.\n\n If e2b_router_url is provided, uses the RoutedSandbox for batch processing.\n Otherwise, uses direct AsyncSandbox with parallelization.\n \"\"\"\n if self.e2b_router_url is not None:\n routed_sandbox = RoutedSandbox(router_url=self.e2b_router_url)\n\n executions = routed_sandbox.run_code(\n scripts=scripts,\n languages=languages,\n timeout=30,\n request_timeout=28,\n )\n\n rewards = []\n for execution in executions:\n try:\n reward = float(execution.text)\n rewards.append(reward)\n except Exception:\n rewards.append(None)\n return rewards\n\n try:\n rewards = self._run_async_from_sync(scripts, languages, self.num_parallel)\n except Exception as e:\n print(f\"Error from E2B executor: {e}\")\n rewards = [0.0] * len(scripts)\n\n return rewards\n\n def _run_async_from_sync(self, scripts: List[str], languages: List[str], num_parallel: int) -> List[float]:\n \"\"\"Function wrapping the `_run_async` function.\"\"\"\n try:\n rewards = asyncio.run(self._run_async(scripts, languages, num_parallel))\n except Exception as e:\n print(f\"Error from E2B executor async: {e}\")\n raise e\n\n return rewards\n\n async def _run_async(self, scripts: List[str], languages: List[str], num_parallel: int) -> List[float]:\n semaphore = asyncio.Semaphore(num_parallel)\n\n tasks = [self._run_script(script, languages, semaphore) for script in scripts]\n\n results = await asyncio.gather(*tasks)\n rewards = list(results)\n\n return rewards\n\n async def _run_script(self, script: str, languages: List[str], semaphore: asyncio.Semaphore) -> float:\n # We set a timeout margin, as the AsyncSandbox timeout does not seem to work\n # These values are based on running 256 examples with the gold solution\n # from open-r1/verifiable-coding-problems-python_decontaminated\n # see scripts/benchmark_e2b.py\n\n SANDBOX_TIMEOUT = 30\n MARGIN = 2\n REQUEST_TIMEOUT = SANDBOX_TIMEOUT - MARGIN\n ASYNCIO_TIMEOUT = SANDBOX_TIMEOUT + MARGIN\n\n async with semaphore:\n try:\n sandbox = await AsyncSandbox.create(timeout=SANDBOX_TIMEOUT, request_timeout=REQUEST_TIMEOUT)\n execution = await asyncio.wait_for(\n sandbox.run_code(script, languages=languages),\n timeout=ASYNCIO_TIMEOUT,\n )\n return float(execution.text)\n except (TypeError, ValueError):\n return 0.0\n except asyncio.TimeoutError:\n print(\"Operation timed out\")\n return 0.0\n except Exception as e:\n print(f\"Error in `_run_script` from E2B sandbox ID {sandbox.sandbox_id} : {e}\")\n return 0.0\n finally:\n try:\n await sandbox.kill()\n except Exception as e:\n print(f\"Error from E2B executor kill with sandbox ID {sandbox.sandbox_id} : {e}\")\n\n\nclass MorphProvider(CodeExecutionProvider):\n \"\"\"Provider that executes code using MorphCloud's Sandbox API.\"\"\"\n\n def __init__(self, num_parallel: int = 2, morph_router_url: Optional[str] = None):\n \"\"\"Initialize the Morph provider.\n\n Args:\n num_parallel: Number of parallel executions to use\n morph_router_url: URL for the MorphCloud router (if using router mode)\n \"\"\"\n if not is_morph_available():\n raise ImportError(\n \"MorphCloud is not available and required for this provider. Please install MorphCloud with \"\n \"`pip install morphcloud` and add an API key to a `.env` file.\"\n )\n\n try:\n from dotenv import load_dotenv\n\n load_dotenv()\n except ImportError:\n print(\"Warning: python-dotenv not installed. Environment variables must be set directly.\")\n\n self.num_parallel = num_parallel\n self.morph_router_url = morph_router_url\n\n if self.morph_router_url is not None:\n self.routed_sandbox = RoutedMorphSandbox(router_url=self.morph_router_url)\n return\n\n import os\n\n self.api_key = os.getenv(\"MORPH_API_KEY\")\n if not self.api_key:\n raise ValueError(\"MorphCloud API key not found. Please set the MORPH_API_KEY environment variable.\")\n\n try:\n self.client = MorphCloudClient(api_key=self.api_key)\n self.Sandbox = Sandbox\n except ImportError as e:\n raise ImportError(f\"Required MorphCloud dependencies not installed: {e}\")\n\n def execute_scripts(self, scripts: List[str], languages: List[str]) -> List[float]:\n \"\"\"Execute scripts using MorphCloud Sandbox API.\n\n Args:\n scripts: List of Python scripts to execute\n language: Programming language\n\n Returns:\n List of float rewards (one per script)\n \"\"\"\n\n if hasattr(self, \"routed_sandbox\"):\n try:\n results = self.routed_sandbox.run_code(\n scripts=scripts,\n languages=languages,\n timeout=90,\n request_timeout=96,\n )\n\n rewards = []\n for result in results:\n try:\n reward = float(result.text)\n rewards.append(reward)\n except (ValueError, AttributeError):\n rewards.append(0.0)\n return rewards\n except Exception as e:\n print(f\"Error from MorphCloud router: {e}\")\n return [0.0] * len(scripts)\n\n import asyncio\n\n try:\n rewards = asyncio.run(self._run_async(scripts, languages, self.num_parallel))\n except Exception as e:\n print(f\"Error from MorphCloud executor: {e}\")\n rewards = [0.0] * len(scripts)\n\n return rewards\n\n async def _run_async(self, scripts: List[str], languages: List[str], num_parallel: int) -> List[float]:\n \"\"\"Run multiple scripts concurrently with limited parallelism.\n\n Args:\n scripts: List of scripts to execute\n language: Programming language\n num_parallel: Maximum number of concurrent executions\n\n Returns:\n List of rewards\n \"\"\"\n\n semaphore = asyncio.Semaphore(num_parallel)\n\n tasks = [self._run_script(script, languages, semaphore) for script in scripts]\n\n results = await asyncio.gather(*tasks)\n\n return list(results)\n\n async def _run_script(self, script: str, languages: List[str], semaphore: asyncio.Semaphore) -> float:\n \"\"\"Execute a single script in a MorphCloud Sandbox.\n\n Args:\n script: The script to execute\n language: Programming language\n semaphore: Semaphore to limit concurrency\n\n Returns:\n Float reward from script execution\n \"\"\"\n SANDBOX_TIMEOUT = 90\n MARGIN = 6\n ASYNCIO_TIMEOUT = SANDBOX_TIMEOUT + MARGIN\n\n sandbox = None\n async with semaphore:\n try:\n sandbox = await asyncio.to_thread(self.Sandbox.new, client=self.client, ttl_seconds=SANDBOX_TIMEOUT)\n result = await asyncio.wait_for(\n asyncio.to_thread(\n sandbox.run_code,\n script,\n languages=languages,\n timeout=SANDBOX_TIMEOUT,\n ),\n timeout=ASYNCIO_TIMEOUT,\n )\n\n reward = 0.0\n try:\n if hasattr(result, \"text\") and result.text:\n lines = result.text.strip().split(\"\\n\")\n if lines:\n try:\n reward = float(lines[-1])\n except ValueError:\n try:\n reward = float(result.text.strip())\n except ValueError:\n pass\n elif hasattr(result, \"stdout\") and result.stdout:\n lines = result.stdout.strip().split(\"\\n\")\n if lines:\n try:\n reward = float(lines[-1])\n except ValueError:\n pass\n except (ValueError, AttributeError):\n pass\n\n return reward\n\n except asyncio.TimeoutError:\n return 0.0\n except Exception:\n return 0.0\n finally:\n if sandbox:\n try:\n await asyncio.to_thread(sandbox.close)\n await asyncio.to_thread(sandbox.shutdown)\n except Exception:\n pass\n\n\ndef get_provider(provider_type: str = \"e2b\", **kwargs) -> CodeExecutionProvider:\n \"\"\"Factory function to get the appropriate code execution provider.\n\n Args:\n provider_type: Type of provider to use (\"e2b\", \"morph\")\n **kwargs: Additional arguments to pass to the provider\n\n Returns:\n An instance of CodeExecutionProvider\n \"\"\"\n num_parallel = kwargs.pop(\"num_parallel\", 2)\n\n if provider_type == \"e2b\":\n # Extract E2B-specific arguments\n e2b_router_url = kwargs.pop(\"e2b_router_url\", None)\n return E2BProvider(\n num_parallel=num_parallel,\n e2b_router_url=e2b_router_url,\n )\n elif provider_type == \"morph\":\n # Extract Morph-specific arguments\n morph_router_url = kwargs.pop(\"morph_router_url\", None)\n return MorphProvider(\n num_parallel=num_parallel,\n morph_router_url=morph_router_url,\n )\n else:\n raise ValueError(f\"Unknown provider type: {provider_type}\")\n"], ["/open-r1/src/open_r1/utils/competitive_programming/cf_scoring.py", "import asyncio\nimport os\nfrom io import BytesIO\nfrom typing import Literal\n\nfrom async_lru import alru_cache\n\nfrom .piston_client import PistonClient\nfrom .utils import batched\n\n\nasync def score_single_test_case(\n client: PistonClient,\n problem_data: dict,\n test_input: str,\n test_output: str,\n submission: str,\n submission_language: str = \"cpp\",\n) -> tuple[str, str]:\n if submission_language not in [\"python\", \"cpp\"]:\n raise ValueError(f\"Invalid submission language: {submission_language}\")\n try:\n result = await client.send_execute(\n {\n \"files\": [\n {\"name\": f\"main.{submission_language}\", \"content\": submission},\n *(\n [{\"name\": \"checker.py\", \"content\": problem_data[\"generated_checker\"]}]\n if problem_data[\"generated_checker\"]\n else []\n ),\n {\"name\": \"input.txt\", \"content\": test_input},\n {\"name\": \"correct_output.txt\", \"content\": test_output},\n {\n \"name\": \"grader_config\",\n \"content\": \"\\n\".join(\n f\"{key}={value}\"\n for key, value in {\n \"TIME_LIMIT\": problem_data[\"time_limit\"],\n \"MEMORY_LIMIT\": problem_data[\"memory_limit\"],\n \"INPUT_MODE\": problem_data[\"input_mode\"],\n }.items()\n ),\n },\n ],\n \"run_timeout\": (problem_data[\"time_limit\"] + 10) * 1000,\n # +10 seconds hard limit. time limits are handled by the codeforces script\n },\n language=\"cf_python3\" if submission_language == \"python\" else \"c++17\",\n )\n except Exception as e:\n print(f\"Error scoring submission: {e}\")\n return False\n\n return result\n\n\n@alru_cache(maxsize=32) # TODO make this configurable\nasync def get_generated_contest_tests(contest_id: str) -> list[dict]:\n import pandas as pd\n\n import aiofiles\n import aiofiles.os\n\n tests_folder = os.environ.get(\"CF_TESTS_FOLDER\", None)\n if not tests_folder:\n raise ValueError(\n \"CF_TESTS_FOLDER environment variable not set! Please download the codeforces generated tests and set CF_TESTS_FOLDER to the folder path. See https://huggingface.co/datasets/open-r1/codeforces for more information.\"\n )\n if not await aiofiles.os.path.exists(tests_folder):\n raise ValueError(\n f\"CF_TESTS_FOLDER path '{tests_folder}' does not exist! Please download the codeforces generated tests and set CF_TESTS_FOLDER to the folder path. See https://huggingface.co/datasets/open-r1/codeforces for more information.\"\n )\n parquet_path = os.path.join(tests_folder, f\"test_cases_{int(contest_id):04d}.parquet\")\n if not await aiofiles.os.path.exists(parquet_path):\n return {}\n\n # Read parquet file asynchronously\n async with aiofiles.open(parquet_path, \"rb\") as f:\n content = await f.read()\n df = pd.read_parquet(BytesIO(content))\n\n # Group by problem_id and convert to dictionary of lists\n grouped_tests = df.groupby(\"problem_id\").apply(lambda x: x[[\"input\", \"output\"]].to_dict(\"records\")).to_dict()\n\n return grouped_tests\n\n\nasync def get_generated_tests(problem_id: str) -> list[dict]:\n contest_id = problem_id.split(\"/\")[0]\n return (await get_generated_contest_tests(contest_id)).get(problem_id, [])\n\n\nasync def score_submission(\n client: PistonClient,\n problem_data: dict,\n submission: str,\n test_batch_size: int = 1,\n scoring_mode: Literal[\"pass_fail\", \"partial\", \"weighted_sum\"] = \"weighted_sum\",\n no_compile_reward: float = -0.1,\n no_submission_reward: float = -1.0,\n submission_language: str = \"cpp\",\n) -> float:\n if submission_language not in [\"python\", \"cpp\"]:\n raise ValueError(f\"Invalid submission language: {submission_language}\")\n test_cases = problem_data[\"official_tests\"] + (await get_generated_tests(problem_data[\"id\"]))\n # invalid/not a coding problem\n if test_cases is None or len(test_cases) == 0:\n return None\n # no code extracted\n if not submission:\n return no_submission_reward\n\n passed_test_cases = 0\n # run one batch, check if any of them failed (0 score): if so stop evaluating (assuming non partial score); otherwise continue with the next batch of test cases.\n for test_batch_to_run in batched(test_cases, test_batch_size) if test_batch_size >= 1 else [test_cases]:\n results = await asyncio.gather(\n *[\n asyncio.create_task(\n score_single_test_case(\n client, problem_data, test_case[\"input\"], test_case[\"output\"], submission, submission_language\n )\n )\n for test_case in test_batch_to_run\n ]\n )\n if any(result and result[\"compile\"][\"code\"] != 0 for result in results):\n return no_compile_reward\n\n tests_passed_results = [\n result and result[\"run\"][\"code\"] == 0 and result[\"run\"][\"stdout\"].strip() == \"1\" for result in results\n ]\n if scoring_mode == \"pass_fail\" and any(not test_passed for test_passed in tests_passed_results):\n break\n passed_test_cases += sum(1 for test_passed in tests_passed_results if test_passed)\n\n pass_fail_score = 1.0 if passed_test_cases == len(test_cases) else 0.0\n\n if scoring_mode == \"pass_fail\":\n return pass_fail_score\n elif scoring_mode == \"partial\":\n return passed_test_cases / len(test_cases)\n elif scoring_mode == \"weighted_sum\":\n return pass_fail_score + 0.1 * (passed_test_cases / len(test_cases))\n else:\n raise ValueError(f\"Invalid scoring mode: {scoring_mode}\")\n"], ["/open-r1/scripts/benchmark_e2b.py", "# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nBenchmark script for the code_reward function with E2B.\n\nThis script measures the performance of the code_reward function with varying numbers\nof samples and parallelization levels.\n\nEach sample is a CodeForces problem with a gold standard solution that is executed against a set of public test cases.\n\"\"\"\n\nfrom datasets import load_dataset\nimport time\nfrom tqdm.auto import tqdm\n\nfrom dotenv import load_dotenv\nload_dotenv()\n\nfrom open_r1.rewards import code_reward\n\ndef benchmark_code_reward(example):\n start_time = time.time()\n test_completions = [[{\"content\": example[\"gold_standard_solution\"]}]]\n reward_kwargs = {\"verification_info\": [example[\"verification_info\"]]}\n rewards = code_reward(test_completions, **reward_kwargs)\n end_time = time.time()\n example[\"test_reward\"] = rewards[0]\n example[\"reward_time\"] = end_time - start_time\n return example\n\nif __name__ == \"__main__\":\n parallel_dict = {\n 16:[1,4,16],\n 64:[4,16, 64],\n 256:[16, 64, 96], # cap at 96 as PRO account is limited to 100\n }\n # Store results for table formatting\n results = []\n \n for num_samples in tqdm([16, 64,256], desc=\"Benchmarking samples\"):\n for num_parallel in parallel_dict[num_samples]:\n code_dataset = load_dataset(\"open-r1/verifiable-coding-problems-python_decontaminated\")\n code_dataset = code_dataset[\"train\"].shuffle(seed=42).select(range(num_samples))\n\n test_completions = [[{\"content\": example[\"gold_standard_solution\"]}] for example in code_dataset]\n reward_kwargs = {\"verification_info\": [example[\"verification_info\"] for example in code_dataset]}\n\n start_time = time.time()\n rewards = code_reward(test_completions, num_parallel=num_parallel, **reward_kwargs)\n execution_time = time.time() - start_time\n \n # Calculate some statistics about rewards\n mean_reward = sum(rewards) / len(rewards)\n min_reward = min(rewards)\n max_reward = max(rewards)\n \n # Store results\n results.append({\n \"num_samples\": num_samples,\n \"num_parallel\": num_parallel,\n \"execution_time\": execution_time,\n \"mean_reward\": mean_reward,\n \"min_reward\": min_reward,\n \"max_reward\": max_reward\n })\n \n print(\"\\n## Benchmark Results\\n\")\n print(\"| Sample Size | Parallelization | Execution Time (s) | Mean Reward | Min Reward | Max Reward |\")\n print(\"|:-----------:|:---------------:|------------------:|:-----------:|:-----------:|:-----------:|\")\n \n for result in results:\n print(f\"| {result['num_samples']:^11} | {result['num_parallel']:^15} | {result['execution_time']:17.2f} | {result['mean_reward']:^11.4f} | {result['min_reward']:^11.4f} | {result['max_reward']:^11.4f} |\")\n \n"], ["/open-r1/src/open_r1/utils/competitive_programming/piston_client.py", "import asyncio\nimport os\nimport random\nimport re\nimport subprocess\nfrom collections import Counter\nfrom functools import lru_cache\n\nimport aiohttp\n\n\nclass PistonError(Exception):\n pass\n\n\n@lru_cache(maxsize=1)\ndef get_piston_client_from_env(session=None):\n piston_endpoints = os.getenv(\"PISTON_ENDPOINTS\")\n if piston_endpoints is None:\n raise ValueError(\n \"For IOI/CF problems Piston endpoints running our IOI package are required. Please add a list of valid Piston endpoints to a PISTON_ENDPOINTS variable in a `.env` file.\"\n )\n piston_endpoints = sorted(\n piston_endpoints.split(\",\") if piston_endpoints != \"slurm\" else get_slurm_piston_endpoints()\n )\n gpu_nb = int(os.getenv(\"LOCAL_RANK\", 0)) # per‑GPU index\n world = int(os.getenv(\"WORLD_SIZE\", 1)) # total GPUs\n if world > 1:\n print(f\"Using a subset of piston endpoints for GPU#{gpu_nb}\")\n piston_endpoints = piston_endpoints[gpu_nb::world]\n random.shuffle(piston_endpoints)\n max_requests_per_endpoint = os.getenv(\"PISTON_MAX_REQUESTS_PER_ENDPOINT\", \"1\")\n return PistonClient(piston_endpoints, session, max_requests_per_endpoint=int(max_requests_per_endpoint))\n\n\nclass PistonClient:\n \"\"\"\n A client that will automatically load balance across multiple Piston (https://github.com/engineer-man/piston) workers.\n This assumes piston is running our custom cms_ioi package: https://github.com/guipenedo/piston/releases/\n We recommend starting the instances with the following script as otherwise some IOI problems will hit default limits:\n ```\n export PISTON_COMPILE_TIMEOUT=60000\n export PISTON_RUN_TIMEOUT=60000\n export PISTON_OUTPUT_MAX_SIZE=1000000000\n export PISTON_MAX_FILE_SIZE=1000000000\n export PISTON_DISABLE_NETWORKING=true\n export PISTON_REPO_URL=https://github.com/guipenedo/piston/releases/download/pkgs/index\n mkdir /piston\n\n sed -i '/app.use(body_parser.urlencoded/c\\ app.use(body_parser.urlencoded({ extended: true, limit: \\\"512mb\\\" }));' src/index.js\n sed -i '/app.use(body_parser.json/c\\ app.use(body_parser.json({ limit: \\\"512mb\\\" }));' src/index.js\n\n # Start server in background\n node src```\n\n Piston docs for API usage: https://piston.readthedocs.io/en/latest/api-v2/\n \"\"\"\n\n def __init__(\n self,\n base_endpoint: str | list[str] = \"http://ip-10-53-80-65:3223/api/v2\",\n session=None,\n max_requests_per_endpoint=1,\n ):\n self.max_requests_per_endpoint = max_requests_per_endpoint\n self.base_endpoints = [base_endpoint] if isinstance(base_endpoint, str) else base_endpoint\n if len(self.base_endpoints) == 0:\n raise ValueError(\"No Piston endpoints provided. Please check your PISTON_ENDPOINTS environment variable.\")\n self.endpoint_ids = {endpoint: i for i, endpoint in enumerate(self.base_endpoints)}\n\n self._session = session\n self.endpoint_tokens = asyncio.Queue(maxsize=max_requests_per_endpoint * len(self.base_endpoints))\n\n for _ in range(max_requests_per_endpoint):\n for base_endpoint in self.base_endpoints:\n self.endpoint_tokens.put_nowait(base_endpoint)\n self._endpoint_failures = Counter()\n self._unhealthy_endpoints = set()\n self._endpoint_failures_lock = asyncio.Lock()\n\n @property\n def session(self):\n if self._session is None:\n self._session = aiohttp.ClientSession(\n timeout=aiohttp.ClientTimeout(sock_read=30),\n connector=aiohttp.TCPConnector(\n limit=self.max_requests_per_endpoint * len(self.base_endpoints),\n ttl_dns_cache=300,\n keepalive_timeout=5 * 60,\n ),\n )\n return self._session\n\n async def _wait_for_endpoint(self):\n endpoint = await self.endpoint_tokens.get()\n return endpoint\n\n async def _release_endpoint(self, endpoint):\n await self.endpoint_tokens.put(endpoint)\n\n async def _send_request(self, endpoint, route, data=None, method=\"post\"):\n async with self.session.request(\n method, f\"{endpoint.rstrip('/')}/{route}\", json=data, headers={\"Content-Type\": \"application/json\"}\n ) as response:\n return await response.json(content_type=None)\n\n async def _send_to_all(self, route, data=None, method=\"post\"):\n return await asyncio.gather(\n *[self._send_request(endpoint, route, data, method) for endpoint in self.base_endpoints]\n )\n\n async def _send_to_one(self, endpoint, route, data=None, method=\"post\"):\n return await self._send_request(endpoint, route, data, method)\n\n async def install_package(self, language, version):\n return await self._send_to_all(\"packages\", {\"language\": language, \"version\": version}, method=\"post\")\n\n async def uninstall_package(self, language, version):\n return await self._send_to_all(\"packages\", {\"language\": language, \"version\": version}, method=\"delete\")\n\n async def get_supported_runtimes(self):\n return await self._send_to_all(\"runtimes\", method=\"get\")\n\n async def _check_failed_endpoint(self, endpoint):\n async with self._endpoint_failures_lock:\n if endpoint in self._unhealthy_endpoints:\n return\n try:\n await asyncio.sleep(5)\n await self.get_supported_runtimes()\n except Exception as e:\n print(f\"Error checking endpoint {endpoint}, dropping it ({e})\")\n self._unhealthy_endpoints.add(endpoint)\n if len(self._unhealthy_endpoints) >= len(self.base_endpoints):\n raise PistonError(\"All endpoints are unhealthy. Please check your Piston workers.\")\n\n async def send_execute(self, data, language=\"cms_ioi\", max_retries=5):\n data = data | {\n \"language\": language,\n \"version\": \"*\",\n }\n\n base_delay = 1.0\n\n status = None\n endpoint = None\n\n for attempt in range(max_retries + 1):\n try:\n endpoint = await self._wait_for_endpoint()\n if attempt > 0:\n await asyncio.sleep(1)\n async with self.session.post(\n f\"{endpoint.rstrip('/')}/execute\", json=data, headers={\"Content-Type\": \"application/json\"}\n ) as response:\n status = response.status\n res_json = await response.json(content_type=None)\n\n if status != 200:\n raise PistonError(f\"Server error. status={status}. {res_json}\")\n if res_json is None:\n raise PistonError(f\"Empty response. status={status}\")\n # piston overloaded\n if \"run\" in res_json and \"Resource temporarily unavailable\" in res_json[\"run\"].get(\"stderr\", \"\"):\n raise PistonError(f\"Piston overloaded: {res_json['run']['stderr']}\")\n return res_json\n\n except (PistonError, asyncio.TimeoutError, aiohttp.ClientConnectionError, RuntimeError) as e:\n # Only retry if we haven't reached max retries yet\n if attempt < max_retries:\n # Calculate backoff with jitter\n delay = min(base_delay * (2**attempt), 10) # Exponential backoff, capped at 10 seconds\n jitter = delay * 0.2 * (2 * asyncio.get_event_loop().time() % 1 - 0.5) # Add ±10% jitter\n retry_delay = delay + jitter\n print(f\"Retrying in {retry_delay:.2f} seconds [{self.endpoint_ids[endpoint]}] {endpoint} - {e}\")\n\n # special case: worker died\n if isinstance(e, aiohttp.ClientConnectionError) and \"Connect call failed\" in str(e):\n await self._check_failed_endpoint(endpoint)\n else:\n # hopefully we won't get this one again\n await self._release_endpoint(endpoint)\n endpoint = None\n\n await asyncio.sleep(retry_delay)\n else:\n await self._check_failed_endpoint(endpoint)\n except Exception as e:\n print(f\"Propagating exception {type(e)}: {e}\")\n raise e\n finally:\n # Ensure endpoint is always released, even if an exception occurs\n if endpoint is not None:\n try:\n await self._release_endpoint(endpoint)\n except Exception as e:\n print(f\"Error releasing endpoint {endpoint}: {e}\")\n endpoint = None\n\n\ndef get_slurm_piston_endpoints():\n \"\"\"Get list of active piston worker endpoints from squeue output\"\"\"\n # Run squeue command to get job name, hostname and status, filtering for RUNNING state\n result = subprocess.run(\n [\"squeue\", '--format=\"%j %N %T\"', \"--noheader\", \"--states=RUNNING\"], capture_output=True, text=True\n )\n\n # Split output into lines and skip header\n lines = result.stdout.strip().split(\"\\n\")\n\n endpoints = []\n for line in lines:\n # Parse job name from squeue output\n fields = line.split()\n job_name = fields[0].strip('\"') # Remove quotes\n hostname = fields[1]\n\n # Extract port if job name matches pattern\n match = re.match(r\"piston-worker-(\\d+)\", job_name)\n if match:\n port = match.group(1)\n endpoints.append(f\"http://{hostname}:{port}/api/v2\")\n\n return endpoints\n"], ["/open-r1/src/open_r1/utils/evaluation.py", "import subprocess\nfrom typing import TYPE_CHECKING, Dict, Union\n\nfrom .hub import get_gpu_count_for_vllm, get_param_count_from_repo_id\n\n\nif TYPE_CHECKING:\n from trl import GRPOConfig, SFTConfig, ModelConfig\n\nimport base64\nimport os\n\n\n# We need a special environment setup to launch vLLM from within Slurm training jobs.\n# - Reference code: https://github.com/huggingface/brrr/blob/c55ba3505686d690de24c7ace6487a5c1426c0fd/brrr/lighteval/one_job_runner.py#L105\n# - Slack thread: https://huggingface.slack.com/archives/C043JTYE1MJ/p1726566494958269\nuser_home_directory = os.path.expanduser(\"~\")\nVLLM_SLURM_PREFIX = [\n \"env\",\n \"-i\",\n \"bash\",\n \"-c\",\n f\"for f in /etc/profile.d/*.sh; do source $f; done; export HOME={user_home_directory}; sbatch \",\n]\n\n\ndef register_lighteval_task(\n configs: Dict[str, str],\n eval_suite: str,\n task_name: str,\n task_list: str,\n num_fewshot: int = 0,\n):\n \"\"\"Registers a LightEval task configuration.\n\n - Core tasks can be added from this table: https://github.com/huggingface/lighteval/blob/main/src/lighteval/tasks/tasks_table.jsonl\n - Custom tasks that require their own metrics / scripts, should be stored in scripts/evaluation/extended_lighteval_tasks\n\n Args:\n configs (Dict[str, str]): The dictionary to store the task configuration.\n eval_suite (str, optional): The evaluation suite.\n task_name (str): The name of the task.\n task_list (str): The comma-separated list of tasks in the format \"extended|{task_name}|{num_fewshot}|0\" or \"lighteval|{task_name}|{num_fewshot}|0\".\n num_fewshot (int, optional): The number of few-shot examples. Defaults to 0.\n is_custom_task (bool, optional): Whether the task is a custom task. Defaults to False.\n \"\"\"\n # Format task list in lighteval format\n task_list = \",\".join(f\"{eval_suite}|{task}|{num_fewshot}|0\" for task in task_list.split(\",\"))\n configs[task_name] = task_list\n\n\nLIGHTEVAL_TASKS = {}\n\nregister_lighteval_task(LIGHTEVAL_TASKS, \"lighteval\", \"math_500\", \"math_500\", 0)\nregister_lighteval_task(LIGHTEVAL_TASKS, \"lighteval\", \"aime24\", \"aime24\", 0)\nregister_lighteval_task(LIGHTEVAL_TASKS, \"lighteval\", \"aime25\", \"aime25\", 0)\nregister_lighteval_task(LIGHTEVAL_TASKS, \"lighteval\", \"gpqa\", \"gpqa:diamond\", 0)\nregister_lighteval_task(LIGHTEVAL_TASKS, \"extended\", \"lcb\", \"lcb:codegeneration\", 0)\nregister_lighteval_task(LIGHTEVAL_TASKS, \"extended\", \"lcb_v4\", \"lcb:codegeneration_v4\", 0)\n\n\ndef get_lighteval_tasks():\n return list(LIGHTEVAL_TASKS.keys())\n\n\nSUPPORTED_BENCHMARKS = get_lighteval_tasks()\n\n\ndef run_lighteval_job(\n benchmark: str,\n training_args: Union[\"SFTConfig\", \"GRPOConfig\"],\n model_args: \"ModelConfig\",\n) -> None:\n task_list = LIGHTEVAL_TASKS[benchmark]\n model_name = training_args.hub_model_id\n model_revision = training_args.hub_model_revision\n # For large models >= 30b params or those running the MATH benchmark, we need to shard them across the GPUs to avoid OOM\n num_gpus = get_gpu_count_for_vllm(model_name, model_revision)\n if get_param_count_from_repo_id(model_name) >= 30_000_000_000:\n tensor_parallel = True\n else:\n num_gpus = 2 # Hack while cluster is full\n tensor_parallel = False\n\n cmd = VLLM_SLURM_PREFIX.copy()\n cmd_args = [\n f\"--gres=gpu:{num_gpus}\",\n f\"--job-name=or1_{benchmark}_{model_name.split('/')[-1]}_{model_revision}\",\n \"slurm/evaluate.slurm\",\n benchmark,\n f'\"{task_list}\"',\n model_name,\n model_revision,\n f\"{tensor_parallel}\",\n f\"{model_args.trust_remote_code}\",\n ]\n if training_args.system_prompt is not None:\n # encode to base64 to avoid issues with special characters\n # we decode in the sbatch script\n prompt_encoded = base64.b64encode(training_args.system_prompt.encode()).decode()\n cmd_args.append(prompt_encoded)\n cmd[-1] += \" \" + \" \".join(cmd_args)\n subprocess.run(cmd, check=True)\n\n\ndef run_benchmark_jobs(training_args: Union[\"SFTConfig\", \"GRPOConfig\"], model_args: \"ModelConfig\") -> None:\n benchmarks = training_args.benchmarks\n if len(benchmarks) == 1 and benchmarks[0] == \"all\":\n benchmarks = get_lighteval_tasks()\n # Evaluate on all supported benchmarks. Later we may want to include a `chat` option\n # that just evaluates on `ifeval` and `mt_bench` etc.\n\n for benchmark in benchmarks:\n print(f\"Launching benchmark `{benchmark}`\")\n if benchmark in get_lighteval_tasks():\n run_lighteval_job(benchmark, training_args, model_args)\n else:\n raise ValueError(f\"Unknown benchmark {benchmark}\")\n"], ["/open-r1/scripts/run_benchmarks.py", "# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom dataclasses import dataclass, field\nfrom typing import List, Optional\n\nfrom open_r1.utils.evaluation import SUPPORTED_BENCHMARKS, run_benchmark_jobs\nfrom open_r1.configs import SFTConfig\nfrom trl import ModelConfig, TrlParser\n\n\n@dataclass\nclass ScriptArguments:\n model_id: str = field(\n default=\"deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B\",\n metadata={\"help\": \"The Hub model id to push the model to.\"},\n )\n model_revision: str = field(default=\"main\", metadata={\"help\": \"The Hub model branch to push the model to.\"})\n trust_remote_code: bool = field(default=False, metadata={\"help\": \"Trust the remote code.\"})\n benchmarks: List[str] = field(\n default_factory=lambda: [], metadata={\"help\": \"The benchmarks to run after training.\"}\n )\n list_benchmarks: bool = field(default=False, metadata={\"help\": \"List all supported benchmarks.\"})\n system_prompt: Optional[str] = field(\n default=None, metadata={\"help\": \"The system prompt to use for the benchmark.\"}\n )\n\n\ndef main():\n parser = TrlParser(ScriptArguments)\n args = parser.parse_args_and_config()[0]\n if args.list_benchmarks:\n print(\"Supported benchmarks:\")\n for benchmark in SUPPORTED_BENCHMARKS:\n print(f\" - {benchmark}\")\n return\n benchmark_args = SFTConfig(\n output_dir=\"\",\n hub_model_id=args.model_id,\n hub_model_revision=args.model_revision,\n benchmarks=args.benchmarks,\n system_prompt=args.system_prompt,\n )\n run_benchmark_jobs(\n benchmark_args,\n ModelConfig(model_name_or_path=\"\", model_revision=\"\", trust_remote_code=args.trust_remote_code),\n )\n\n\nif __name__ == \"__main__\":\n main()\n"], ["/open-r1/src/open_r1/utils/routed_morph.py", "# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import List, Optional\n\nimport requests\n\n\nclass RoutedMorphSandbox:\n \"\"\"\n Client for the MorphCloud router service that mimics the API of MorphCloud's Sandbox.\n\n This class provides a simple interface to execute code via a central MorphCloud router,\n which manages sandbox creation and cleanup. It allows batch processing of multiple scripts\n in a single request for improved efficiency.\n\n Attributes:\n router_url (str): The URL of the MorphCloud router service.\n timeout (int): Execution timeout in seconds.\n request_timeout (int): HTTP request timeout in seconds.\n \"\"\"\n\n def __init__(self, router_url: str, timeout: int = 300, request_timeout: int = 60):\n \"\"\"\n Initialize the routed MorphCloud sandbox client.\n\n Args:\n router_url: The URL of the MorphCloud router, including host and port.\n timeout: Default execution timeout in seconds.\n request_timeout: Default HTTP request timeout in seconds.\n \"\"\"\n self.router_url = router_url\n self.timeout = timeout\n self.request_timeout = request_timeout\n\n def run_code(\n self,\n scripts: List[str],\n languages: Optional[List[str]] = None,\n timeout: Optional[int] = None,\n request_timeout: Optional[int] = None,\n ) -> List:\n \"\"\"\n Execute multiple scripts using MorphCloud via the router.\n\n Args:\n scripts: List of code scripts to execute.\n languages: List of programming languages for each script. If None, defaults to Python for all scripts.\n timeout: Execution timeout in seconds. If None, uses the instance timeout.\n request_timeout: HTTP request timeout in seconds. If None, uses the instance request_timeout.\n\n Returns:\n List of execution results with text and exception_str properties.\n \"\"\"\n\n actual_timeout = timeout if timeout is not None else self.timeout\n actual_request_timeout = request_timeout if request_timeout is not None else self.request_timeout\n\n # Default to Python for all scripts if languages is not provided\n if languages is None:\n languages = [\"python\"] * len(scripts)\n\n payload = {\n \"scripts\": scripts,\n \"languages\": languages,\n \"timeout\": actual_timeout,\n \"request_timeout\": actual_request_timeout,\n }\n\n try:\n endpoint = f\"http://{self.router_url}/execute_batch\"\n response = requests.post(endpoint, json=payload, timeout=actual_request_timeout)\n\n if response.status_code != 200:\n error = f\"Request to MorphCloud router failed with status code: {response.status_code}\"\n print(error)\n\n results = []\n for _ in scripts:\n results.append(type(\"obj\", (object,), {\"text\": None, \"exception_str\": error}))\n return results\n\n response_data = response.json()\n results = []\n\n for item in response_data:\n # Log the response data to see what we're getting\n # print(f\"RoutedMorphSandbox: Got response item: {item}\")\n result = type(\n \"obj\",\n (object,),\n {\n \"text\": item.get(\"text\"),\n \"exception_str\": item.get(\"exception_str\"),\n },\n )\n results.append(result)\n\n return results\n\n except Exception as e:\n error = f\"Error communicating with MorphCloud router: {str(e)}\"\n print(error)\n\n results = []\n for _ in scripts:\n results.append(type(\"obj\", (object,), {\"text\": None, \"exception_str\": error}))\n return results\n"], ["/open-r1/src/open_r1/utils/routed_sandbox.py", "# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import List, Optional\n\nimport requests\nfrom e2b_code_interpreter.models import Execution, ExecutionError, Result\n\n\nclass RoutedSandbox:\n \"\"\"\n A sandbox environment that routes code execution requests to the E2B Router.\n This class is designed for batched execution of scripts, primarily for Python code.\n It mimics the usage of 'Sandbox' from 'e2b_code_interpreter', but adds support for batch processing.\n\n Attributes:\n router_url (str): The URL of the E2B Router to which code execution requests are sent.\n \"\"\"\n\n def __init__(self, router_url: str):\n \"\"\"\n Initializes the RoutedSandbox with the specified router URL.\n\n Args:\n router_url (str): The URL of the E2B Router.\n \"\"\"\n self.router_url = router_url\n\n def run_code(\n self,\n scripts: list[str],\n languages: Optional[List[str]] = None,\n timeout: Optional[int] = None,\n request_timeout: Optional[int] = None,\n ) -> list[Execution]:\n \"\"\"\n Executes a batch of scripts in the sandbox environment.\n\n Args:\n scripts (list[str]): A list of code scripts to execute.\n languages (list[str], optional): List of programming languages for each script. If None, defaults to Python for all scripts.\n timeout (Optional[int], optional): The maximum execution time for each script in seconds. Defaults to 300 seconds.\n request_timeout (Optional[int], optional): The timeout for the HTTP request in seconds. Defaults to 30 seconds.\n\n Returns:\n list[Execution]: A list of Execution objects containing the results, logs, and errors (if any) for each script.\n \"\"\"\n # Set default values for timeouts if not provided\n if timeout is None:\n timeout = 300 # Default to 5 minutes\n if request_timeout is None:\n request_timeout = 30 # Default to 30 seconds\n\n # Default to Python for all scripts if languages is not provided\n if languages is None:\n languages = [\"python\"] * len(scripts)\n\n # Prepare the payload for the HTTP POST request\n payload = {\n \"scripts\": scripts,\n \"languages\": languages,\n \"timeout\": timeout,\n \"request_timeout\": request_timeout,\n }\n\n # Send the request to the E2B Router\n response = requests.post(f\"http://{self.router_url}/execute_batch\", json=payload)\n if not response.ok:\n print(f\"Request failed with status code: {response.status_code}\")\n\n # Parse the response and construct Execution objects\n results = response.json()\n output = []\n for result in results:\n if result[\"execution\"] is None:\n # If execution is None, create an empty Execution object\n # This can happen when a script times out or fails to execute\n execution = Execution()\n else:\n execution = Execution(\n results=[Result(**r) for r in result[\"execution\"][\"results\"]],\n logs=result[\"execution\"][\"logs\"],\n error=(ExecutionError(**result[\"execution\"][\"error\"]) if result[\"execution\"][\"error\"] else None),\n execution_count=result[\"execution\"][\"execution_count\"],\n )\n output.append(execution)\n\n return output\n\n\nif __name__ == \"__main__\":\n # for local testing launch an E2B router with: python scripts/e2b_router.py\n sbx = RoutedSandbox(router_url=\"0.0.0.0:8000\")\n codes = [\"print('hello world')\", \"print('hello world)\"]\n executions = sbx.run_code(codes) # Execute Python inside the sandbox\n\n print(executions)\n"], ["/open-r1/src/open_r1/utils/competitive_programming/ioi_utils.py", "from collections import defaultdict\nfrom functools import lru_cache\n\nfrom datasets import load_dataset\n\n\ndef add_includes(code: str, problem_id: str) -> str:\n \"\"\"\n Fix common compilation errors for IOI problems.\n \"\"\"\n if not code:\n return code\n # has most of the useful functions\n code_header = \"#include \\n\"\n # include the problem header\n problem_header_include = f'#include \"{problem_id}.h\"'\n if problem_header_include not in code:\n code_header += problem_header_include + \"\\n\"\n # use namespace std since models forget std:: often\n if \"using namespace std;\" not in code and \"std::\" not in code:\n code_header += \"\\nusing namespace std;\\n\\n\"\n return code_header + code\n\n\n@lru_cache\ndef load_ioi_tests_for_year(year: int) -> dict[str, dict[str, tuple[str, str]]]:\n \"\"\"\n Load IOI tests for a given year.\n \"\"\"\n tests_dataset = load_dataset(\"open-r1/ioi-test-cases\", name=f\"{year}\", split=\"train\")\n test_cases = defaultdict(dict)\n for test_case in tests_dataset:\n test_cases[test_case[\"problem_id\"]][test_case[\"test_name\"]] = test_case[\"test_input\"], test_case[\"test_output\"]\n return test_cases\n\n\ndef load_ioi_tests(year: int, problem_id: str) -> dict[str, tuple[str, str]]:\n \"\"\"\n Load IOI tests for a given year and problem id.\n \"\"\"\n return load_ioi_tests_for_year(year)[problem_id]\n"], ["/open-r1/scripts/get_tensor_parallel_size.py", "import argparse\nfrom transformers import AutoConfig\nfrom math import gcd\n\ndef get_tensor_parallel_size(model_name: str, revision: str = None, default_tp: int = 8) -> int:\n try:\n config = AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=True)\n num_heads = getattr(config, 'num_attention_heads', None)\n\n if num_heads is not None and num_heads % default_tp != 0:\n tp = gcd(num_heads, default_tp)\n return max(tp, 1)\n else:\n return default_tp\n except Exception as e:\n print(f\"Warning: Failed to fetch config for {model_name}@{revision}: {e}\")\n return default_tp\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model_name\", type=str, required=True, help=\"Hugging Face model name or path\")\n parser.add_argument(\"--revision\", type=str, default=None, help=\"Model revision if applicable\")\n parser.add_argument(\"--default_tp\", type=int, default=8, help=\"Default TP size (usually GPUs per node)\")\n\n args = parser.parse_args()\n\n tp = get_tensor_parallel_size(args.model_name, args.revision, args.default_tp)\n print(tp)\n"], ["/open-r1/src/open_r1/utils/model_utils.py", "import torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizer\n\nfrom trl import ModelConfig, get_kbit_device_map, get_quantization_config\n\nfrom ..configs import GRPOConfig, SFTConfig\n\n\ndef get_tokenizer(model_args: ModelConfig, training_args: SFTConfig | GRPOConfig) -> PreTrainedTokenizer:\n \"\"\"Get the tokenizer for the model.\"\"\"\n tokenizer = AutoTokenizer.from_pretrained(\n model_args.model_name_or_path,\n revision=model_args.model_revision,\n trust_remote_code=model_args.trust_remote_code,\n )\n\n if training_args.chat_template is not None:\n tokenizer.chat_template = training_args.chat_template\n\n return tokenizer\n\n\ndef get_model(model_args: ModelConfig, training_args: SFTConfig | GRPOConfig) -> AutoModelForCausalLM:\n \"\"\"Get the model\"\"\"\n torch_dtype = (\n model_args.torch_dtype if model_args.torch_dtype in [\"auto\", None] else getattr(torch, model_args.torch_dtype)\n )\n quantization_config = get_quantization_config(model_args)\n model_kwargs = dict(\n revision=model_args.model_revision,\n trust_remote_code=model_args.trust_remote_code,\n attn_implementation=model_args.attn_implementation,\n torch_dtype=torch_dtype,\n use_cache=False if training_args.gradient_checkpointing else True,\n device_map=get_kbit_device_map() if quantization_config is not None else None,\n quantization_config=quantization_config,\n )\n model = AutoModelForCausalLM.from_pretrained(\n model_args.model_name_or_path,\n **model_kwargs,\n )\n return model\n"], ["/open-r1/src/open_r1/utils/competitive_programming/code_patcher.py", "import re\n\n\ndef fix_python3_imports(source_code):\n \"\"\"\n Fix common import and function changes between Python 3 versions\n\n Args:\n source_code (str): The Python source code to update\n\n Returns:\n str: The updated source code\n \"\"\"\n # Dictionary of patterns to replacements\n replacements = [\n # Fix collections.abc imports (changed in Python 3.3+)\n (\n r\"from collections import (Mapping|Sequence|Set|Container|MutableMapping|MutableSet|MutableSequence)\",\n r\"from collections.abc import \\1\",\n ),\n # Fix imp module deprecation (deprecated in 3.4)\n (r\"import imp\", r\"import importlib\"),\n # Fix asyncio.async() to asyncio.ensure_future() (renamed in 3.4.4)\n (r\"asyncio\\.async\\(\", r\"asyncio.ensure_future(\"),\n # Fix inspect.getargspec to inspect.getfullargspec (deprecated in 3.5)\n (r\"inspect\\.getargspec\", r\"inspect.getfullargspec\"),\n # Fix array.array 'c' type code to 'b' (removed in 3.9)\n (r\"array\\.array\\('c'\", r\"array.array('b'\"),\n # Fix backslash line continuation with multiple newlines (Python-specific issue)\n (r\"\\\\(\\r\\n|\\r|\\n)+\", \"\\\\\\n\"),\n # some solutions use getlogin() to check if they are debugging or on an actual submission\n (r\"(?:os\\s*\\.\\s*)?getlogin\\s*\\(\\s*\\)\", \"False\"),\n # Fix usage of fractions.gcd (moved to math in 3.5)\n # 1. Fix direct usage: fractions.gcd -> math.gcd\n (r\"\\bfractions\\.gcd\\b\", r\"math.gcd\"),\n # 2. Fix 'from fractions import gcd, X' -> 'from fractions import X' (start/middle)\n (r\"(from\\s+fractions\\s+import\\s+(?:\\([^)]*)?)\\bgcd\\s*,\\s*\", r\"\\1\"),\n # 3. Fix 'from fractions import X, gcd' -> 'from fractions import X' (end)\n (r\"(from\\s+fractions\\s+import\\s+.*?\\S)\\s*,\\s*\\bgcd(\\s*\\)?\\s*(?:#.*)?)\", r\"\\1\\2\"),\n # 4. Fix standalone 'from fractions import gcd' -> 'from math import gcd'\n (r\"from\\s+fractions\\s+import\\s+\\(?\\s*gcd\\s*\\)?\", r\"\"),\n # --- End: Replacement for the faulty line ---\n ]\n\n lines = source_code.splitlines()\n last_import = max(\n [\n i\n for i, line in enumerate(lines)\n if line.strip().startswith(\"import\") or (line.strip().startswith(\"from\") and \"import\" in line)\n ],\n default=0,\n )\n import_section = \"\\n\".join(lines[: last_import + 1])\n main_source = \"\\n\".join(lines[last_import:])\n\n if \"fractions.gcd\" in source_code and \"import math\" not in source_code:\n import_section += \"\\nimport math\"\n elif \"gcd\" in source_code and \"from math import gcd\" not in source_code:\n import_section += \"\\nfrom math import gcd\"\n\n if \"set_int_max_str_digits\" not in source_code:\n import_section += \"\\nimport sys\\nsys.set_int_max_str_digits(0)\"\n\n source_code = import_section + \"\\n\" + main_source\n\n # Apply each replacement\n for pattern, replacement in replacements:\n source_code = re.sub(pattern, replacement, source_code)\n\n source_code = source_code.rstrip(\"\\\\\")\n\n return source_code\n\n\ndef fix_cpp_includes(source_code):\n # has most of the useful functions\n code_header = \"#include \\n\"\n # use namespace std since models forget std:: often\n if \"using namespace std;\" not in source_code and \"std::\" not in source_code:\n code_header += \"\\nusing namespace std;\\n\\n\"\n return code_header + source_code\n\n\ndef is_patchable(lang):\n return lang in (\"python\", \"python3\", \"Python 3\", \"PyPy 3\", \"PyPy 3-64\", \"cpp\") or \"C++\" in lang\n\n\ndef patch_code(text, lang):\n if not text:\n return text\n if lang in (\"python\", \"python3\", \"Python 3\", \"PyPy 3\", \"PyPy 3-64\"):\n return fix_python3_imports(text)\n elif \"cpp\" in lang or \"C++\" in lang:\n return fix_cpp_includes(text)\n return text\n\n\ntests = [\n \"\"\"read = lambda: map(int, input().split())\nn, m, z = read()\nfrom fractions import gcd\nans = z // (n * m // gcd(n, m))\nprint(ans)\"\"\",\n \"\"\"from fractions import Fraction,gcd\n\na,b,c,d = [int(x) for x in input().split()]\n\nif a*d > b*c:\n num = a*d-b*c\n denom = a*d\nelse:\n num = b*c-a*d\n denom = b*c\ndiv = gcd(num,denom)\nprint('%d/%d'%(num//div,denom//div))\"\"\",\n]\n\nif __name__ == \"__main__\":\n for test in tests:\n print(\"ORIGINAL:\", test, sep=\"\\n\\n\")\n print(\"PATCHED:\", patch_code(test, \"Python 3\"), sep=\"\\n\\n\")\n print(\"=\" * 50)\n"], ["/open-r1/src/open_r1/utils/__init__.py", "from .data import get_dataset\nfrom .import_utils import is_e2b_available, is_morph_available\nfrom .model_utils import get_model, get_tokenizer\n\n\n__all__ = [\"get_tokenizer\", \"is_e2b_available\", \"is_morph_available\", \"get_model\", \"get_dataset\"]\n"], ["/open-r1/src/open_r1/utils/import_utils.py", "# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom transformers.utils.import_utils import _is_package_available\n\n\n# Use same as transformers.utils.import_utils\n_e2b_available = _is_package_available(\"e2b\")\n\n\ndef is_e2b_available() -> bool:\n return _e2b_available\n\n\n_morph_available = _is_package_available(\"morphcloud\")\n\n\ndef is_morph_available() -> bool:\n return _morph_available\n"], ["/open-r1/src/open_r1/utils/competitive_programming/__init__.py", "from .cf_scoring import score_submission\nfrom .code_patcher import patch_code\nfrom .ioi_scoring import SubtaskResult, score_subtask, score_subtasks\nfrom .ioi_utils import add_includes\nfrom .morph_client import get_morph_client_from_env\nfrom .piston_client import get_piston_client_from_env, get_slurm_piston_endpoints\n\n\n__all__ = [\n \"get_piston_client_from_env\",\n \"get_slurm_piston_endpoints\",\n \"get_morph_client_from_env\",\n \"patch_code\",\n \"score_submission\",\n \"score_subtask\",\n \"score_subtasks\",\n \"add_includes\",\n \"SubtaskResult\",\n]\n"], ["/open-r1/src/open_r1/utils/competitive_programming/utils.py", "from itertools import islice\n\n\ndef batched(iterable, n):\n \"Batch data into lists of length n. The last batch may be shorter.\"\n # batched('ABCDEFG', 3) --> ABC DEF G\n if n < 1:\n return iterable\n it = iter(iterable)\n while batch := list(islice(it, n)):\n yield batch\n"], ["/open-r1/src/open_r1/__init__.py", "# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n"]], "task_instance_info": {"created_time": "2025-08-20 15:37:07", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Conditionally load either a single dataset or combine multiple datasets with weighted sampling, apply column selection and data splitting configurations, then return formatted training data based on provided parameters."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```python\n[TASK_BEGIN]\n if not args.dataset_name:\n logger.error(\"Dataset name(s) must be provided in configuration.\")\n raise ValueError(\"Dataset name(s) must be provided in configuration.\")\n \n loaded_datasets = []\n \n for dataset_name in args.dataset_name:\n dataset = datasets.load_dataset(\n dataset_name,\n split=args.dataset_config.split,\n data_dir=args.dataset_config.data_dir,\n cache_dir=args.cache_dir,\n )\n loaded_datasets.append(dataset)\n \n if len(loaded_datasets) > 1:\n combined_dataset = concatenate_datasets(loaded_datasets)\n else:\n combined_dataset = loaded_datasets[0]\n \n return DatasetDict(train=combined_dataset)\n[TASK_END]\n```", "inference_time": "2025-08-20 15-37-35"}, "editdistance_info": {"edit_distance": 11.75, "calculate_time": "2025-08-20 15:37:35", "true_code_clean": "if args.dataset_name and not args.dataset_mixture:\n logger.info(f\"Loading dataset: {args.dataset_name}\")\n return datasets.load_dataset(args.dataset_name, args.dataset_config)\n elif args.dataset_mixture:\n logger.info(f\"Creating dataset mixture with {len(args.dataset_mixture.datasets)} datasets\")\n seed = args.dataset_mixture.seed\n datasets_list = []\n for dataset_config in args.dataset_mixture.datasets:\n logger.info(f\"Loading dataset for mixture: {dataset_config.id} (config: {dataset_config.config})\")\n ds = datasets.load_dataset(\n dataset_config.id,\n dataset_config.config,\n split=dataset_config.split,\n )\n if dataset_config.columns is not None:\n ds = ds.select_columns(dataset_config.columns)\n if dataset_config.weight is not None:\n ds = ds.shuffle(seed=seed).select(range(int(len(ds) * dataset_config.weight)))\n logger.info(\n f\"Subsampled dataset '{dataset_config.id}' (config: {dataset_config.config}) with weight={dataset_config.weight} to {len(ds)} examples\"\n )\n datasets_list.append(ds)\n if datasets_list:\n combined_dataset = concatenate_datasets(datasets_list)\n combined_dataset = combined_dataset.shuffle(seed=seed)\n logger.info(f\"Created dataset mixture with {len(combined_dataset)} examples\")\n if args.dataset_mixture.test_split_size is not None:\n combined_dataset = combined_dataset.train_test_split(\n test_size=args.dataset_mixture.test_split_size, seed=seed\n )\n logger.info(\n f\"Split dataset into train and test sets with test size: {args.dataset_mixture.test_split_size}\"\n )\n return combined_dataset\n else:\n return DatasetDict({\"train\": combined_dataset})\n else:\n raise ValueError(\"No datasets were loaded from the mixture configuration\")\n else:\n raise ValueError(\"Either `dataset_name` or `dataset_mixture` must be provided\")", "predict_code_clean": "if not args.dataset_name:\n logger.error(\"Dataset name(s) must be provided in configuration.\")\n raise ValueError(\"Dataset name(s) must be provided in configuration.\")\n loaded_datasets = []\n for dataset_name in args.dataset_name:\n dataset = datasets.load_dataset(\n dataset_name,\n split=args.dataset_config.split,\n data_dir=args.dataset_config.data_dir,\n cache_dir=args.cache_dir,\n )\n loaded_datasets.append(dataset)\n if len(loaded_datasets) > 1:\n combined_dataset = concatenate_datasets(loaded_datasets)\n else:\n combined_dataset = loaded_datasets[0]\n return DatasetDict(train=combined_dataset)"}}